import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import { LogIn, Eye, EyeOff } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { resolvePostLoginRedirect } from "@/lib/cmsPageAccess";
import { redirectFromSearch, sanitizeRedirectPath } from "@/lib/authRedirect";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import orionLogo from "@/assets/orion-logo.svg";
import sparkHorse from "@/assets/spark-horse.png";

function loginErrorMessage(reason: string): string {
  switch (reason) {
    case "invalid_credentials":
      return "Invalid username or password";
    case "csrf":
      return "Your session expired. Please refresh the page and try again.";
    case "network":
      return "Unable to reach the server. Check your connection and try again.";
    default:
      return "Sign in failed. Please try again.";
  }
}

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { login, isAuthenticated, loading } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const redirectTarget = sanitizeRedirectPath(
    (location.state as { from?: string } | null)?.from ?? redirectFromSearch(location.search)
  );

  useEffect(() => {
    if (loading || !isAuthenticated) return;
    let cancelled = false;
    resolvePostLoginRedirect(redirectTarget).then((destination) => {
      if (!cancelled) navigate(destination, { replace: true });
    });
    return () => {
      cancelled = true;
    };
  }, [isAuthenticated, loading, navigate, redirectTarget]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSubmitting(true);
    try {
      const result = await login(username.trim(), password);
      if (result.ok) {
        const destination = await resolvePostLoginRedirect(redirectTarget);
        navigate(destination, { replace: true });
      } else {
        setError(loginErrorMessage(result.reason));
      }
    } catch {
      setError(loginErrorMessage("network"));
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <p className="text-muted-foreground font-display">Loading…</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="w-full max-w-md"
      >
        <div className="bg-card rounded-2xl shadow-xl border border-border p-8 space-y-6">
          <div className="flex flex-col items-center gap-3">
            <img src={orionLogo} alt="Orion Logo" className="h-10" />
            <img src={sparkHorse} alt="Spark" className="h-24" />
            <h1 className="font-display text-2xl font-bold text-foreground">
              Welcome to Spark
            </h1>
            <p className="text-muted-foreground text-sm text-center">
              Enter your credentials to access the dashboard
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Username</label>
              <Input
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="Enter username"
                required
                autoComplete="username"
              />
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Password</label>
              <div className="relative">
                <Input
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter password"
                  required
                  autoComplete="current-password"
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>

            {error && (
              <motion.p
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-destructive text-sm text-center"
              >
                {error}
              </motion.p>
            )}

            <Button type="submit" className="w-full gap-2" disabled={submitting}>
              <LogIn size={16} />
              {submitting ? "Signing in…" : "Sign In"}
            </Button>
          </form>
        </div>
      </motion.div>
    </div>
  );
};

export default Login;
