'use client';

import { useState, useEffect } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import { Separator } from '@/components/ui/separator';
import { Mail, Lock, Phone, User, GraduationCap, Home, Store, Eye, EyeOff, Shield, ArrowLeft, KeyRound, CheckCircle2, Copy, Check, RefreshCw, Timer } from 'lucide-react';

interface RoleOption {
  id: string;
  labelKey: string;
  icon: React.ElementType;
}

const roleOptions: RoleOption[] = [
  { id: 'general', labelKey: 'auth.role.general', icon: User },
  { id: 'student', labelKey: 'auth.role.student', icon: GraduationCap },
  { id: 'houseOwner', labelKey: 'auth.role.houseOwner', icon: Home },
  { id: 'shopOwner', labelKey: 'auth.role.shopOwner', icon: Store },
];

const demoAccounts = [
  { email: 'demo@needyfy.com', password: 'demo123', label: 'General User', labelBn: 'সাধারণ ব্যবহারকারী', role: 'general', icon: User, color: 'emerald' },
  { email: 'owner@needyfy.com', password: 'owner123', label: 'House Owner', labelBn: 'বাড়ির মালিক', role: 'houseOwner', icon: Home, color: 'amber' },
  { email: 'shopowner@needyfy.com', password: 'shop123', label: 'Shop Owner', labelBn: 'দোকান মালিক', role: 'shopOwner', icon: Store, color: 'amber' },
  { email: 'superadmin@needyfy.com', password: 'SuperAdmin@2025', label: 'Super Admin', labelBn: 'সুপার অ্যাডমিন', role: 'admin', icon: Shield, color: 'orange' },
];

