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

export function RegisterPage() {
  const navigate = useNavigate();
  const { register, isLoading } = useAuth();
  const { setErrors, clearErrors, getError } = useFormErrors();
  const [generalError, setGeneralError] = useState<string | null>(null);

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

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

    if (password !== confirmPassword) {
      setErrors({ confirmPassword: 'Passwords do not match' });
      return;
    }

    try {
      await register({ email, password, name });
      navigate('/', { replace: true });
    } catch (error) {
      if (error instanceof Error) {
        setGeneralError(error.message);
      } else {
        setGeneralError('An unexpected error occurred.');
      }
    }
  };

  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">Create an account</CardTitle>
          <CardDescription>Get started with persona-community-5</CardDescription>
        </CardHeader>

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

            <FormField
              label="Name"
              name="name"
              type="text"
              placeholder="Your name"
              error={getError('name')}
              autoComplete="name"
              autoFocus
            />

            <FormField
              label="Email"
              name="email"
              type="email"
              placeholder="you@example.com"
              error={getError('email')}
              required
              autoComplete="email"
            />

            <FormField
              label="Password"
              name="password"
              type="password"
              placeholder="At least 8 characters"
              error={getError('password')}
              required
              autoComplete="new-password"
              description="Must contain uppercase, lowercase, and a number"
            />

            <FormField
              label="Confirm Password"
              name="confirmPassword"
              type="password"
              placeholder="Repeat your password"
              error={getError('confirmPassword')}
              required
              autoComplete="new-password"
            />
          </CardContent>

          <CardFooter className="flex flex-col gap-4">
            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Create account
            </Button>

            <p className="text-sm text-center text-[var(--text-muted)]">
              Already have an account?{' '}
              <Link to="/login" className="text-[var(--accent)] hover:underline">
                Sign in
              </Link>
            </p>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}
