// src/app/(root)/login/LoginForm.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Mail, Lock, Eye, EyeOff, AlertCircle, Loader2, ArrowRight } from 'lucide-react';
import toast from 'react-hot-toast';

type FormData = { email: string; password: string; rememberMe: boolean };
type Errors   = Record<string, string>;

export default function LoginForm() {
  const router       = useRouter();
  const searchParams = useSearchParams();

  const [showPassword,  setShowPassword]  = useState(false);
  const [isLoading,     setIsLoading]     = useState(false);
  const [socialLoading, setSocialLoading] = useState(false);
  const [errors,        setErrors]        = useState<Errors>({});
  const [form,          setForm]          = useState<FormData>({ email: '', password: '', rememberMe: false });

  useEffect(() => {
    const registered = searchParams.get('registered');
    const error      = searchParams.get('error');
    if (registered === 'true') {
      toast.success('Registration successful! Please sign in.');
      window.history.replaceState({}, '', '/login');
    }
    if (error) {
      const errorMap: Record<string, string> = {
        wrong_google: 'This email is not registered with Google. Please use email/password or sign up.',
      };
      toast.error(errorMap[error] || decodeURIComponent(error));
      window.history.replaceState({}, '', '/login');
    }
  }, [searchParams]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }));
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const validate = (): boolean => {
    const newErrors: Errors = {};
    if (!form.email)                           newErrors.email    = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(form.email)) newErrors.email    = 'Enter a valid email';
    if (!form.password)                        newErrors.password = 'Password is required';
    else if (form.password.length < 6)         newErrors.password = 'Minimum 6 characters';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setIsLoading(true);
    try {
      const res  = await fetch('/api/frontend/user/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: form.email, password: form.password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Login failed');
      if (data.requires2FA) {
        toast.success(data.message);
        router.push(`/verify-2fa?userId=${data.tempUserId}&method=${data.twoFactorMethod}`);
        return;
      }
      toast.success('Welcome back!');
      router.push('/dashboard');
    } catch (err) {
      setErrors({ submit: err instanceof Error ? err.message : 'Something went wrong.' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGoogleLogin = async () => {
    setSocialLoading(true);
    try {
      const res  = await fetch('/api/frontend/user/auth/google/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ redirectUri: `${window.location.origin}/auth/callback` }),
      });
      const data = await res.json();
      if (data.redirectUrl) { window.location.href = data.redirectUrl; return; }
      throw new Error('No redirect URL received');
    } catch {
      toast.error('Failed to sign in with Google');
      setSocialLoading(false);
    }
  };

  const inputClass = (field: string) =>
    `w-full pl-10 pr-3 py-3 text-sm border rounded-xl bg-background text-text-primary
     placeholder-text-secondary/40 outline-none transition-all
     focus:ring-2 focus:ring-[#0066FF]/20 ${
       errors[field]
         ? 'border-red-300 focus:border-red-400'
         : 'border-black/10 focus:border-[#0066FF]'
     }`;

  return (
    <div>
      {/* Header */}
      <div className="text-center mb-7">
        {/* Mobile logo */}
        <div className="lg:hidden flex justify-center mb-5">
          <Link href="/">
            <div className="h-11 w-11 rounded-xl bg-linear-to-br from-[#0066FF] to-[#00D4FF] flex items-center justify-center">
              <span className="text-white font-bold text-lg">OE</span>
            </div>
          </Link>
        </div>
        <h2 className="text-2xl font-bold text-text-primary">Welcome back</h2>
        <p className="mt-1.5 text-sm text-text-secondary">Sign in to your OutreachExpert account</p>
      </div>

      {/* Submit error */}
      {errors.submit && (
        <div className="mb-5 flex items-start gap-3 p-3.5 rounded-xl bg-red-50 border border-red-200">
          <AlertCircle className="h-4 w-4 text-red-500 shrink-0 mt-0.5" />
          <p className="text-sm text-red-700">{errors.submit}</p>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">

        {/* Email */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">Email</label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type="email"
              name="email"
              value={form.email}
              onChange={handleChange}
              placeholder="you@company.com"
              className={inputClass('email')}
            />
          </div>
          {errors.email && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.email}
            </p>
          )}
        </div>

        {/* Password */}
        <div>
          <div className="flex items-center justify-between mb-1.5">
            <label className="text-xs font-medium text-text-primary">Password</label>
            <Link href="/forgot-password" className="text-xs text-[#0066FF] hover:text-[#0052cc] transition-colors">
              Forgot password?
            </Link>
          </div>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type={showPassword ? 'text' : 'password'}
              name="password"
              value={form.password}
              onChange={handleChange}
              placeholder="••••••••"
              className={`${inputClass('password')} pr-10`}
            />
            <button
              type="button"
              onClick={() => setShowPassword(p => !p)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-text-secondary hover:text-text-primary transition-colors"
            >
              {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
          {errors.password && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.password}
            </p>
          )}
        </div>

        {/* Remember me */}
        <label className="flex items-center gap-2.5 cursor-pointer w-fit">
          <input
            type="checkbox"
            name="rememberMe"
            checked={form.rememberMe}
            onChange={handleChange}
            className="w-4 h-4 rounded border-black/20 text-[#0066FF] focus:ring-[#0066FF]/20"
          />
          <span className="text-xs text-text-secondary">Remember me for 30 days</span>
        </label>

        {/* Submit */}
        <button
          type="submit"
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl
            bg-[#0066FF] hover:bg-[#0052cc] active:scale-[0.99] text-white text-sm font-semibold
            transition-all disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {isLoading
            ? <><Loader2 className="h-4 w-4 animate-spin" /> Signing in...</>
            : <>Sign in <ArrowRight className="h-4 w-4" /></>
          }
        </button>

      </form>

      {/* Below form */}
      <div className="mt-6 space-y-4">

        {/* Divider */}
        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-black/8" />
          </div>
          <div className="relative flex justify-center">
            <span className="px-3 bg-surface text-xs text-text-secondary">or continue with</span>
          </div>
        </div>

        {/* Google */}
        <button
          onClick={handleGoogleLogin}
          disabled={socialLoading}
          className="w-full flex items-center justify-center gap-3 py-3 px-4 rounded-xl
            border border-black/10 hover:bg-black/3 active:scale-[0.99]
            text-sm text-text-primary transition-all
            disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {socialLoading ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <svg className="h-4 w-4 shrink-0" viewBox="0 0 24 24">
              <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.93l3.66-2.84z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.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>

        {/* Sign up */}
        <p className="pt-2 border-t border-black/8 text-center text-xs text-text-secondary">
          Don`t have an account?{' '}
          <Link href="/register" className="font-medium text-[#0066FF] hover:text-[#0052cc] transition-colors">
            Create one free
          </Link>
        </p>

      </div>
    </div>
  );
}