// ============ FORGOT PASSWORD COMPONENT (INLINE - SAME PAGE) ============
function ForgotPassword({ onBack }: { onBack: () => void }) {
  const { language } = useAppStore();
  const { toast } = useToast();
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [devCode, setDevCode] = useState('');
  const [copied, setCopied] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [isDevMode, setIsDevMode] = useState(false);
  // Progressive reveal states - all on same page
  const [codeSent, setCodeSent] = useState(false);
  const [codeVerified, setCodeVerified] = useState(false);

  // Countdown timer for code expiration
  useEffect(() => {
    if (codeSent && !codeVerified && countdown > 0) {
      const timer = setTimeout(() => setCountdown(c => c - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [codeSent, codeVerified, countdown]);

  const formatCountdown = (seconds: number) => {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const handleCopyCode = async () => {
    if (devCode) {
      try {
        await navigator.clipboard.writeText(devCode);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } catch {
        const el = document.getElementById('dev-code-display');
        if (el) {
          const range = document.createRange();
          range.selectNodeContents(el);
          const sel = window.getSelection();
          sel?.removeAllRanges();
          sel?.addRange(range);
        }
      }
    }
  };

  const handleSendCode = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!email) return;
    setIsLoading(true);
    setError('');

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

      if (res.ok) {
        setCodeSent(true);
        setCodeVerified(false);
        setCountdown(600); // 10 min countdown
        if (data.dev && data.code) {
          setDevCode(data.code);
          setIsDevMode(true);
          setCode(data.code);
          toast({
            title: language === 'en' ? '📧 Dev Mode - Code Auto-Filled' : '📧 ডেভ মোড - কোড অটো-ফিল করা হয়েছে',
            description: language === 'en'
              ? `Code: ${data.code} (SMTP not configured - code auto-filled below)`
              : `কোড: ${data.code} (SMTP কনফিগার করা নেই - কোড নিচে অটো-ফিল করা হয়েছে)`,
            duration: 8000,
          });
        } else {
          setIsDevMode(false);
          toast({
            title: language === 'en' ? '✅ Code Sent!' : '✅ কোড পাঠানো হয়েছে!',
            description: data.message,
            duration: 5000,
          });
        }
        // Auto-focus first OTP digit
        setTimeout(() => {
          const firstOtp = document.getElementById('otp-digit-0');
          firstOtp?.focus();
        }, 100);
      } else {
        setError(data.error || (language === 'en' ? 'Failed to send code' : 'কোড পাঠাতে ব্যর্থ'));
      }
    } catch {
      setError(language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি');
    } finally {
      setIsLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (!code || code.length < 6) return;
    setIsLoading(true);
    setError('');

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

      if (res.ok) {
        setCodeVerified(true);
        // Auto-focus new password field
        setTimeout(() => {
          const pwInput = document.getElementById('new-password');
          pwInput?.focus();
        }, 100);
      } else {
        setError(data.error || (language === 'en' ? 'Invalid code' : 'ভুল কোড'));
      }
    } catch {
      setError(language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি');
    } finally {
      setIsLoading(false);
    }
  };

  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPassword || !confirmPassword) return;

    if (newPassword.length < 6) {
      setError(t('profile.minPasswordLength', language));
      return;
    }

    if (newPassword !== confirmPassword) {
      setError(t('auth.passwordMismatch', language));
      return;
    }

    setIsLoading(true);
    setError('');

    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code, newPassword }),
      });
      const data = await res.json();

      if (res.ok) {
        toast({
          title: t('auth.resetSuccess', language),
          description: language === 'en' ? 'You can now login with your new password' : 'আপনি এখন নতুন পাসওয়ার্ড দিয়ে লগইন করতে পারেন',
          duration: 5000,
        });
        onBack();
      } else {
        setError(data.error || (language === 'en' ? 'Failed to reset password' : 'পাসওয়ার্ড রিসেট করতে ব্যর্থ'));
      }
    } catch {
      setError(language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি');
    } finally {
      setIsLoading(false);
    }
  };

  const handleResendCode = async () => {
    setIsLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (res.ok) {
        setCountdown(600);
        toast({
          title: language === 'en' ? 'Code Resent!' : 'কোড আবার পাঠানো হয়েছে!',
          description: data.message,
          duration: 5000,
        });
        if (data.dev && data.code) {
          setDevCode(data.code);
          setIsDevMode(true);
          setCode(data.code);
        }
      }
    } catch {
      setError(language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি');
    } finally {
      setIsLoading(false);
    }
  };

  // Auto-verify code when all 6 digits are entered
  useEffect(() => {
    if (!codeSent || codeVerified || code.length < 6) return;
    
    const verifyCode = async () => {
      setIsLoading(true);
      setError('');
      try {
        const res = await fetch('/api/auth/forgot-password', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, code }),
        });
        const data = await res.json();
        if (res.ok) {
          setCodeVerified(true);
          setTimeout(() => {
            const pwInput = document.getElementById('new-password');
            pwInput?.focus();
          }, 100);
        } else {
          setError(data.error || (language === 'en' ? 'Invalid code' : 'ভুল কোড'));
        }
      } catch {
        setError(language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি');
      } finally {
        setIsLoading(false);
      }
    };
    
    verifyCode();
  }, [code, codeSent, codeVerified, email, language]);

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex flex-col items-center gap-1.5 py-1">
        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
          <KeyRound className="h-6 w-6 text-primary" />
        </div>
        <h3 className="text-base font-semibold">{t('auth.resetPassword', language)}</h3>
        <p className="text-center text-xs text-muted-foreground">
          {t('auth.enterEmail', language)}
        </p>
      </div>

      {/* Dev Mode Banner */}
      {isDevMode && codeSent && (
        <div className="rounded-xl border-2 border-dashed border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3">
          <div className="flex items-center gap-2 mb-2">
            <div className="flex h-5 w-5 items-center justify-center rounded-full bg-amber-400">
              <span className="text-[10px] font-bold text-amber-900">!</span>
            </div>
            <span className="text-xs font-bold text-amber-700 dark:text-amber-400">
              {language === 'en' ? 'DEV MODE - SMTP Not Configured' : 'ডেভ মোড - SMTP কনফিগার করা নেই'}
            </span>
          </div>
          <div className="flex items-center gap-2 rounded-lg bg-white dark:bg-amber-900/30 p-2.5">
            <span className="text-xs text-muted-foreground">
              {language === 'en' ? 'Your code:' : 'আপনার কোড:'}
            </span>
            <span id="dev-code-display" className="flex-1 text-center font-mono text-xl font-black tracking-[0.3em] text-primary">
              {devCode}
            </span>
            <button
              type="button"
              onClick={handleCopyCode}
              className="flex h-7 w-7 items-center justify-center rounded-md bg-primary/10 hover:bg-primary/20 transition-colors"
              title="Copy code"
            >
              {copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5 text-primary" />}
            </button>
          </div>
          <p className="mt-1.5 text-[10px] text-amber-600 dark:text-amber-400/70 text-center">
            {language === 'en'
              ? 'In production, this code will be sent to your email'
              : 'প্রোডাকশনে, এই কোড আপনার ইমেইলে পাঠানো হবে'}
          </p>
        </div>
      )}

      {error && (
        <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">
          {error}
        </div>
      )}

      {/* Single inline form - all fields on same page */}
      <form onSubmit={codeVerified ? handleResetPassword : (e) => { e.preventDefault(); if (!codeSent) handleSendCode(); }} className="space-y-4">
        {/* Email Field - always visible */}
        <div className="space-y-2">
          <Label htmlFor="forgot-email">{t('auth.email', language)}</Label>
          <div className="flex gap-2">
            <div className="relative flex-1">
              <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="forgot-email"
                type="email"
                placeholder="name@example.com"
                value={email}
                onChange={(e) => { setEmail(e.target.value); setError(''); }}
                className="pl-9"
                disabled={codeSent}
                required
              />
            </div>
            {!codeSent && (
              <Button
                type="submit"
                className="shrink-0 bg-gradient-to-r from-primary to-primary/90 font-semibold"
                disabled={isLoading || !email}
              >
                {isLoading ? (
                  <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                ) : (
                  t('auth.sendCode', language)
                )}
              </Button>
            )}
          </div>
          {codeSent && (
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">
                <CheckCircle2 className="h-3 w-3" />
                <span>{language === 'en' ? 'Code sent to this email' : 'এই ইমেইলে কোড পাঠানো হয়েছে'}</span>
              </div>
              {!codeVerified && (
                <button
                  type="button"
                  onClick={() => { setCodeSent(false); setCode(''); setError(''); }}
                  className="text-xs text-muted-foreground hover:text-foreground"
                >
                  {language === 'en' ? 'Change' : 'পরিবর্তন'}
                </button>
              )}
            </div>
          )}
        </div>

        {/* OTP Code Input - appears after code is sent */}
        {codeSent && !codeVerified && (
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label className="text-sm">{t('auth.enterCode', language)}</Label>
              <div className="flex items-center gap-2">
                {countdown > 0 && (
                  <div className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Timer className="h-3 w-3" />
                    <span>{formatCountdown(countdown)}</span>
                  </div>
                )}
                <button
                  type="button"
                  onClick={handleResendCode}
                  disabled={isLoading || countdown > 540}
                  className="flex items-center gap-1 text-xs text-primary hover:underline disabled:opacity-50"
                >
                  <RefreshCw className={`h-3 w-3 ${isLoading ? 'animate-spin' : ''}`} />
                  {t('auth.resendCode', language)}
                </button>
              </div>
            </div>
            <div className="flex justify-center gap-2">
              {[0, 1, 2, 3, 4, 5].map((index) => (
                <input
                  key={index}
                  id={`otp-digit-${index}`}
                  type="text"
                  inputMode="numeric"
                  maxLength={1}
                  value={code[index] || ''}
                  onChange={(e) => {
                    const val = e.target.value.replace(/\D/g, '');
                    if (val) {
                      const newCode = code.split('');
                      newCode[index] = val.slice(-1);
                      setCode(newCode.join(''));
                      setError('');
                      if (index < 5) {
                        const nextInput = document.getElementById(`otp-digit-${index + 1}`);
                        nextInput?.focus();
                      }
                    } else {
                      const newCode = code.split('');
                      newCode[index] = '';
                      setCode(newCode.join(''));
                      setError('');
                    }
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Backspace' && !code[index] && index > 0) {
                      const prevInput = document.getElementById(`otp-digit-${index - 1}`);
                      prevInput?.focus();
                    }
                  }}
                  className={`h-12 w-10 rounded-lg border-2 text-center text-lg font-bold transition-colors focus:outline-none focus:ring-2 focus:ring-primary/30 ${
                    code[index] ? 'border-primary bg-primary/5' : 'border-muted-foreground/20'
                  }`}
                />
              ))}
            </div>
            {isLoading && code.length === 6 && (
              <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
                <span className="h-3 w-3 animate-spin rounded-full border-2 border-primary border-t-transparent" />
                <span>{language === 'en' ? 'Verifying...' : 'যাচাই করা হচ্ছে...'}</span>
              </div>
            )}
          </div>
        )}

        {/* Verified indicator */}
        {codeVerified && (
          <div className="flex items-center gap-2 rounded-lg border border-emerald-200 bg-emerald-50 dark:bg-emerald-950/20 dark:border-emerald-800/30 p-3">
            <CheckCircle2 className="h-4 w-4 text-emerald-600 dark:text-emerald-400 shrink-0" />
            <span className="text-xs font-medium text-emerald-700 dark:text-emerald-400">
              {language === 'en' ? 'Code verified successfully!' : 'কোড সফলভাবে যাচাই হয়েছে!'}
            </span>
          </div>
        )}

        {/* Password Fields - appear after code is verified */}
        {codeVerified && (
          <>
            <div className="space-y-2">
              <Label htmlFor="new-password">{t('auth.newPassword', language)}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="new-password"
                  type="password"
                  placeholder="••••••••"
                  value={newPassword}
                  onChange={(e) => { setNewPassword(e.target.value); setError(''); }}
                  className="pl-9"
                  required
                  minLength={6}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirm-password">{t('auth.confirmPassword', language)}</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  id="confirm-password"
                  type="password"
                  placeholder="••••••••"
                  value={confirmPassword}
                  onChange={(e) => { setConfirmPassword(e.target.value); setError(''); }}
                  className="pl-9"
                  required
                  minLength={6}
                />
              </div>
            </div>

            <Button
              type="submit"
              className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
              disabled={isLoading}
            >
              {isLoading ? (
                <span className="flex items-center gap-2">
                  <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                  {t('common.loading', language)}
                </span>
              ) : (
                t('auth.resetPassword', language)
              )}
            </Button>
          </>
        )}
      </form>

      <Separator />
      <button
        type="button"
        onClick={onBack}
        className="flex w-full items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="h-4 w-4" />
        {t('auth.backToLogin', language)}
      </button>
    </div>
  );
}

