'use client';

import { useState, type FormEvent } from 'react';
import { motion } from 'framer-motion';
import {
  Shield,
  Eye,
  EyeOff,
  Loader2,
  ArrowLeft,
  Globe,
  AlertCircle,
  KeyRound,
} from 'lucide-react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { useStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import type { User } from '@/lib/store';

export default function AdminLogin() {
  const setPortal = useStore((s) => s.setPortal);
  const login = useStore((s) => s.login);
  const setAuthToken = useStore((s) => s.setAuthToken);
  const language = useStore((s) => s.language);
  const setLanguage = useStore((s) => s.setLanguage);
  const { t } = useTranslation();

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

  const validateForm = (): boolean => {
    if (!email.trim()) {
      setError(t.form.requiredField);
      return false;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError(t.form.invalidEmail);
      return false;
    }
    if (!password.trim()) {
      setError(t.form.requiredField);
      return false;
    }
    if (password.length < 4) {
      setError(t.form.minLength.replace('{min}', '4'));
      return false;
    }
    return true;
  };

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

    if (!validateForm()) return;

    setIsLoading(true);

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

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || t.messages.error.loginFailed);
        return;
      }

      // Map the API user to our store User type
      const user: User = {
        id: data.user.id,
        name: data.user.name,
        email: data.user.email,
        phone: data.user.phone,
        role: data.user.role === 'head_of_department' ? 'hod' : data.user.role,
        area: data.user.area?.name,
        areaId: data.user.area?.id,
        department: undefined,
        avatar: data.user.avatar,
        isActive: data.user.isActive,
        workloadLimit: data.user.workloadLimit,
        createdAt: data.user.createdAt,
        updatedAt: new Date().toISOString(),
      };

      login(user);
      setAuthToken(data.token); // Store auth token for API calls
    } catch (err) {
      setError(t.messages.error.networkError);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-4 py-8 relative overflow-hidden">
      {/* Background */}
      <div className="fixed inset-0 -z-10">
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-900 via-emerald-800 to-emerald-950" />
        <div
          className="absolute inset-0 opacity-[0.04]"
          style={{
            backgroundImage: `radial-gradient(circle, white 1px, transparent 1px)`,
            backgroundSize: '28px 28px',
          }}
        />
        <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-400 via-teal-300 to-emerald-400" />
      </div>

      {/* Language Switcher */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        className="absolute top-4 right-4 sm:top-6 sm:right-6"
      >
        <Button
          variant="outline"
          size="sm"
          onClick={() => setLanguage(language === 'en' ? 'bn' : 'en')}
          className="gap-1.5 bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 hover:border-white/30 text-white"
        >
          <Globe className="size-3.5" />
          <span className="font-medium text-xs">{language === 'en' ? 'BN' : 'EN'}</span>
        </Button>
      </motion.div>

      {/* Back to Landing */}
      <motion.div
        initial={{ opacity: 0, x: -10 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ duration: 0.4, delay: 0.1 }}
        className="absolute top-4 left-4 sm:top-6 sm:left-6"
      >
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setPortal('landing')}
          className="gap-1.5 text-emerald-200 hover:text-white hover:bg-white/10"
        >
          <ArrowLeft className="size-3.5" />
          <span className="text-xs">{language === 'en' ? 'Back' : 'পিছনে'}</span>
        </Button>
      </motion.div>

      {/* Login Card */}
      <motion.div
        initial={{ opacity: 0, y: 30, scale: 0.95 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.6, ease: 'easeOut' }}
        className="w-full max-w-md"
      >
        <Card className="border-0 shadow-2xl overflow-hidden">
          {/* Header with gradient */}
          <CardHeader className="bg-gradient-to-r from-emerald-700 via-emerald-600 to-teal-600 p-6 sm:p-8 text-center">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ type: 'spring', stiffness: 200, damping: 15, delay: 0.3 }}
              className="flex justify-center mb-4"
            >
              <div className="w-14 h-14 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center">
                <Shield className="w-7 h-7 text-white" />
              </div>
            </motion.div>
            <h1 className="text-xl sm:text-2xl font-bold text-white">
              {t.portal.adminPortal}
            </h1>
            <p className="text-emerald-100/80 text-sm mt-1">
              {t.portal.welcomeBack}
            </p>
          </CardHeader>

          <CardContent className="p-6 sm:p-8">
            {/* Error Message */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -5 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 p-3 mb-5 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm"
              >
                <AlertCircle className="w-4 h-4 shrink-0" />
                <span>{error}</span>
              </motion.div>
            )}

            <form onSubmit={handleSubmit} className="space-y-5">
              {/* Email */}
              <div className="space-y-2">
                <Label htmlFor="admin-email" className="text-emerald-800">
                  {t.form.email}
                </Label>
                <Input
                  id="admin-email"
                  type="email"
                  placeholder="admin@usd.com"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    setError('');
                  }}
                  className="border-emerald-200 focus-visible:border-emerald-500 focus-visible:ring-emerald-500/20"
                  autoComplete="email"
                  disabled={isLoading}
                />
              </div>

              {/* Password */}
              <div className="space-y-2">
                <Label htmlFor="admin-password" className="text-emerald-800">
                  {t.form.password}
                </Label>
                <div className="relative">
                  <Input
                    id="admin-password"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      setError('');
                    }}
                    className="border-emerald-200 focus-visible:border-emerald-500 focus-visible:ring-emerald-500/20 pr-10"
                    autoComplete="current-password"
                    disabled={isLoading}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-emerald-400 hover:text-emerald-600 transition-colors"
                    tabIndex={-1}
                  >
                    {showPassword ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* Remember Me */}
              <div className="flex items-center gap-2">
                <Checkbox
                  id="admin-remember"
                  checked={rememberMe}
                  onCheckedChange={(checked) => setRememberMe(checked === true)}
                  className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
                />
                <Label
                  htmlFor="admin-remember"
                  className="text-sm text-emerald-700 cursor-pointer"
                >
                  {language === 'en' ? 'Remember me' : 'আমাকে মনে রাখুন'}
                </Label>
              </div>

              {/* Login Button */}
              <Button
                type="submit"
                className="w-full bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-700 hover:to-emerald-800 text-white shadow-lg shadow-emerald-200 h-11 text-sm font-semibold"
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {t.common.loading}
                  </>
                ) : (
                  t.portal.login
                )}
              </Button>
            </form>

            {/* Demo Credentials Hint */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 1 }}
              className="mt-6 p-3 rounded-lg bg-emerald-50 border border-emerald-100"
            >
              <div className="flex items-start gap-2">
                <KeyRound className="w-4 h-4 text-emerald-500 mt-0.5 shrink-0" />
                <div className="text-xs text-emerald-600">
                  <p className="font-medium mb-1">
                    {language === 'en' ? 'Demo Credentials' : 'ডেমো পরিচয়পত্র'}
                  </p>
                  <p className="text-emerald-500">
                    admin@usd.com / admin123
                  </p>
                </div>
              </div>
            </motion.div>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  );
}
