import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '@persona-community-5/auth';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  FormField,
  Alert,
  AlertDescription,
  Loader2,
} from '@persona-community-5/ui';

export function LoginPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { sendOTP, loginWithOTP, isLoading } = useAuth();
  const [generalError, setGeneralError] = useState<string | null>(null);
  const [otpSent, setOtpSent] = useState(false);
  const [otpEmail, setOtpEmail] = useState('');

  const from = (location.state as { from?: string })?.from || '/';

  const handleSendOTP = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setGeneralError(null);

    const formData = new FormData(e.currentTarget);
    const email = formData.get('email') as string;

    try {
      await sendOTP(email);
      setOtpEmail(email);
      setOtpSent(true);
    } catch (error) {
      setGeneralError(error instanceof Error ? error.message : 'Failed to send code');
    }
  };

  const handleVerifyOTP = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setGeneralError(null);

    const formData = new FormData(e.currentTarget);
    const code = formData.get('code') as string;

    try {
      await loginWithOTP({ email: otpEmail, code });
      navigate(from, { replace: true });
    } catch (error) {
      setGeneralError(error instanceof Error ? error.message : 'Invalid code');
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--surface-100)] p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">Welcome</CardTitle>
          <CardDescription>Sign in to the Persona Community</CardDescription>
        </CardHeader>

        <CardContent className="space-y-4">
          {generalError && (
            <Alert variant="destructive">
              <AlertDescription>{generalError}</AlertDescription>
            </Alert>
          )}

          {!otpSent && (
            <form onSubmit={handleSendOTP} className="space-y-4">
              <FormField
                label="Email"
                name="email"
                type="email"
                placeholder="you@example.com"
                required
                autoComplete="email"
                autoFocus
              />
              <Button type="submit" className="w-full" disabled={isLoading}>
                {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Send Code
              </Button>
            </form>
          )}

          {otpSent && (
            <form onSubmit={handleVerifyOTP} className="space-y-4">
              <p className="text-sm text-[var(--text-muted)]">
                A 6-digit code was sent to <strong>{otpEmail}</strong>
              </p>
              <FormField
                label="Code"
                name="code"
                type="text"
                placeholder="000000"
                required
                autoComplete="one-time-code"
                autoFocus
              />
              <Button type="submit" className="w-full" disabled={isLoading}>
                {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Verify
              </Button>
              <button
                type="button"
                className="w-full text-sm text-[var(--text-muted)] hover:text-[var(--text-secondary)]"
                onClick={() => { setOtpSent(false); setGeneralError(null); }}
              >
                Use a different email
              </button>
            </form>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