export default function AuthModule() {
  const { language, setUser, setCurrentSection } = useAppStore();
  const { toast } = useToast();

  const [activeTab, setActiveTab] = useState<string>('login');
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [loginError, setLoginError] = useState('');
  const [showForgotPassword, setShowForgotPassword] = useState(false);

  // Login form
  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');

  // Signup form
  const [signupName, setSignupName] = useState('');
  const [signupEmail, setSignupEmail] = useState('');
  const [signupPhone, setSignupPhone] = useState('');
  const [signupPassword, setSignupPassword] = useState('');
  const [selectedRoles, setSelectedRoles] = useState<string[]>(['general']);

  const handleRoleToggle = (roleId: string) => {
    setSelectedRoles((prev) =>
      prev.includes(roleId)
        ? prev.filter((r) => r !== roleId)
        : [...prev, roleId]
    );
  };

  // Helper: Try admin login and navigate to admin section within SPA
  const tryAdminLogin = async (email: string, password: string): Promise<boolean> => {
    try {
      const adminRes = await fetch('/api/admin/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      if (!adminRes.ok) return false;
      const adminData = await adminRes.json();
      if (adminData.success && adminData.admin) {
        const { setAdminUser, setCurrentSection } = useAppStore.getState();
        setAdminUser({
          id: String(adminData.admin.id),
          name: String(adminData.admin.name),
          email: String(adminData.admin.email),
          role: String(adminData.admin.role),
          avatar: adminData.admin.avatar ? String(adminData.admin.avatar) : undefined,
          phone: adminData.admin.phone ? String(adminData.admin.phone) : undefined,
          permissions: adminData.admin.permissions as any,
        }, String(adminData.admin.token));
        setCurrentSection('admin');
        toast({
          title: language === 'en' ? 'Admin Login Successful!' : 'অ্যাডমিন লগইন সফল!',
          description: `${language === 'en' ? 'Welcome back' : 'ফিরে আসুন'}, ${adminData.admin.name}`,
          duration: 3000,
        });
        return true;
      }
    } catch {
      // Admin auth failed
    }
    return false;
  };

  // Check if email looks like an admin email
  const isAdminEmail = (email: string): boolean => {
    const adminPatterns = ['superadmin@needyfy.com', 'admin@needyfy.com', 'admin@', 'superadmin@'];
    const normalized = email.trim().toLowerCase();
    return adminPatterns.some(p => p.endsWith('@') ? normalized.startsWith(p) && normalized.endsWith('needyfy.com') : normalized === p);
  };

  const performLogin = async (email: string, password: string) => {
    setIsLoading(true);
    setLoginError('');

    if (isAdminEmail(email)) {
      const adminSuccess = await tryAdminLogin(email, password);
      if (adminSuccess) {
        setIsLoading(false);
        return;
      }
      setLoginError(language === 'en' ? 'Invalid admin credentials' : 'অ্যাডমিন ক্রেডেনশিয়াল ভুল');
      setIsLoading(false);
      return;
    }

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

      const data = await res.json();

      if (res.ok) {
        const userRoles = data.user.roles
          ? data.user.roles.split(',').map((r: string) => r.trim())
          : ['general'];

        setUser({
          id: data.user.id,
          name: data.user.name,
          email: data.user.email,
          phone: data.user.phone || undefined,
          avatar: data.user.avatar || undefined,
          roles: userRoles,
        }, data.token || null);

        const hasOwnerRole = userRoles.includes('houseOwner') || userRoles.includes('shopOwner');
        const isAdmin = userRoles.includes('admin') || userRoles.includes('super_admin');

        if (isAdmin) {
          const adminSuccess = await tryAdminLogin(email, password);
          if (adminSuccess) return;
        }

        const targetSection = hasOwnerRole ? 'owner-dashboard' : 'home';
        setCurrentSection(targetSection as any);
        toast({
          title: language === 'en' ? 'Login Successful!' : 'লগইন সফল!',
          description: `${language === 'en' ? 'Welcome back' : 'ফিরে আসুন'}, ${data.user.name}`,
          duration: 3000,
        });
      } else {
        const adminSuccess = await tryAdminLogin(email, password);
        if (adminSuccess) return;
        setLoginError(data.error || 'Invalid credentials');
      }
    } catch {
      const adminSuccess = await tryAdminLogin(email, password);
      if (adminSuccess) return;
      setLoginError('Network error. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!loginEmail || !loginPassword) return;
    await performLogin(loginEmail, loginPassword);
  };

  const handleSignup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!signupName || !signupEmail || !signupPassword) return;
    if (selectedRoles.length === 0) return;

    setIsLoading(true);

    try {
      const res = await fetch('/api/auth', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: signupName,
          email: signupEmail,
          phone: signupPhone || undefined,
          password: signupPassword,
          roles: selectedRoles.join(','),
        }),
      });

      const data = await res.json();

      if (res.ok) {
        const userRoles = data.user.roles
          ? data.user.roles.split(',').map((r: string) => r.trim())
          : selectedRoles;

        setUser({
          id: data.user.id,
          name: data.user.name,
          email: data.user.email,
          phone: data.user.phone || undefined,
          roles: userRoles,
        }, data.token || null);

        const hasOwnerRole = userRoles.includes('houseOwner') || userRoles.includes('shopOwner');
        setCurrentSection(hasOwnerRole ? 'owner-dashboard' as any : 'home');

        toast({
          title: language === 'en' ? 'Account Created!' : 'অ্যাকাউন্ট তৈরি হয়েছে!',
          description: language === 'en' ? 'Welcome to Needyfy!' : 'Needyfy-তে স্বাগতম!',
          duration: 3000,
        });
      } else {
        toast({
          title: language === 'en' ? 'Signup Failed' : 'সাইনআপ ব্যর্থ',
          description: data.error || 'Please try again',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Network Error' : 'নেটওয়ার্ক ত্রুটি',
        description: 'Please try again',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleDemoLogin = async (account: typeof demoAccounts[0]) => {
    await performLogin(account.email, account.password);
  };

  const getColorClasses = (color: string) => {
    switch (color) {
      case 'emerald':
        return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400';
      case 'amber':
        return 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400';
      case 'blue':
        return 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400';
      case 'orange':
        return 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400';
      default:
        return 'bg-gray-100 text-gray-700 dark:bg-gray-950/30 dark:text-gray-400';
    }
  };

  return (
    <div className="flex min-h-[calc(100vh-8rem)] items-center justify-center px-4 py-6 sm:py-8">
      <div className="w-full max-w-md">
        {/* Orange Gradient Header */}
        <div className="mb-6 rounded-t-2xl bg-gradient-to-br from-primary via-primary/90 to-primary/80 px-6 py-8 text-center">
          <img
            src="/logo-needyfy.png"
            alt="Needyfy Logo"
            className="mx-auto mb-3 h-16 w-16 rounded-2xl object-cover shadow-lg"
          />
          <h1 className="text-3xl font-bold tracking-tight text-white">
            {showForgotPassword ? t('auth.resetPassword', language) : t('app.name', language)}
          </h1>
          <p className="mt-1 text-sm text-primary-foreground/80">
            {showForgotPassword
              ? (language === 'en' ? 'Recover your account' : 'আপনার অ্যাকাউন্ট পুনরুদ্ধার করুন')
              : t('app.tagline', language)}
          </p>
        </div>

        <Card className="rounded-t-none border-t-0 shadow-lg">
          <CardContent className="pt-6">
            {showForgotPassword ? (
              <ForgotPassword onBack={() => setShowForgotPassword(false)} />
            ) : (
              <Tabs value={activeTab} onValueChange={setActiveTab}>
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="login" className="text-sm">
                    {t('auth.login', language)}
                  </TabsTrigger>
                  <TabsTrigger value="signup" className="text-sm">
                    {t('auth.signup', language)}
                  </TabsTrigger>
                </TabsList>

                {/* Login Form */}
                <TabsContent value="login" className="mt-0">
                  <div className="space-y-4">
                    <form onSubmit={handleLogin} className="space-y-4">
                      {loginError && (
                        <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">
                          {loginError}
                        </div>
                      )}

                      {/* Email */}
                      <div className="space-y-2">
                        <Label htmlFor="login-email">
                          {t('auth.email', language)}
                        </Label>
                        <div className="relative">
                          <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                          <Input
                            id="login-email"
                            type="email"
                            placeholder="name@example.com"
                            value={loginEmail}
                            onChange={(e) => { setLoginEmail(e.target.value); setLoginError(''); }}
                            className="pl-9"
                            required
                          />
                        </div>
                      </div>

                      {/* Password */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label htmlFor="login-password">
                            {t('auth.password', language)}
                          </Label>
                          <button
                            type="button"
                            className="text-xs text-primary hover:underline"
                            onClick={() => setShowForgotPassword(true)}
                          >
                            {t('auth.forgotPassword', language)}
                          </button>
                        </div>
                        <div className="relative">
                          <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                          <Input
                            id="login-password"
                            type={showPassword ? 'text' : 'password'}
                            placeholder="••••••••"
                            value={loginPassword}
                            onChange={(e) => { setLoginPassword(e.target.value); setLoginError(''); }}
                            className="pl-9 pr-10"
                            required
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                          >
                            {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                          </button>
                        </div>
                      </div>

                      {/* Submit */}
                      <Button
                        type="submit"
                        className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
                        disabled={isLoading}
                      >
                        {isLoading ? (
                          <span className="flex items-center gap-2">
                            <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                            {t('common.loading', language)}
                          </span>
                        ) : (
                          t('auth.login', language)
                        )}
                      </Button>

                      <p className="text-center text-xs text-muted-foreground">
                        {t('auth.noAccount', language)}{' '}
                        <button
                          type="button"
                          className="font-semibold text-primary hover:underline"
                          onClick={() => setActiveTab('signup')}
                        >
                          {t('auth.signup', language)}
                        </button>
                      </p>
                    </form>

                    {/* Demo Accounts - Auto Login */}
                    <div className="mt-5">
                      <Separator className="mb-4" />
                      <p className="mb-3 text-center text-xs font-medium text-muted-foreground">
                        {language === 'en' ? 'Quick Demo Login' : 'দ্রুত ডেমো লগইন'}
                      </p>
                      <div className="space-y-2">
                        {demoAccounts.map((account) => {
                          const Icon = account.icon;
                          return (
                            <button
                              key={account.email}
                              type="button"
                              onClick={() => handleDemoLogin(account)}
                              disabled={isLoading}
                              className="flex w-full items-center gap-3 rounded-lg border border-dashed border-border bg-accent/30 px-3 py-2.5 text-left transition-colors hover:bg-accent/60 hover:border-primary/30 disabled:opacity-50"
                            >
                              <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${getColorClasses(account.color)}`}>
                                <Icon className="h-4 w-4" />
                              </div>
                              <div className="flex-1">
                                <p className="text-xs font-semibold text-foreground">
                                  {language === 'en' ? account.label : account.labelBn}
                                </p>
                                <p className="text-[10px] text-muted-foreground">{account.email}</p>
                              </div>
                              <span className="text-[10px] font-medium text-primary">
                                {isLoading ? '...' : (language === 'en' ? 'Login' : 'লগইন')}
                              </span>
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                </TabsContent>

                {/* Signup Form */}
                <TabsContent value="signup" className="mt-0">
                  <form onSubmit={handleSignup} className="space-y-4">
                    {/* Full Name */}
                    <div className="space-y-2">
                      <Label htmlFor="signup-name">
                        {t('auth.name', language)}
                      </Label>
                      <div className="relative">
                        <User className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                          id="signup-name"
                          type="text"
                          placeholder={t('auth.name', language)}
                          value={signupName}
                          onChange={(e) => setSignupName(e.target.value)}
                          className="pl-9"
                          required
                        />
                      </div>
                    </div>

                    {/* Email */}
                    <div className="space-y-2">
                      <Label htmlFor="signup-email">
                        {t('auth.email', language)}
                      </Label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                          id="signup-email"
                          type="email"
                          placeholder="name@example.com"
                          value={signupEmail}
                          onChange={(e) => setSignupEmail(e.target.value)}
                          className="pl-9"
                          required
                        />
                      </div>
                    </div>

                    {/* Phone */}
                    <div className="space-y-2">
                      <Label htmlFor="signup-phone">
                        {t('auth.phone', language)}
                      </Label>
                      <div className="relative">
                        <Phone className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                          id="signup-phone"
                          type="tel"
                          placeholder="+880 1XXX-XXXXXX"
                          value={signupPhone}
                          onChange={(e) => setSignupPhone(e.target.value)}
                          className="pl-9"
                        />
                      </div>
                    </div>

                    {/* Password */}
                    <div className="space-y-2">
                      <Label htmlFor="signup-password">
                        {t('auth.password', language)}
                      </Label>
                      <div className="relative">
                        <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                          id="signup-password"
                          type={showPassword ? 'text' : 'password'}
                          placeholder="••••••••"
                          value={signupPassword}
                          onChange={(e) => setSignupPassword(e.target.value)}
                          className="pl-9 pr-10"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                        >
                          {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </button>
                      </div>
                    </div>

                    {/* Role Selection */}
                    <div className="space-y-3">
                      <Label className="text-sm font-semibold">{t('auth.selectRoles', language)}</Label>
                      <p className="text-[11px] text-muted-foreground">
                        {language === 'en'
                          ? 'Choose House Owner or Shop Owner to list properties'
                          : 'সম্পত্তি তালিকাভুক্ত করতে বাড়ির মালিক বা দোকান মালিক নির্বাচন করুন'}
                      </p>
                      <div className="grid grid-cols-2 gap-2">
                        {roleOptions.map((role) => {
                          const Icon = role.icon;
                          const isSelected = selectedRoles.includes(role.id);

                          return (
                            <label
                              key={role.id}
                              className={`flex cursor-pointer items-center gap-2 rounded-lg border p-3 transition-colors duration-150 ${
                                isSelected
                                  ? 'border-primary bg-primary/5 text-primary'
                                  : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-accent'
                              }`}
                            >
                              <Checkbox
                                checked={isSelected}
                                onCheckedChange={() => handleRoleToggle(role.id)}
                                className="sr-only"
                              />
                              <Icon className="h-4 w-4" />
                              <span className="text-xs font-medium">
                                {t(role.labelKey, language)}
                              </span>
                            </label>
                          );
                        })}
                      </div>
                    </div>

                    {/* Submit */}
                    <Button
                      type="submit"
                      className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
                      disabled={isLoading || selectedRoles.length === 0}
                    >
                      {isLoading ? t('common.loading', language) : t('auth.signup', language)}
                    </Button>

                    <p className="text-center text-xs text-muted-foreground">
                      {t('auth.hasAccount', language)}{' '}
                      <button
                        type="button"
                        className="font-semibold text-primary hover:underline"
                        onClick={() => setActiveTab('login')}
                      >
                        {t('auth.login', language)}
                      </button>
                    </p>
                  </form>
                </TabsContent>
              </Tabs>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
