import { useState } from 'react';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import { useAuth } from '@{{PROJECT_NAME}}/auth';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  CardFooter,
  FormField,
  useFormErrors,
  Alert,
  AlertDescription,
  Loader2,
} from '@{{PROJECT_NAME}}/ui';
import { isApiClientError } from '@{{PROJECT_NAME}}/api-client';

type LoginTab = 'password' | 'otp' | 'magic-link';

export function LoginPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { login, sendOTP, loginWithOTP, sendMagicLink, isLoading } = useAuth();
  const { setErrors, clearErrors, getError } = useFormErrors();
  const [generalError, setGeneralError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<LoginTab>('password');
  const [otpSent, setOtpSent] = useState(false);
  const [otpEmail, setOtpEmail] = useState('');
  const [magicLinkSent, setMagicLinkSent] = useState(false);

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

  const handlePasswordLogin = 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;

    try {
      await login({ email, password });
      navigate(from, { replace: true });
    } catch (error) {
      if (isApiClientError(error)) {
        if (error.isValidationError()) {
          setErrors(error.getFieldErrors());
        } else {
          setGeneralError(error.message);
        }
      } else if (error instanceof Error) {
        setGeneralError(error.message);
      } else {
        setGeneralError('An unexpected error occurred.');
      }
    }
  };

  const handleSendOTP = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    clearErrors();
    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();
    clearErrors();
    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');
    }
  };

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

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

    try {
      await sendMagicLink(email);
      setMagicLinkSent(true);
    } catch (error) {
      setGeneralError(error instanceof Error ? error.message : 'Failed to send link');
    }
  };

  const tabClass = (tab: LoginTab) =>
    `flex-1 py-2 text-sm font-medium text-center rounded-md transition-colors ${
      activeTab === tab
        ? 'bg-[var(--surface-100)] text-[var(--text-primary)] shadow-sm'
        : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
    }`;

  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 back</CardTitle>
          <CardDescription>Sign in to your {{PROJECT_NAME}} account</CardDescription>
        </CardHeader>

        <CardContent className="space-y-4">
          {/* Tab switcher */}
          <div className="flex gap-1 p-1 rounded-lg bg-[var(--surface-200)]">
            <button type="button" className={tabClass('password')} onClick={() => { setActiveTab('password'); clearErrors(); setGeneralError(null); }}>
              Password
            </button>
            <button type="button" className={tabClass('otp')} onClick={() => { setActiveTab('otp'); clearErrors(); setGeneralError(null); setOtpSent(false); }}>
              OTP
            </button>
            <button type="button" className={tabClass('magic-link')} onClick={() => { setActiveTab('magic-link'); clearErrors(); setGeneralError(null); setMagicLinkSent(false); }}>
              Magic Link
            </button>
          </div>

          {generalError && (
            <Alert variant="destructive">
              <AlertDescription>{generalError}</AlertDescription>
            </Alert>
          )}

          {/* Password tab */}
          {activeTab === 'password' && (
            <form onSubmit={handlePasswordLogin} className="space-y-4">
              <FormField
                label="Email"
                name="email"
                type="email"
                placeholder="you@example.com"
                error={getError('email')}
                required
                autoComplete="email"
                autoFocus
              />
              <FormField
                label="Password"
                name="password"
                type="password"
                placeholder="Enter your password"
                error={getError('password')}
                required
                autoComplete="current-password"
              />
              <div className="text-right">
                <Link to="/forgot-password" className="text-sm text-[var(--accent)] hover:underline">
                  Forgot password?
                </Link>
              </div>
              <Button type="submit" className="w-full" disabled={isLoading}>
                {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Sign in
              </Button>
            </form>
          )}

          {/* OTP tab */}
          {activeTab === 'otp' && !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>
          )}

          {activeTab === 'otp' && 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)}
              >
                Use a different email
              </button>
            </form>
          )}

          {/* Magic Link tab */}
          {activeTab === 'magic-link' && !magicLinkSent && (
            <form onSubmit={handleSendMagicLink} 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 magic link
              </Button>
            </form>
          )}

          {activeTab === 'magic-link' && magicLinkSent && (
            <div className="text-center space-y-3 py-4">
              <p className="text-sm text-[var(--text-primary)]">Check your email</p>
              <p className="text-sm text-[var(--text-muted)]">
                We sent a sign-in link to your email. Click it to continue.
              </p>
              <p className="text-xs text-[var(--text-muted)]">
                In dev mode, check the server console for the link token.
              </p>
            </div>
          )}
        </CardContent>

        <CardFooter className="flex flex-col gap-3">
          <p className="text-sm text-center text-[var(--text-muted)]">
            Don't have an account?{' '}
            <Link to="/register" className="text-[var(--accent)] hover:underline">
              Sign up
            </Link>
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
