import { useState } from 'react';
import { useAuth } from '@{{PROJECT_NAME}}/auth';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  FormField,
  Alert,
  AlertDescription,
  Loader2,
  Check,
} from '@{{PROJECT_NAME}}/ui';

export function VerifyEmailPage() {
  const { user, getToken } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [codeSent, setCodeSent] = useState(false);
  const [verified, setVerified] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const apiPrefix = import.meta.env.VITE_API_URL || '';

  const authHeaders = () => {
    const token = getToken();
    return {
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
    };
  };

  const handleSendCode = async () => {
    setError(null);
    setIsLoading(true);

    try {
      const res = await fetch(`${apiPrefix}/api/{{SERVICE_NAME}}/auth/verify-email/send`, {
        method: 'POST',
        headers: authHeaders(),
      });

      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error?.message || body.message || 'Failed to send code');
      }

      setCodeSent(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerify = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

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

    try {
      const res = await fetch(`${apiPrefix}/api/{{SERVICE_NAME}}/auth/verify-email`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({ code }),
      });

      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error?.message || body.message || 'Verification failed');
      }

      setVerified(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  if (verified) {
    return (
      <div className="space-y-6">
        <Card className="max-w-md mx-auto">
          <CardHeader className="text-center">
            <div className="flex justify-center mb-2">
              <Check className="h-12 w-12 text-green-500" />
            </div>
            <CardTitle>Email verified</CardTitle>
            <CardDescription>Your email address has been verified successfully.</CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="max-w-md mx-auto">
        <CardHeader className="text-center">
          <CardTitle>Verify your email</CardTitle>
          <CardDescription>
            {codeSent
              ? `Enter the 6-digit code sent to ${user?.email}`
              : 'Verify your email address to access all features'}
          </CardDescription>
        </CardHeader>

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

          {!codeSent ? (
            <div className="text-center">
              <p className="text-sm text-[var(--text-muted)] mb-4">
                We'll send a verification code to <strong>{user?.email}</strong>
              </p>
              <Button onClick={handleSendCode} disabled={isLoading}>
                {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Send verification code
              </Button>
              <p className="text-xs text-[var(--text-muted)] mt-2">
                In dev mode, check the server console for the code.
              </p>
            </div>
          ) : (
            <form onSubmit={handleVerify} className="space-y-4">
              <FormField
                label="Verification 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 email
              </Button>
              <button
                type="button"
                className="w-full text-sm text-[var(--text-muted)] hover:text-[var(--text-secondary)]"
                onClick={handleSendCode}
              >
                Resend code
              </button>
            </form>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
