'use client';

import { useState, useRef, useEffect } from 'react';
import { useAppStore } from '@/lib/store';
import { useAppEnv } from '@/lib/env-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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { useToast } from '@/hooks/use-toast';
import { Separator } from '@/components/ui/separator';
import { Mail, Lock, Phone, User, GraduationCap, Home, Store, Eye, EyeOff, ArrowLeft, KeyRound, CheckCircle2 } 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: 'blue' },
];

type ForgotPasswordStep = 'email' | 'code' | 'newPassword' | 'success';

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

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

  // 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']);

  // Forgot Password state
  const [forgotDialogOpen, setForgotDialogOpen] = useState(false);
  const [forgotStep, setForgotStep] = useState<ForgotPasswordStep>('email');
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotCode, setForgotCode] = useState('');
  const [devModeCode, setDevModeCode] = useState(''); // Only used in dev mode (SMTP not configured)
  const [newPassword, setNewPassword] = useState('');
  const [confirmNewPassword, setConfirmNewPassword] = useState('');
  const [forgotLoading, setForgotLoading] = useState(false);
  const [codeError, setCodeError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const codeInputRefs = useRef<(HTMLInputElement | null)[]>([]);

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

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

    try {
      // First, try regular user auth
      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'];

        // Check if this is an admin/super_admin - redirect to admin portal
        if (userRoles.includes('admin') || userRoles.includes('super_admin')) {
          // Authenticate via admin endpoint to get admin token
          try {
            const adminRes = await fetch('/api/admin/auth', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ email, password }),
            });
            const adminData = await adminRes.json();
            if (adminData.success) {
              toast({
                title: language === 'en' ? 'Welcome to Admin Portal!' : 'অ্যাডমিন পোর্টালে স্বাগতম!',
                description: `${language === 'en' ? 'Redirecting' : 'রিডাইরেক্ট হচ্ছে'}...`,
                duration: 2000,
              });
              // Set admin state BEFORE redirect so admin page picks it up
              const { useAppStore: storeRef } = await import('@/lib/store');
              storeRef.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,
              }, adminData.admin.token);
              storeRef.getState().setAdminTab('dashboard');
              // Small delay then redirect
              setTimeout(() => { window.location.href = '/admin'; }, 100);
              return;
            }
          } catch {
            // Fallback: just redirect to /admin
            window.location.href = '/admin';
            return;
          }
        }

        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,
        });

        // Navigate based on role
        const hasOwnerRole = userRoles.includes('houseOwner') || userRoles.includes('shopOwner');
        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 {
        // If regular auth fails, try admin auth directly
        try {
          const adminRes = await fetch('/api/admin/auth', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email, password }),
          });
          const adminData = await adminRes.json();
          if (adminData.success) {
            toast({
              title: language === 'en' ? 'Welcome to Admin Portal!' : 'অ্যাডমিন পোর্টালে স্বাগতম!',
              description: `${language === 'en' ? 'Redirecting' : 'রিডাইরেক্ট হচ্ছে'}...`,
              duration: 2000,
            });
            const { useAppStore: storeRef } = await import('@/lib/store');
            storeRef.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,
            }, adminData.admin.token);
            storeRef.getState().setAdminTab('dashboard');
            setTimeout(() => { window.location.href = '/admin'; }, 100);
            return;
          }
        } catch { /* ignore */ }
        setLoginError(data.error || 'Invalid credentials');
      }
    } catch {
      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,
        });

        // Navigate based on role
        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]) => {
    // Auto-login directly with demo credentials
    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-sky-100 text-sky-700 dark:bg-sky-950/30 dark:text-sky-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';
    }
  };

  // Forgot Password handlers
  const openForgotDialog = () => {
    setForgotStep('email');
    setForgotEmail('');
    setForgotCode('');
    setDevModeCode('');
    setNewPassword('');
    setConfirmNewPassword('');
    setCodeError('');
    setPasswordError('');
    setForgotDialogOpen(true);
  };

  const handleSendCode = async () => {
    if (!forgotEmail) return;
    setForgotLoading(true);
    setCodeError('');

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

      if (res.ok) {
        if (data.dev && data.code) {
          // Dev mode: SMTP not configured, code returned for testing
          setDevModeCode(data.code);
          toast({
            title: language === 'en' ? '⚠️ Dev Mode - Verification Code' : '⚠️ ডেভ মোড - ভেরিফিকেশন কোড',
            description: `${language === 'en' ? 'SMTP not configured. Your code is' : 'SMTP কনফিগার করা নেই। আপনার কোড হলো'}: ${data.code}`,
            duration: 15000,
          });
        } else {
          // Production: code sent to email
          toast({
            title: language === 'en' ? 'Code Sent!' : 'কোড পাঠানো হয়েছে!',
            description: language === 'en'
              ? 'A verification code has been sent to your email'
              : 'আপনার ইমেইলে একটি ভেরিফিকেশন কোড পাঠানো হয়েছে',
            duration: 5000,
          });
        }
        setForgotStep('code');
      } else {
        toast({
          title: language === 'en' ? 'Error' : 'ত্রুটি',
          description: data.error || (language === 'en' ? 'Failed to send code' : 'কোড পাঠাতে ব্যর্থ'),
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Error' : 'ত্রুটি',
        description: language === 'en' ? 'Failed to send verification code' : 'ভেরিফিকেশন কোড পাঠাতে ব্যর্থ',
        variant: 'destructive',
      });
    } finally {
      setForgotLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (forgotCode.length !== 6) return;
    setForgotLoading(true);
    setCodeError('');

    try {
      // Verify the code against the server using the dedicated verify endpoint
      const res = await fetch('/api/auth/forgot-password', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: forgotEmail,
          code: forgotCode,
        }),
      });

      if (res.ok) {
        // Code is valid — move to new password step
        setForgotStep('newPassword');
      } else {
        const data = await res.json();
        setCodeError(data.error || (language === 'en' ? 'Invalid code. Please try again.' : 'ভুল কোড। আবার চেষ্টা করুন।'));
      }
    } catch {
      // Network error — fallback to dev mode code check if available
      if (devModeCode && forgotCode === devModeCode) {
        setForgotStep('newPassword');
      } else {
        setCodeError(language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। আবার চেষ্টা করুন।');
      }
    } finally {
      setForgotLoading(false);
    }
  };

  const handleSetNewPassword = async () => {
    if (!newPassword || !confirmNewPassword) {
      setPasswordError(language === 'en' ? 'Please fill in all fields' : 'সব ক্ষেত্র পূরণ করুন');
      return;
    }
    if (newPassword !== confirmNewPassword) {
      setPasswordError(language === 'en' ? 'Passwords do not match' : 'পাসওয়ার্ড মিলছে না');
      return;
    }
    if (newPassword.length < 6) {
      setPasswordError(language === 'en' ? 'Password must be at least 6 characters' : 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে');
      return;
    }

    setForgotLoading(true);
    setPasswordError('');

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

      const data = await res.json();

      if (res.ok) {
        setForgotStep('success');
        toast({
          title: language === 'en' ? 'Success!' : 'সফল!',
          description: t('auth.passwordResetSuccess', language),
          duration: 3000,
        });
      } else {
        setPasswordError(data.error || (language === 'en' ? 'Failed to reset password' : 'পাসওয়ার্ড রিসেট ব্যর্থ'));
      }
    } catch {
      setPasswordError(language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। আবার চেষ্টা করুন।');
    } finally {
      setForgotLoading(false);
    }
  };

  const handleBackToLogin = () => {
    setForgotDialogOpen(false);
    setForgotStep('email');
  };

  // Handle individual digit input for OTP
  const handleDigitChange = (index: number, value: string) => {
    if (value.length > 1) {
      // Handle paste - fill all inputs
      const digits = value.replace(/\D/g, '').slice(0, 6).split('');
      const newCode = forgotCode.split('');
      digits.forEach((digit, i) => {
        if (index + i < 6) {
          newCode[index + i] = digit;
        }
      });
      setForgotCode(newCode.join(''));
      // Focus the next empty or last input
      const nextIndex = Math.min(index + digits.length, 5);
      codeInputRefs.current[nextIndex]?.focus();
      return;
    }

    const newCode = forgotCode.split('');
    newCode[index] = value.replace(/\D/g, '');
    setForgotCode(newCode.join(''));

    if (value && index < 5) {
      codeInputRefs.current[index + 1]?.focus();
    }
  };

  const handleDigitKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !forgotCode[index] && index > 0) {
      codeInputRefs.current[index - 1]?.focus();
    }
  };

  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={appLogoUrl || '/logo-needyfy.png'}
            alt={`${appName || 'Needyfy'} Logo`}
            className="mx-auto mb-3 h-16 w-16 rounded-2xl object-cover shadow-lg"
            onError={(e) => { (e.target as HTMLImageElement).src = '/logo-needyfy.png'; }}
          />
          <h1 className="text-3xl font-bold tracking-tight text-white">
            {appName || t('app.name', language)}
          </h1>
          <p className="mt-1 text-sm text-primary-foreground/80">
            {appTagline || t('app.tagline', language)}
          </p>
        </div>

        <Card className="rounded-t-none border-t-0 shadow-lg">
          <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">
              <CardContent className="pt-6">
                <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={openForgotDialog}
                      >
                        {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>
              </CardContent>
            </TabsContent>

            {/* Signup Form */}
            <TabsContent value="signup" className="mt-0">
              <CardContent className="pt-6">
                <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 - Prominent */}
                  <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>
              </CardContent>
            </TabsContent>
          </Tabs>
        </Card>
      </div>

      {/* Forgot Password Dialog */}
      <Dialog open={forgotDialogOpen} onOpenChange={(open) => {
        if (!open) {
          // Reset state when closing
          setForgotStep('email');
          setForgotEmail('');
          setForgotCode('');
          setDevModeCode('');
          setNewPassword('');
          setConfirmNewPassword('');
          setCodeError('');
          setPasswordError('');
        }
        setForgotDialogOpen(open);
      }}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {forgotStep !== 'email' && (
                <button
                  onClick={() => {
                    if (forgotStep === 'code') setForgotStep('email');
                    else if (forgotStep === 'newPassword') setForgotStep('code');
                  }}
                  className="rounded-full p-1 hover:bg-accent"
                >
                  <ArrowLeft className="h-4 w-4" />
                </button>
              )}
              {forgotStep === 'success'
                ? t('auth.passwordResetSuccess', language)
                : t('auth.resetPassword', language)}
            </DialogTitle>
            <DialogDescription>
              {forgotStep === 'email' && t('auth.enterEmail', language)}
              {forgotStep === 'code' && t('auth.enterCode', language)}
              {forgotStep === 'newPassword' &&
                (language === 'en'
                  ? 'Enter your new password'
                  : 'আপনার নতুন পাসওয়ার্ড লিখুন')}
              {forgotStep === 'success' &&
                (language === 'en'
                  ? 'Your password has been reset successfully. You can now login with your new password.'
                  : 'আপনার পাসওয়ার্ড সফলভাবে রিসেট হয়েছে। আপনি এখন নতুন পাসওয়ার্ড দিয়ে লগইন করতে পারেন।')}
            </DialogDescription>
          </DialogHeader>

          {/* Step 1: Email Input */}
          {forgotStep === 'email' && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="forgot-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="forgot-email"
                    type="email"
                    placeholder="name@example.com"
                    value={forgotEmail}
                    onChange={(e) => setForgotEmail(e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>
              <Button
                onClick={handleSendCode}
                className="w-full"
                disabled={!forgotEmail || forgotLoading}
              >
                {forgotLoading ? (
                  <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>
                ) : (
                  <>
                    <KeyRound className="mr-2 h-4 w-4" />
                    {t('auth.sendCode', language)}
                  </>
                )}
              </Button>
            </div>
          )}

          {/* Step 2: Code Verification */}
          {forgotStep === 'code' && (
            <div className="space-y-4">
              <div className="space-y-3">
                <Label>{t('auth.verificationCode', language)}</Label>
                <div className="flex justify-center gap-2">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <Input
                      key={i}
                      ref={(el) => { codeInputRefs.current[i] = el; }}
                      type="text"
                      inputMode="numeric"
                      maxLength={6}
                      value={forgotCode[i] || ''}
                      onChange={(e) => handleDigitChange(i, e.target.value)}
                      onKeyDown={(e) => handleDigitKeyDown(i, e)}
                      className="h-12 w-10 text-center text-lg font-semibold"
                    />
                  ))}
                </div>
                {codeError && (
                  <p className="text-center text-xs text-destructive">{codeError}</p>
                )}
              </div>
              <Button
                onClick={handleVerifyCode}
                className="w-full"
                disabled={forgotCode.length !== 6 || forgotLoading}
              >
                {forgotLoading ? (
                  <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.verifyCode', language)
                )}
              </Button>
              <p className="text-center text-xs text-muted-foreground">
                {language === 'en' ? "Didn't receive the code? " : 'কোড পাননি? '}
                <button
                  type="button"
                  className="text-primary hover:underline"
                  onClick={handleSendCode}
                >
                  {language === 'en' ? 'Resend' : 'পুনরায় পাঠান'}
                </button>
              </p>
            </div>
          )}

          {/* Step 3: New Password */}
          {forgotStep === 'newPassword' && (
            <div className="space-y-4">
              <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); setPasswordError(''); }}
                    className="pl-9"
                  />
                </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={confirmNewPassword}
                    onChange={(e) => { setConfirmNewPassword(e.target.value); setPasswordError(''); }}
                    className="pl-9"
                  />
                </div>
              </div>
              {passwordError && (
                <p className="text-xs text-destructive">{passwordError}</p>
              )}
              <Button
                onClick={handleSetNewPassword}
                className="w-full"
                disabled={!newPassword || !confirmNewPassword || forgotLoading}
              >
                {forgotLoading ? (
                  <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.setCode', language)
                )}
              </Button>
            </div>
          )}

          {/* Step 4: Success */}
          {forgotStep === 'success' && (
            <div className="flex flex-col items-center gap-4 py-4">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30">
                <CheckCircle2 className="h-8 w-8 text-emerald-600 dark:text-emerald-400" />
              </div>
              <Button onClick={handleBackToLogin} className="w-full">
                {t('auth.backToLogin', language)}
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
