'use client';

import { useState, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Shield, Eye, EyeOff, Loader2, AlertCircle, Lock, ChevronDown, ChevronUp } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAppStore } from '@/store/app-store';
import { useLangStore } from '@/store/lang-store';
import { toast } from 'sonner';
import type { UserType } from '@/types';

// ─── Main Component ───────────────────────────────────────────────────────────

export function LoginPage() {
  const navigate = useAppStore((s) => s.navigate);
  const setUser = useAppStore((s) => s.setUser);
  const t = useLangStore((s) => s.t);

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [showTestCreds, setShowTestCreds] = useState(false);

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError('');

      if (!email.trim()) {
        setError('Email is required');
        return;
      }

      if (!password) {
        setError('Password is required');
        return;
      }

      setIsLoading(true);

      try {
        const res = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: email.trim(), password }),
        });

        const data = await res.json();

        if (data.success) {
          const userData: UserType = data.data;
          localStorage.setItem('scamchecker_user', JSON.stringify(userData));
          setUser(userData);
          toast.success('Welcome back! Login successful.');
          navigate('dashboard');
        } else {
          setError(data.error || 'Login failed');
          toast.error(data.error || 'Login failed');
        }
      } catch {
        setError('Something went wrong. Please try again.');
        toast.error('Something went wrong. Please try again.');
      } finally {
        setIsLoading(false);
      }
    },
    [email, password, setUser, navigate]
  );

  const fillTestCreds = (role: 'admin' | 'user') => {
    if (role === 'admin') {
      setEmail('admin@scamcheckerbd.com');
      setPassword('admin123');
    } else {
      setEmail('user@example.com');
      setPassword('user123');
    }
  };

  return (
    <div className="min-h-[80vh] flex flex-col lg:flex-row">
      {/* ─── Left Side - Branding / Illustration ──────────────────────────── */}
      <div className="relative hidden lg:flex lg:w-1/2 items-center justify-center overflow-hidden bg-gradient-to-br from-emerald-900 via-emerald-800 to-teal-900">
        {/* Animated pattern background */}
        <div className="absolute inset-0 cyber-grid opacity-30" />
        
        {/* Floating decorative elements - CSS only */}
        <div className="absolute top-1/4 left-1/4 w-[300px] h-[300px] rounded-full opacity-20 animate-pulse-slow"
          style={{ background: 'radial-gradient(circle, oklch(0.558 0.158 155 / 0.4), transparent 70%)' }} />
        <div className="absolute bottom-1/4 right-1/4 w-[200px] h-[200px] rounded-full opacity-15 animate-pulse-slow"
          style={{ background: 'radial-gradient(circle, oklch(0.6 0.118 184.704 / 0.4), transparent 70%)', animationDelay: '3s' }} />
        
        {/* Small floating dots - CSS only */}
        <div className="absolute top-[15%] left-[20%] w-2 h-2 rounded-full bg-emerald-400/30 animate-float" />
        <div className="absolute top-[35%] right-[25%] w-3 h-3 rounded-full bg-teal-400/20 animate-float" style={{ animationDelay: '2s' }} />
        <div className="absolute bottom-[30%] left-[35%] w-2 h-2 rounded-full bg-emerald-300/25 animate-float" style={{ animationDelay: '4s' }} />
        <div className="absolute bottom-[20%] right-[15%] w-2.5 h-2.5 rounded-full bg-teal-300/20 animate-float" style={{ animationDelay: '1s' }} />
        <div className="absolute top-[60%] left-[10%] w-1.5 h-1.5 rounded-full bg-emerald-400/20 animate-float" style={{ animationDelay: '3s' }} />

        {/* Content */}
        <div className="relative z-10 text-center px-12 max-w-lg">
          <motion.div
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.6, ease: 'easeOut' }}
          >
            {/* Shield Logo */}
            <div className="shield-glow inline-flex p-6 rounded-3xl bg-emerald-500/15 border border-emerald-400/20 mb-8">
              <Shield className="h-16 w-16 text-emerald-300" strokeWidth={1.5} />
            </div>
            
            <h1 className="text-4xl font-extrabold text-white mb-4 leading-tight">
              Protect Yourself<br />
              <span className="bg-gradient-to-r from-emerald-300 to-teal-300 bg-clip-text text-transparent">
                From Scams
              </span>
            </h1>
            
            <p className="text-emerald-200/70 text-lg leading-relaxed mb-8">
              Join Bangladesh&apos;s community-powered scam intelligence platform. Report, verify, and stay safe.
            </p>

            {/* Social proof */}
            <div className="flex items-center justify-center gap-3">
              <div className="flex -space-x-2">
                {['R', 'S', 'M', 'F', 'T'].map((initial, i) => (
                  <div
                    key={i}
                    className="w-8 h-8 rounded-full border-2 border-emerald-900 flex items-center justify-center text-xs font-bold text-white"
                    style={{
                      backgroundColor: [
                        'oklch(0.558 0.158 155)',
                        'oklch(0.6 0.118 184.704)',
                        'oklch(0.558 0.158 155)',
                        'oklch(0.6 0.118 184.704)',
                        'oklch(0.558 0.158 155)',
                      ][i],
                    }}
                  >
                    {initial}
                  </div>
                ))}
              </div>
              <span className="text-sm text-emerald-200/60">
                <span className="font-semibold text-emerald-200/90">10,000+</span> users protecting themselves
              </span>
            </div>
          </motion.div>
        </div>
      </div>

      {/* ─── Right Side - Form ──────────────────────────────────────────── */}
      <div className="flex-1 flex items-center justify-center px-4 py-12 sm:px-8 lg:px-16">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, ease: 'easeOut' }}
          className="w-full max-w-md"
        >
          {/* Mobile-only shield logo */}
          <div className="flex justify-center mb-6 lg:hidden">
            <div className="shield-glow p-3 rounded-2xl bg-emerald-500/10 border border-emerald-500/20">
              <Shield className="h-10 w-10 text-emerald-500" />
            </div>
          </div>

          <div className="text-center mb-8">
            <h2 className="text-2xl sm:text-3xl font-bold">{t('auth.welcomeBack')}</h2>
            <p className="mt-2 text-muted-foreground">
              {t('auth.signIn')}
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Error Message */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 p-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm"
              >
                <AlertCircle className="h-4 w-4 shrink-0" />
                {error}
              </motion.div>
            )}

            {/* Email */}
            <div className="space-y-2">
              <Label htmlFor="login-email">{t('auth.email')}</Label>
              <div className="relative">
                <Input
                  id="login-email"
                  type="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    if (error) setError('');
                  }}
                  disabled={isLoading}
                  autoComplete="email"
                  className="h-11 pl-4 focus-visible:ring-emerald-500/30 focus-visible:border-emerald-500/50"
                />
              </div>
            </div>

            {/* Password */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="login-password">{t('auth.password')}</Label>
                <button
                  type="button"
                  className="text-xs text-emerald-600 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 font-medium transition-colors"
                >
                  Forgot password?
                </button>
              </div>
              <div className="relative">
                <Input
                  id="login-password"
                  type={showPassword ? 'text' : 'password'}
                  placeholder="Enter your password"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    if (error) setError('');
                  }}
                  disabled={isLoading}
                  autoComplete="current-password"
                  className="h-11 pr-10 focus-visible:ring-emerald-500/30 focus-visible:border-emerald-500/50"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
            </div>

            {/* Remember me */}
            <div className="flex items-center gap-2">
              <Checkbox
                id="remember-me"
                checked={rememberMe}
                onCheckedChange={(checked) => setRememberMe(checked === true)}
                className="data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
              />
              <Label htmlFor="remember-me" className="text-sm text-muted-foreground cursor-pointer">
                Remember me for 30 days
              </Label>
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={isLoading}
              className="w-full h-11 text-base rounded-xl bg-gradient-to-r from-emerald-600 to-emerald-500 hover:from-emerald-700 hover:to-emerald-600 dark:from-emerald-500 dark:to-emerald-400 dark:hover:from-emerald-600 dark:hover:to-emerald-500 shadow-lg shadow-emerald-500/20 transition-all duration-200"
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Signing in...
                </>
              ) : (
                <>
                  <Lock className="h-4 w-4" />
                  {t('auth.loginButton')}
                </>
              )}
            </Button>
          </form>

          {/* Divider */}
          <div className="relative my-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-border" />
            </div>
            <div className="relative flex justify-center text-xs">
              <span className="px-3 bg-background text-muted-foreground">or continue with</span>
            </div>
          </div>

          {/* Social login buttons (visual only) */}
          <div className="grid grid-cols-2 gap-3">
            <Button variant="outline" className="h-10 rounded-xl" type="button">
              <svg className="h-4 w-4 mr-2" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path 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" fill="#34A853"/><path 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" fill="#FBBC05"/><path 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" fill="#EA4335"/></svg>
              Google
            </Button>
            <Button variant="outline" className="h-10 rounded-xl" type="button">
              <svg className="h-4 w-4 mr-2" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2C6.477 2 2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.879V14.89h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.989C18.343 21.129 22 16.99 22 12c0-5.523-4.477-10-10-10z"/></svg>
              Facebook
            </Button>
          </div>

          {/* Test Credentials - Collapsible */}
          <div className="mt-6 rounded-xl border border-emerald-500/15 overflow-hidden">
            <button
              type="button"
              onClick={() => setShowTestCreds(!showTestCreds)}
              className="w-full flex items-center justify-between px-4 py-3 bg-emerald-500/5 hover:bg-emerald-500/8 transition-colors"
            >
              <span className="text-xs font-medium text-emerald-600 dark:text-emerald-400 flex items-center gap-1.5">
                <Shield className="h-3.5 w-3.5" />
                Test Credentials (Demo)
              </span>
              {showTestCreds ? (
                <ChevronUp className="h-3.5 w-3.5 text-emerald-500" />
              ) : (
                <ChevronDown className="h-3.5 w-3.5 text-emerald-500" />
              )}
            </button>
            {showTestCreds && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                transition={{ duration: 0.2 }}
                className="px-4 py-3 space-y-2 bg-emerald-500/[0.03]"
              >
                <button
                  type="button"
                  onClick={() => fillTestCreds('admin')}
                  className="w-full flex items-center justify-between px-3 py-2 rounded-lg bg-background border border-border hover:border-emerald-500/30 transition-colors text-left"
                >
                  <div>
                    <p className="text-xs font-medium">Admin Account</p>
                    <p className="text-[10px] text-muted-foreground">admin@scamcheckerbd.com / admin123</p>
                  </div>
                  <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium">Fill</span>
                </button>
                <button
                  type="button"
                  onClick={() => fillTestCreds('user')}
                  className="w-full flex items-center justify-between px-3 py-2 rounded-lg bg-background border border-border hover:border-emerald-500/30 transition-colors text-left"
                >
                  <div>
                    <p className="text-xs font-medium">User Account</p>
                    <p className="text-[10px] text-muted-foreground">user@example.com / user123</p>
                  </div>
                  <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-medium">Fill</span>
                </button>
              </motion.div>
            )}
          </div>

          {/* Register Link */}
          <p className="mt-6 text-sm text-muted-foreground text-center">
            {t('auth.noAccount')}{' '}
            <button
              type="button"
              onClick={() => navigate('register')}
              className="font-semibold text-emerald-600 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 transition-colors"
            >
              {t('auth.createAccount')}
            </button>
          </p>
        </motion.div>
      </div>
    </div>
  );
}
