'use client';

import { useState, type FormEvent } from 'react';
import { motion } from 'framer-motion';
import {
  Headphones,
  Eye,
  EyeOff,
  Loader2,
  ArrowLeft,
  Globe,
  AlertCircle,
  UserPlus,
} 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 { useStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import type { User } from '@/lib/store';

export default function ClientLogin() {
  const setPortal = useStore((s) => s.setPortal);
  const setView = useStore((s) => s.setView);
  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 [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,
        createdAt: data.user.createdAt,
        updatedAt: new Date().toISOString(),
      };

      login(user);
      setAuthToken(data.token);
    } 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 - lighter than admin */}
      <div className="fixed inset-0 -z-10">
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-50 via-teal-50/50 to-emerald-100/30" />
        <div
          className="absolute inset-0 opacity-[0.03]"
          style={{
            backgroundImage: `radial-gradient(circle, #059669 1px, transparent 1px)`,
            backgroundSize: '28px 28px',
          }}
        />
        {/* Decorative circles */}
        <div className="absolute -top-20 -right-20 w-72 h-72 rounded-full bg-emerald-200/30 blur-3xl" />
        <div className="absolute -bottom-20 -left-20 w-72 h-72 rounded-full bg-teal-200/30 blur-3xl" />
      </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/80 backdrop-blur-sm border-emerald-200 hover:bg-emerald-50 hover:border-emerald-300 text-emerald-700 shadow-sm"
        >
          <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-600 hover:text-emerald-800 hover:bg-emerald-50"
        >
          <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-xl overflow-hidden">
          {/* Header - lighter green gradient */}
          <CardHeader className="bg-gradient-to-r from-emerald-500 via-emerald-400 to-teal-400 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/25 backdrop-blur-sm flex items-center justify-center">
                <Headphones className="w-7 h-7 text-white" />
              </div>
            </motion.div>
            <h1 className="text-xl sm:text-2xl font-bold text-white">
              {t.portal.clientPortal}
            </h1>
            <p className="text-emerald-50/80 text-sm mt-1">
              {t.portal.welcome}
            </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="client-email" className="text-emerald-800">
                  {t.form.email}
                </Label>
                <Input
                  id="client-email"
                  type="email"
                  placeholder="user1@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">
                <div className="flex items-center justify-between">
                  <Label htmlFor="client-password" className="text-emerald-800">
                    {t.form.password}
                  </Label>
                  <button
                    type="button"
                    className="text-xs text-emerald-600 hover:text-emerald-800 transition-colors"
                  >
                    {t.portal.forgotPassword}
                  </button>
                </div>
                <div className="relative">
                  <Input
                    id="client-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>

              {/* Login Button */}
              <Button
                type="submit"
                className="w-full bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600 text-white shadow-lg shadow-emerald-100 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>

            {/* Register Link */}
            <div className="mt-6 text-center">
              <p className="text-sm text-emerald-600/70">
                {language === 'en' ? "Don't have an account?" : 'অ্যাকাউন্ট নেই?'}{' '}
                <button
                  type="button"
                  onClick={() => setView('register')}
                  className="inline-flex items-center gap-1 font-semibold text-emerald-700 hover:text-emerald-900 transition-colors"
                >
                  <UserPlus className="w-3.5 h-3.5" />
                  {t.portal.register}
                </button>
              </p>
            </div>

            {/* Demo hint */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 1 }}
              className="mt-4 p-3 rounded-lg bg-emerald-50/50 border border-emerald-100"
            >
              <p className="text-xs text-emerald-500 text-center">
                {language === 'en' ? 'Demo: user1@usd.com / admin123' : 'ডেমো: user1@usd.com / admin123'}
              </p>
            </motion.div>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  );
}
