import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "../services/api";
import { useAuth } from "../hooks/useAuth";
import { usePageTitle } from "../hooks/usePageTitle";
import { toast } from "react-toastify";
import { motion } from "motion/react";
import { Rocket, Loader2 } from "lucide-react";

export function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [needsSetup, setNeedsSetup] = useState<boolean | null>(null);
  const { refresh } = useAuth();
  const navigate = useNavigate();
  usePageTitle(needsSetup ? "Create Admin Account" : "Sign In");

  useEffect(() => {
    api.auth.setupStatus().then(res => {
      setNeedsSetup(res.ok ? (res.data as any)?.needsSetup : false);
    });
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (needsSetup && password !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }
    setLoading(true);

    let res;
    if (needsSetup) {
      res = await api.auth.firstUser(username, password);
    } else {
      res = await api.auth.login(username, password);
    }

    setLoading(false);
    if (res.ok) {
      await refresh();
      navigate("/");
    } else {
      toast.error(res.message || (needsSetup ? "Failed to create account" : "Login failed"));
    }
  };

  if (needsSetup === null) {
    return <div className="min-h-screen flex items-center justify-center">
      <Loader2 size={32} className="animate-spin text-blue-600 dark:text-blue-400" />
    </div>;
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-slate-900 px-4">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="bg-white dark:bg-slate-800 shadow-xl rounded-2xl p-8 w-full max-w-sm"
      >
        <div className="text-center mb-6">
          <Rocket size={40} className="mx-auto mb-2 text-blue-600 dark:text-blue-400" />
          <h1 className="text-2xl font-bold">PR Previews</h1>
          {needsSetup ? (
            <p className="text-sm text-blue-600 dark:text-blue-400 mt-1 font-medium">Create your admin account</p>
          ) : (
            <p className="text-sm text-gray-500 dark:text-slate-400 mt-1">Sign in to manage your previews</p>
          )}
        </div>

        {needsSetup && (
          <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg text-xs text-blue-700 dark:text-blue-300">
            This is the first time setup. Create the founder admin account.
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Username</label>
            <input
              type="text"
              value={username}
              onChange={e => setUsername(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              autoFocus
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">Password</label>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
              minLength={needsSetup ? 8 : undefined}
            />
          </div>
          {needsSetup && (
            <div>
              <label className="block text-sm font-medium mb-1">Confirm Password</label>
              <input
                type="password"
                value={confirmPassword}
                onChange={e => setConfirmPassword(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
          )}
          <button
            type="submit"
            disabled={loading}
            className="w-full py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium text-sm transition-colors disabled:opacity-50"
          >
            {loading ? (needsSetup ? "Creating..." : "Signing in...") : (needsSetup ? "Create Admin Account" : "Sign in")}
          </button>
        </form>
      </motion.div>
    </div>
  );
}
