import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@context/AuthContext";
import { useTheme } from "@context/ThemeContext";
import toast from "react-hot-toast";
import { Music2, Fingerprint, Eye, Lock, User, Mail } from "lucide-react";
import {
  isBiometricAvailable,
  getBiometricType,
  authenticateWithBiometric,
  getBiometricCredential,
  hasBiometricRegistered,
} from "@utils/biometric";

export default function LoginPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [biometricAvailable, setBiometricAvailable] = useState(false);
  const [biometricType, setBiometricType] = useState("");
  const [showForgotPassword, setShowForgotPassword] = useState(false);

  const { login } = useAuth();
  const { isDark } = useTheme();
  const navigate = useNavigate();

  // Check biometric availability on mount
  useEffect(() => {
    checkBiometric();
  }, []);

  const checkBiometric = async () => {
    const available = await isBiometricAvailable();
    setBiometricAvailable(available);
    if (available) {
      setBiometricType(getBiometricType());
    }
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!username || !password) {
      setError("Please enter username and password");
      return;
    }

    setLoading(true);
    setError("");

    try {
      await login(username, password);
      toast.success("Welcome back!");
      navigate("/");
    } catch (err) {
      setError(err.message || "Invalid credentials");
    } finally {
      setLoading(false);
    }
  };

  // Handle biometric login
  const handleBiometricLogin = async () => {
    if (!username) {
      toast.error("Please enter your username first");
      return;
    }

    if (!hasBiometricRegistered(username)) {
      toast.error(
        "Biometric authentication not set up for this account. Please login with password first.",
      );
      return;
    }

    setLoading(true);
    setError("");

    try {
      const credentialId = getBiometricCredential(username);
      const assertion = await authenticateWithBiometric(credentialId);

      // Send assertion to server for verification
      const response = await fetch("/api/auth/biometric-login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, assertion }),
      });

      const data = await response.json();

      if (data.success) {
        // Store token and navigate
        localStorage.setItem("authToken", data.token);
        toast.success(`Welcome back! Authenticated with ${biometricType}`);
        navigate("/");
      } else {
        setError(data.message || "Biometric authentication failed");
      }
    } catch (err) {
      setError(err.message || "Biometric authentication failed");
      toast.error("Biometric authentication failed");
    } finally {
      setLoading(false);
    }
  };

  // Handle Enter key press
  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      handleSubmit(e);
    }
  };

  return (
    <div
      className={`min-h-screen flex items-center justify-center px-4 py-8 ${
        isDark
          ? "bg-gradient-to-br from-slate-950 via-purple-950 to-slate-950"
          : "bg-gradient-to-br from-blue-50 via-purple-50 to-blue-50"
      }`}
    >
      <div className="w-full max-w-md">
        {/* Main Login Card */}
        <div
          className={`backdrop-blur-xl rounded-3xl p-8 sm:p-10 shadow-2xl ${
            isDark
              ? "bg-white/10 border border-white/20"
              : "bg-white/90 border border-gray-200"
          }`}
        >
          {/* Logo and Title */}
          <div className="text-center mb-8">
            <div
              className={`inline-flex items-center justify-center w-20 h-20 rounded-2xl mb-4 ${
                isDark ? "bg-purple-500/20" : "bg-purple-100"
              }`}
            >
              <Music2
                size={40}
                className={isDark ? "text-purple-400" : "text-purple-600"}
              />
            </div>
            <h1
              className={`text-3xl sm:text-4xl font-bold mb-2 ${
                isDark ? "text-white" : "text-gray-900"
              }`}
            >
              Worship
            </h1>
            <p
              className={`text-sm ${
                isDark ? "text-white/60" : "text-gray-600"
              }`}
            >
              House of Praise Music Platform
            </p>
          </div>

          {/* Error Message */}
          {error && (
            <div
              role="alert"
              aria-live="assertive"
              className="bg-red-500/10 border border-red-500/30 text-red-500 px-4 py-3 rounded-xl mb-6 text-center text-sm"
            >
              {error}
            </div>
          )}

          {/* Login Form */}
          <form
            onSubmit={handleSubmit}
            className="space-y-5"
            aria-label="Login form"
          >
            {/* Username Field */}
            <div>
              <label
                htmlFor="username-input"
                className={`block text-sm font-medium mb-2 ${
                  isDark ? "text-white/80" : "text-gray-700"
                }`}
              >
                Username
              </label>
              <div className="relative">
                <User
                  size={20}
                  className={`absolute left-4 top-1/2 -translate-y-1/2 ${
                    isDark ? "text-white/40" : "text-gray-400"
                  }`}
                  aria-hidden="true"
                />
                <input
                  id="username-input"
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  onKeyPress={handleKeyPress}
                  className={`w-full pl-12 pr-4 py-3.5 rounded-xl border text-base transition-all focus:outline-none focus:ring-2 touch-manipulation ${
                    isDark
                      ? "bg-white/5 border-white/20 text-white placeholder-white/40 focus:border-purple-500/50 focus:ring-purple-500/20"
                      : "bg-white border-gray-300 text-gray-900 placeholder-gray-400 focus:border-purple-500 focus:ring-purple-500/20"
                  }`}
                  placeholder="Enter username"
                  autoComplete="username"
                  aria-required="true"
                  aria-describedby={error ? "login-error" : undefined}
                  autoFocus
                />
              </div>
            </div>

            {/* Password Field */}
            <div>
              <label
                htmlFor="password-input"
                className={`block text-sm font-medium mb-2 ${
                  isDark ? "text-white/80" : "text-gray-700"
                }`}
              >
                Password
              </label>
              <div className="relative">
                <Lock
                  size={20}
                  className={`absolute left-4 top-1/2 -translate-y-1/2 ${
                    isDark ? "text-white/40" : "text-gray-400"
                  }`}
                  aria-hidden="true"
                />
                <input
                  id="password-input"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onKeyPress={handleKeyPress}
                  className={`w-full pl-12 pr-4 py-3.5 rounded-xl border text-base transition-all focus:outline-none focus:ring-2 touch-manipulation ${
                    isDark
                      ? "bg-white/5 border-white/20 text-white placeholder-white/40 focus:border-purple-500/50 focus:ring-purple-500/20"
                      : "bg-white border-gray-300 text-gray-900 placeholder-gray-400 focus:border-purple-500 focus:ring-purple-500/20"
                  }`}
                  placeholder="Enter password"
                  autoComplete="current-password"
                  aria-required="true"
                  aria-describedby={error ? "login-error" : undefined}
                />
              </div>
            </div>

            {/* Forgot Password Link */}
            <div className="flex justify-end">
              <button
                type="button"
                onClick={() => setShowForgotPassword(true)}
                className={`text-sm font-medium transition-colors touch-manipulation ${
                  isDark
                    ? "text-purple-400 hover:text-purple-300"
                    : "text-purple-600 hover:text-purple-700"
                }`}
              >
                Forgot password?
              </button>
            </div>

            {/* Login Button */}
            <button
              type="submit"
              disabled={loading}
              className={`w-full py-3.5 rounded-xl font-semibold text-base transition-all transform active:scale-[0.98] touch-manipulation ${
                loading ? "opacity-50 cursor-not-allowed" : "hover:shadow-lg"
              } ${
                isDark
                  ? "bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-500 hover:to-blue-500 text-white"
                  : "bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white shadow-md"
              }`}
              aria-busy={loading}
              aria-label={
                loading ? "Signing in, please wait" : "Sign in to your account"
              }
            >
              {loading ? (
                <span className="flex items-center justify-center gap-2">
                  <div
                    className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"
                    aria-hidden="true"
                  ></div>
                  Signing in...
                </span>
              ) : (
                "Sign In"
              )}
            </button>
          </form>

          {/* Biometric Login */}
          {biometricAvailable && (
            <>
              <div className="relative my-6">
                <div className="absolute inset-0 flex items-center">
                  <div
                    className={`w-full border-t ${
                      isDark ? "border-white/10" : "border-gray-200"
                    }`}
                  ></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span
                    className={`px-4 ${
                      isDark
                        ? "bg-gray-900/50 text-white/60"
                        : "bg-white text-gray-500"
                    }`}
                  >
                    Or continue with
                  </span>
                </div>
              </div>

              <button
                type="button"
                onClick={handleBiometricLogin}
                disabled={loading || !username}
                className={`w-full py-3.5 rounded-xl font-medium text-base transition-all transform active:scale-[0.98] flex items-center justify-center gap-3 touch-manipulation ${
                  loading || !username ? "opacity-50 cursor-not-allowed" : ""
                } ${
                  isDark
                    ? "bg-white/10 hover:bg-white/20 text-white border border-white/20"
                    : "bg-gray-100 hover:bg-gray-200 text-gray-900 border border-gray-300"
                }`}
              >
                <Fingerprint size={20} />
                <span>Biometric Authentication</span>
              </button>
            </>
          )}
        </div>

        {/* Footer */}
        <p
          className={`text-center mt-6 text-sm ${
            isDark ? "text-white/50" : "text-gray-600"
          }`}
        >
          © 2026 House of Praise Church. All rights reserved.
        </p>
      </div>

      {/* Forgot Password Modal */}
      {showForgotPassword && (
        <div
          className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 z-50"
          onClick={() => setShowForgotPassword(false)}
        >
          <div
            className={`max-w-md w-full rounded-2xl p-8 ${
              isDark ? "bg-gray-800" : "bg-white"
            }`}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="text-center mb-6">
              <div
                className={`inline-flex items-center justify-center w-16 h-16 rounded-full mb-4 ${
                  isDark ? "bg-blue-500/20" : "bg-blue-100"
                }`}
              >
                <Mail
                  size={32}
                  className={isDark ? "text-blue-400" : "text-blue-600"}
                />
              </div>
              <h3
                className={`text-2xl font-bold mb-2 ${
                  isDark ? "text-white" : "text-gray-900"
                }`}
              >
                Reset Password
              </h3>
              <p
                className={`text-sm ${
                  isDark ? "text-white/60" : "text-gray-600"
                }`}
              >
                Contact your administrator to reset your password
              </p>
            </div>
            <button
              onClick={() => setShowForgotPassword(false)}
              className={`w-full py-3 rounded-xl font-medium transition-all touch-manipulation ${
                isDark
                  ? "bg-blue-600 hover:bg-blue-700 text-white"
                  : "bg-blue-600 hover:bg-blue-700 text-white"
              }`}
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
