'use client';

import { useState, Suspense } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import Link from 'next/link';

function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/';
  const registered = searchParams.get('registered') === 'true';
  const verified = searchParams.get('verified') === 'true';
  const passwordReset = searchParams.get('passwordReset') === 'true';
  
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [emailNotVerified, setEmailNotVerified] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isResending, setIsResending] = useState(false);

  const handleResendConfirmation = async () => {
    setIsResending(true);
    try {
      const response = await fetch('/api/auth/resend-confirmation', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await response.json();
      if (response.ok) {
        setError('');
        setEmailNotVerified(false);
        alert('Confirmation email sent! Please check your inbox.');
      } else {
        alert(data.error || 'Failed to resend confirmation email');
      }
    } catch (err) {
      alert('An error occurred. Please try again.');
    } finally {
      setIsResending(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setEmailNotVerified(false);
    setIsLoading(true);

    try {
      // First check if email is verified
      const checkResponse = await fetch('/api/auth/check-verification', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const checkData = await checkResponse.json();

      if (!checkData.exists) {
        setError('Invalid email or password');
        setIsLoading(false);
        return;
      }

      if (!checkData.passwordValid) {
        setError('Invalid email or password');
        setIsLoading(false);
        return;
      }

      if (!checkData.verified) {
        setEmailNotVerified(true);
        setIsLoading(false);
        return;
      }

      // Email is verified, proceed with login
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
      });

      if (result?.error) {
        setError('Invalid email or password');
      } else {
        router.push(callbackUrl);
        router.refresh();
      }
    } catch (err) {
      setError('An error occurred. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50 px-4">
      <div className="w-full max-w-md space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-secondary">
            Sign in to your account
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            Or{' '}
            <Link
              href="/register"
              className="font-medium text-blue-600 hover:text-blue-500"
            >
              create a new account
            </Link>
          </p>
        </div>
        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          {registered && (
            <div className="rounded-md bg-green-50 p-4">
              <p className="text-sm text-green-800">
                Account created successfully! Please check your email to confirm your account before signing in.
              </p>
            </div>
          )}
          {verified && (
            <div className="rounded-md bg-green-50 p-4">
              <p className="text-sm text-green-800">
                Email verified successfully! You can now sign in.
              </p>
            </div>
          )}
          {passwordReset && (
            <div className="rounded-md bg-green-50 p-4">
              <p className="text-sm text-green-800">
                Password reset successfully! You can now sign in with your new password.
              </p>
            </div>
          )}
          {emailNotVerified && (
            <div className="rounded-md bg-yellow-50 p-4">
              <p className="text-sm text-yellow-800 mb-2">
                Please verify your email address before signing in. Check your inbox for a confirmation email.
              </p>
              <button
                type="button"
                onClick={handleResendConfirmation}
                disabled={isResending}
                className="text-sm text-yellow-900 underline hover:no-underline font-medium"
              >
                {isResending ? 'Sending...' : 'Resend confirmation email'}
              </button>
            </div>
          )}
          {error && (
            <div className="rounded-md bg-red-50 p-4">
              <p className="text-sm text-red-800">{error}</p>
            </div>
          )}
          <div className="space-y-4 rounded-md shadow-sm">
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-secondary">
                Email address
              </label>
              <Input
                id="email"
                name="email"
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  // Clear email verification error when email changes
                  if (emailNotVerified) {
                    setEmailNotVerified(false);
                  }
                }}
                className="mt-1"
                placeholder="you@example.com"
              />
            </div>
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-secondary">
                Password
              </label>
              <Input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-1"
                placeholder="••••••••"
              />
            </div>
          </div>

          <div>
            <Button
              type="submit"
              className="w-full"
              disabled={isLoading}
            >
              {isLoading ? 'Signing in...' : 'Sign in'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={
      <div className="flex min-h-screen items-center justify-center bg-gray-50 px-4">
        <div className="w-full max-w-md space-y-8">
          <div className="text-center">
            <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-secondary">
              Sign in to your account
            </h2>
            <p className="mt-2 text-center text-sm text-gray-600">Loading...</p>
          </div>
        </div>
      </div>
    }>
      <LoginForm />
    </Suspense>
  );
}

