import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '../ui/card';
import { RadioGroup, RadioGroupItem } from '../ui/radio-group';
import { BookOpen, Mail, User, Phone } from 'lucide-react';
import { useAuth } from '../../lib/authContext';
import { useLanguage } from '../../lib/languageContext';
import { translations } from '../../lib/translations';
import { LanguageSwitcher } from '../LanguageSwitcher';

export function Register() {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [phone, setPhone] = useState('');
  const [gender, setGender] = useState('Male');
  const [country, setCountry] = useState('');
  const [birthDate, setBirthDate] = useState('');
  const [role, setRole] = useState<'student' | 'sheikh'>('student');

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { signUp } = useAuth();
  const { language } = useLanguage();
  const navigate = useNavigate();
  const isRTL = language === 'ar';
  const t = translations[language].auth;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      if (!birthDate) throw new Error(t.error?.birthDateRequired || 'تاريخ الميلاد مطلوب');
      if (!country) throw new Error(t.error?.countryRequired || 'الدولة مطلوبة');

      await signUp(email, password, fullName, role, phone, gender, country, birthDate);

      // التنقل لصفحة إكمال الملف الشخصي أو الصفحة الرئيسية حسب منطق التطبيق
      navigate('/complete-profile');
    } catch (err: any) {
      console.error('Registration error:', err);
      setError(err.message || t.error?.general || 'فشل التسجيل، حاول مرة أخرى');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-emerald-50 to-teal-50 p-4">
      <div className="absolute top-4 right-4 z-10">
        <LanguageSwitcher />
      </div>

      <Card className="w-full max-w-md shadow-lg">
        <CardHeader className="text-center">
          <div className="flex justify-center mb-4">
            <div className="w-16 h-16 bg-emerald-600 rounded-full flex items-center justify-center">
              <BookOpen className="h-8 w-8 text-white" />
            </div>
          </div>
          <CardTitle>{t.createAccount}</CardTitle>
          <CardDescription>{t.createAccountDescription}</CardDescription>
        </CardHeader>

        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4 max-h-[75vh] overflow-y-auto pr-2">
            {/* الاسم الكامل */}
            <div className="space-y-2">
              <Label htmlFor="fullName">{t.fullNameLabel}</Label>
              <div className="relative">
                <User className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="fullName"
                  type="text"
                  placeholder={language === 'ar' ? 'ادخل اسمك بالانجليزى ' : 'enter your name in English'}
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>

  
              <div className="space-y-2">
              <Label htmlFor="fullName">{t.fullNameLabel}</Label>
              <div className="relative">
                <User className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="fullName"
                  type="text"
                  placeholder={language === 'ar' ? 'ادخل أسمك بالعربى ' : 'enter your name in Arabic'}
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>
            {/* البريد الإلكتروني */}
            <div className="space-y-2">
              <Label htmlFor="email">{t.emailLabel}</Label>
              <div className="relative">
                <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="email"
                  type="email"
                  placeholder={language === 'ar' ? 'ادخل الايميل ' : 'enter your email'}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>

            {/* كلمة المرور */}
            <div className="space-y-2">
              <Label htmlFor="password">{t.passwordLabel}</Label>
              <Input
                id="password"
                type="password"
                placeholder={language === 'ar' ? 'ادخل الباسورد ' : 'enter your Password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
              />
            </div>

            {/* رقم الهاتف */}
            <div className="space-y-2">
              <Label htmlFor="phone" className={isRTL ? 'text-right block' : ''} >{t.phoneLabel}</Label>
              <div className="relative">
                <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="phone"
                  type="tel"
                  placeholder={language === 'ar' ? 'ادخل رقم التليفون ' : 'enter your Phone Number'}
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                   className={isRTL ? 'pr-10 text-right' : 'pl-10'}
                    dir={isRTL ? 'rtl' : 'ltr'}
                  
                  required
                />
              </div>
            </div>

            {/* الجنس */}
            <div className="space-y-2">
              <Label htmlFor="gender" className={isRTL ? 'text-right block' : ''}>{t.genderLabel}</Label>
              <select
                id="gender"
                value={gender}
                onChange={(e) => setGender(e.target.value)}
                className="w-full border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
              >
                <option value="Male">{t.genderMale}</option>
                <option value="Female">{t.genderFemale}</option>
               
              </select>
            </div>

            {/* الدولة */}
            <div className="space-y-2">
              <Label htmlFor="country">{t.countryLabel}</Label>
              <select
                id="country"
                value={country}
                onChange={(e) => setCountry(e.target.value)}
                className="w-full border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
                required
              >
                <option value="">{language === 'ar' ? 'اختر دولتك' : 'Select your country'}</option>
                <option value="Egypt">{language === 'ar' ? 'مصر' : 'Egypt'}</option>
                <option value="Saudi Arabia">{language === 'ar' ? 'السعودية' : 'Saudi Arabia'}</option>
                <option value="United Arab Emirates">{language === 'ar' ? 'الإمارات' : 'United Arab Emirates'}</option>
                <option value="Kuwait">{language === 'ar' ? 'الكويت' : 'Kuwait'}</option>
                <option value="Qatar">{language === 'ar' ? 'قطر' : 'Qatar'}</option>
                <option value="Jordan">{language === 'ar' ? 'الأردن' : 'Jordan'}</option>
                <option value="Lebanon">{language === 'ar' ? 'لبنان' : 'Lebanon'}</option>
                <option value="Palestine">{language === 'ar' ? 'فلسطين' : 'Palestine'}</option>
                <option value="Syria">{language === 'ar' ? 'سوريا' : 'Syria'}</option>
                <option value="Iraq">{language === 'ar' ? 'العراق' : 'Iraq'}</option>
                <option value="Morocco">{language === 'ar' ? 'المغرب' : 'Morocco'}</option>
                <option value="Tunisia">{language === 'ar' ? 'تونس' : 'Tunisia'}</option>
                <option value="Algeria">{language === 'ar' ? 'الجزائر' : 'Algeria'}</option>
                <option value="Sudan">{language === 'ar' ? 'السودان' : 'Sudan'}</option>
                <option value="Pakistan">{language === 'ar' ? 'باكستان' : 'Pakistan'}</option>
                <option value="Bangladesh">{language === 'ar' ? 'بنجلاديش' : 'Bangladesh'}</option>
                <option value="Indonesia">{language === 'ar' ? 'إندونيسيا' : 'Indonesia'}</option>
                <option value="Malaysia">{language === 'ar' ? 'ماليزيا' : 'Malaysia'}</option>
                <option value="Turkey">{language === 'ar' ? 'تركيا' : 'Turkey'}</option>
                <option value="Other">{language === 'ar' ? 'أخرى' : 'Other'}</option>
            
              </select>
            </div>

            {/* تاريخ الميلاد */}
             <div className="space-y-2">
              <Label htmlFor="birthDate" className={isRTL ? 'text-right block' : ''}>
                {t.birthDateLabel}
              </Label>
              <Input
                id="birthDate"
                type="date"
                value={birthDate}
                onChange={(e) => setBirthDate(e.target.value)}
                className={isRTL ? 'text-right' : 'pl-10'}
                dir={isRTL ? 'rtl' : 'ltr'}
                required
              />
            </div>

            {/* الدور (طالب / شيخ) */}
            <div className="space-y-2">
              <Label>{t.selectRole}</Label>
              <RadioGroup
                value={role}
                onValueChange={(value) => setRole(value as 'student' | 'sheikh')}
              >
                <div className="flex items-center space-x-2 border rounded-lg p-3 cursor-pointer hover:bg-accent transition-colors">
                  <RadioGroupItem value="student" id="student" />
                  <Label htmlFor="student" className="cursor-pointer flex-1">
                    <div>
                      <div>{t.studentRole}</div>
                      <div className="text-sm text-muted-foreground">
                        {language === 'ar'
                          ? 'أريد تعلم تلاوة القرآن الكريم'
                          : 'I want to learn Quran recitation'}
                      </div>
                    </div>
                  </Label>
                </div>

                <div className="flex items-center space-x-2 border rounded-lg p-3 cursor-pointer hover:bg-accent transition-colors">
                  <RadioGroupItem value="sheikh" id="sheikh" />
                  <Label htmlFor="sheikh" className="cursor-pointer flex-1">
                    <div>
                      <div>{t.sheikhRole}</div>
                      <div className="text-sm text-muted-foreground">
                        {language === 'ar'
                          ? 'أريد تعليم تلاوة القرآن الكريم'
                          : 'I want to teach Quran recitation'}
                      </div>
                    </div>
                  </Label>
                </div>
              </RadioGroup>
            </div>

            {error && (
              <p className="text-red-600 text-sm text-center bg-red-50 p-2 rounded">
                {error}
              </p>
            )}

            <Button type="submit" className="w-full bg-emerald-600" disabled={loading}>
              {loading ? `${t.registerButton}...` : t.registerButton}
            </Button>
          </form>

         <div className="text-center mt-4">
            <button
              onClick={() => navigate('/signin')}
              className="text-emerald-600 hover:underline"
            >
              {t.haveAccount} {t.signInLink}
            </button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}