'use client';

import React, { useState, Suspense } from 'react';
import { signIn } from 'next-auth/react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';

function LoginContent() {
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/tasks';
  const error = searchParams.get('error');
  const [isLoading, setIsLoading] = useState(false);

  const [credError, setCredError] = useState<string | null>(null);

  const handleCredentialsSignIn = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setCredError(null);
    const formData = new FormData(e.currentTarget);

    try {
      const result = await signIn('credentials', {
        email: formData.get('email'),
        password: formData.get('password'),
        redirect: false,
      });

      if (result?.error) {
        if (result.error === 'CredentialsSignin') {
          setCredError('Invalid email or password');
        } else {
          setCredError(result.error);
        }
        setIsLoading(false);
      } else if (result?.ok) {
        window.location.href = callbackUrl;
      }
    } catch {
      setCredError('An unexpected error occurred');
      setIsLoading(false);
    }
  };

  const handleGoogleSignIn = () => {
    setIsLoading(true);
    signIn('google', { callbackUrl });
  };

  return (
    <div className="weekly-auth-container">
      <div className="weekly-auth-card">
        {/* Logo */}
        <div className="weekly-auth-logo">
          My Weekly ToDo&apos;s
        </div>

        {/* Tagline */}
        <p className="weekly-auth-tagline">
          A simple, designy to-do app.
        </p>

        {/* Error Message */}
        {(error || credError) && (
          <div className="weekly-auth-error">
            {credError
              ? credError
              : error === 'CredentialsSignin'
              ? 'Invalid email or password'
              : error === 'email_not_verified'
              ? 'Please verify your email before signing in'
              : `An error occurred during sign in (${error})`}
          </div>
        )}

        <p className="weekly-auth-recommended">
          Recommended: Log in with email
        </p>

        {/* Login Form */}
        <form onSubmit={handleCredentialsSignIn} className="weekly-auth-form">
          <div className="weekly-auth-field">
            <input
              type="email"
              name="email"
              placeholder="Email"
              required
              autoComplete="email"
              className="weekly-auth-input"
            />
          </div>

          <div className="weekly-auth-field">
            <input
              type="password"
              name="password"
              placeholder="Password"
              required
              autoComplete="current-password"
              className="weekly-auth-input"
            />
          </div>

          <button
            type="submit"
            disabled={isLoading}
            className="weekly-auth-button primary"
          >
            {isLoading ? 'Signing in...' : 'Log In'}
          </button>
        </form>

        {/* Divider */}
        <div className="weekly-auth-divider">
          <span>or trust US Big Tech</span>
        </div>

        {/* Google Sign In */}
        <button
          type="button"
          onClick={handleGoogleSignIn}
          disabled={isLoading}
          className="weekly-auth-button google"
        >
          <svg className="google-icon" viewBox="0 0 24 24" width="18" height="18">
            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4 1.66l3-3C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
          </svg>
          Continue with Google
        </button>

        {/* Apple Sign In */}
        <button
          type="button"
          onClick={() => { setIsLoading(true); signIn('apple', { callbackUrl }); }}
          disabled={isLoading}
          className="weekly-auth-button apple"
          style={{ marginTop: '0.75rem', backgroundColor: '#000', color: '#fff' }}
        >
          <svg className="apple-icon" viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
            <path d="M16.365 21.492c-1.385 1.144-2.825 1.114-4.237.491-1.384-.622-2.735-.622-4.116 0-1.472.684-2.825.684-4.116-.279-5.1-4.144-6.31-11.458-2.67-15.002 1.442-1.383 3.08-1.745 4.503-1.745 1.471 0 2.883.682 3.86.682.95 0 2.61-.741 4.364-.741 1.748 0 3.35.532 4.417 1.838-3.647 1.956-3.08 6.906.653 8.358-.89 2.134-1.928 4.624-2.66 6.398zm-4.745-16.79c-.208-2.223 1.72-4.301 3.974-4.702.355 2.37-2.016 4.331-3.974 4.702z" />
          </svg>
          Continue with Apple
        </button>

        {/* Microsoft Sign In */}
        <button
          type="button"
          onClick={() => { setIsLoading(true); signIn('azure-ad', { callbackUrl }); }}
          disabled={isLoading}
          className="weekly-auth-button"
          style={{ marginTop: '0.75rem', backgroundColor: '#0078D4', color: '#fff', border: '1px solid #0078D4' }}
        >
          <svg className="microsoft-icon" viewBox="0 0 21 21" width="18" height="18" fill="currentColor">
            <path d="M10 0H0v10h10V0zM21 0H11v10h10V0zM10 11H0v10h10V11zM21 11H11v10h10V11z" />
          </svg>
          Continue with Microsoft
        </button>

        {/* Links */}
        <div className="weekly-auth-links">
          <Link href="/auth/forgot-password" className="weekly-auth-link">
            Forgot password?
          </Link>
          <span className="weekly-auth-link-divider">·</span>
          <Link href="/auth/signup" className="weekly-auth-link">
            Create account
          </Link>
        </div>
      </div>

      {/* Footer */}
      <footer className="weekly-auth-footer">
        <p>Simple. Beautiful. Yours.</p>
      </footer>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="weekly-auth-container"><div className="weekly-auth-card"><div className="weekly-auth-logo">My Weekly ToDo&apos;s</div></div></div>}>
      <LoginContent />
    </Suspense>
  );
}