"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { login, webauthnAuthOptions, webauthnAuthVerify } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useTranslation } from "@/lib/i18n";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [biometricLoading, setBiometricLoading] = useState(false);
  const [error, setError] = useState("");
  const [biometricAvailable, setBiometricAvailable] = useState(false);
  const [savedEmail, setSavedEmail] = useState("");
  const { setAuth } = useAuth();
  const { t } = useTranslation();
  const router = useRouter();

  useEffect(() => {
    // Check if WebAuthn is available
    if (typeof window !== "undefined" && window.PublicKeyCredential) {
      window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?.()
        .then(available => setBiometricAvailable(available))
        .catch(() => {});
    }
    // Load last used email for biometric
    const last = localStorage.getItem("taskteam_biometric_email");
    if (last) setSavedEmail(last);
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim()) {
      setError(t("auth.email"));
      return;
    }
    setLoading(true);
    setError("");
    try {
      const result = await login({ email: email.trim(), password: password || undefined });
      setAuth(result.data.token, result.data.user);
      router.push("/tasks");
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setLoading(false);
    }
  }

  async function handleBiometricLogin() {
    const biometricEmail = email.trim() || savedEmail;
    if (!biometricEmail) {
      setError("Zadejte email pro biometricke prihlaseni");
      return;
    }
    setBiometricLoading(true);
    setError("");
    try {
      // Get auth options from server
      const optionsRes = await webauthnAuthOptions(biometricEmail);
      const options = optionsRes.data;

      // Create PublicKey credential request
      const allowCredentials = (options.allowCredentials as Array<{ id: string; type: string }>).map(cred => ({
        id: base64urlToBuffer(cred.id),
        type: cred.type as PublicKeyCredentialType,
      }));

      const credential = await navigator.credentials.get({
        publicKey: {
          challenge: base64urlToBuffer(options.challenge as string),
          allowCredentials,
          timeout: 60000,
          userVerification: "required" as UserVerificationRequirement,
        },
      }) as PublicKeyCredential;

      if (!credential) throw new Error("Biometricke overeni selhalo");

      // Send credential_id to server to get JWT
      const credentialId = bufferToBase64url(credential.rawId);
      const result = await webauthnAuthVerify(credentialId);

      // Save email for next time
      localStorage.setItem("taskteam_biometric_email", biometricEmail);

      setAuth(result.data.token, result.data.user);
      router.push("/tasks");
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Biometricke prihlaseni selhalo";
      if (msg.includes("No biometric") || msg.includes("not found")) {
        setError("Pro tento ucet neni nastaveno biometricke prihlaseni. Nastavte ho v Nastaveni.");
      } else {
        setError(msg);
      }
    } finally {
      setBiometricLoading(false);
    }
  }

  return (
    <div className="min-h-[70vh] flex items-center justify-center">
      <div className="w-full max-w-sm">
        <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl p-6 shadow-sm">
          <h1 className="text-2xl font-bold text-center mb-6">{t("auth.login")}</h1>

          {error && (
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg text-sm mb-4">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">{t("auth.email")}</label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none"
                placeholder={t("auth.emailPlaceholder")}
                autoFocus
                autoComplete="email"
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">{t("auth.password")}</label>
              <div className="relative">
                <input
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none pr-10"
                  placeholder="******"
                  autoComplete="current-password"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-sm"
                  tabIndex={-1}
                >
                  {showPassword ? t("auth.hidePassword") : t("auth.showPassword")}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2.5 px-4 rounded-lg transition-colors disabled:opacity-50"
            >
              {loading ? t("common.loading") : t("auth.submit")}
            </button>
          </form>

          {/* Biometric Login */}
          {biometricAvailable && (
            <>
              <div className="flex items-center gap-3 my-4">
                <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
                <span className="text-xs text-gray-400 uppercase">nebo</span>
                <div className="flex-1 h-px bg-gray-200 dark:bg-gray-700" />
              </div>

              <button
                onClick={handleBiometricLogin}
                disabled={biometricLoading}
                className="w-full flex items-center justify-center gap-3 py-2.5 px-4 rounded-lg border-2 border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500 transition-colors disabled:opacity-50 bg-gray-50 dark:bg-gray-800/50"
              >
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="text-blue-600 dark:text-blue-400">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M7.864 4.243A7.5 7.5 0 0119.5 10.5c0 2.92-.556 5.709-1.568 8.268M5.742 6.364A7.465 7.465 0 004.5 10.5a48.667 48.667 0 00-1.418 8.773M11.997 3.001A7.5 7.5 0 0014.5 10.5c0 2.887-.543 5.649-1.533 8.19M9.003 3.001a7.5 7.5 0 00-2.497 7.499 48.12 48.12 0 01-.544 5M12 10.5a2.25 2.25 0 10-4.5 0 2.25 2.25 0 004.5 0z" />
                </svg>
                <span className="font-medium text-sm">
                  {biometricLoading ? "Overuji..." : "Face ID / Otisk prstu"}
                </span>
              </button>
              {savedEmail && !email && (
                <p className="text-xs text-gray-400 text-center mt-2">
                  Posledni ucet: {savedEmail}
                </p>
              )}
            </>
          )}

          <div className="mt-4 text-center">
            <Link href="/forgot-password" className="text-sm text-blue-600 hover:underline">
              {t("auth.forgotPassword")}
            </Link>
          </div>

          <p className="text-center text-sm text-muted mt-4">
            {t("auth.noAccount")}{" "}
            <Link href="/register" className="text-blue-600 hover:underline">
              {t("auth.registerBtn")}
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}

// --- WebAuthn buffer helpers ---
function base64urlToBuffer(base64url: string): ArrayBuffer {
  const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
  const pad = base64.length % 4 === 0 ? "" : "=".repeat(4 - (base64.length % 4));
  const binary = atob(base64 + pad);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  return bytes.buffer;
}

function bufferToBase64url(buffer: ArrayBuffer): string {
  const bytes = new Uint8Array(buffer);
  let binary = "";
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
