import { useEffect, useState } from 'react';
import { Head, Link, useForm } from '@inertiajs/react';
import AuthLayout from '@/Layouts/AuthLayout';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/Components/ui/card";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { CheckCircle2, XCircle, Loader2, Edit2, Globe, Phone } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';
import axios from 'axios';

export default function Register({ detectedCountryIso2 }) {
    const { t } = useTranslation();
    const [isManualPrefix, setIsManualPrefix] = useState(false);
    const [countries, setCountries] = useState([]);
    const [loadingCountries, setLoadingCountries] = useState(true);
    const [usernameStatus, setUsernameStatus] = useState(''); 

    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        username: '',
        email: '',
        country_id: '',
        phone_code: '',
        phone: '',
        password: '',
        password_confirmation: '',
    });

    useEffect(() => {
        axios.get('/api/locations/countries')
            .then(res => {
                setCountries(res.data);
                setLoadingCountries(false);

                if (detectedCountryIso2 && !data.country_id) {
                    const matched = res.data.find(c => c.iso2 === detectedCountryIso2);
                    if (matched) {
                        setData(prev => ({
                            ...prev,
                            country_id: matched.id.toString(),
                            phone_code: matched.phone_code || '+'
                        }));
                    }
                }
            })
            .catch(() => setLoadingCountries(false));
    }, [detectedCountryIso2]);

    const handleCountryChange = (id) => {
        const selected = countries.find(c => c.id.toString() === id);
        setData(prev => ({
            ...prev,
            country_id: id,
            phone_code: isManualPrefix ? prev.phone_code : (selected?.phone_code || '+')
        }));
    };

    useEffect(() => {
        if (data.username.length < 3 || !/^[a-zA-Z0-9_]+$/.test(data.username)) {
            setUsernameStatus('');
            return;
        }
        const timer = setTimeout(() => {
            setUsernameStatus('checking');
            axios.post(route('username.check'), { username: data.username })
                .then(response => setUsernameStatus(response.data.available ? 'available' : 'taken'))
                .catch(() => setUsernameStatus(''));
        }, 500);
        return () => clearTimeout(timer);
    }, [data.username]);

    const submit = (e) => {
        e.preventDefault();
        post(route('register'));
    };

    return (
        <AuthLayout>
            <Head title={t('Create Account')} />

            <Card className="w-full border-border/50 shadow-xl bg-card mt-8 sm:mt-0 overflow-hidden">
                {/* 
                  ঐ কালারফুল দাগটি এখান থেকে রিমুভ করে দেওয়া হয়েছে 
                */}
                
                <CardHeader className="space-y-1 text-center pt-8">
                    <CardTitle className="text-2xl font-black tracking-tight text-foreground">
                        {t('Join the Marketplace')}
                    </CardTitle>
                    <CardDescription>
                        {t('Create your global account in seconds.')}
                    </CardDescription>
                </CardHeader>

                <CardContent className="px-6">
                    <form onSubmit={submit} className="space-y-4">
                        
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="name" className="font-bold">{t('Full Name')}</Label>
                                <Input 
                                    id="name" 
                                    value={data.name} 
                                    onChange={e => setData('name', e.target.value)} 
                                    placeholder={t('John Doe')} 
                                    required 
                                />
                                {errors.name && <p className="text-[11px] text-destructive font-bold">{errors.name}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="username" className="font-bold">{t('Username')}</Label>
                                <div className="relative">
                                    <Input 
                                        id="username" 
                                        value={data.username} 
                                        onChange={e => setData('username', e.target.value.toLowerCase())} 
                                        placeholder={t('johndoe')} 
                                        className="pr-8" 
                                        required 
                                    />
                                    <div className="absolute right-2 top-2.5">
                                        {usernameStatus === 'checking' && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
                                        {usernameStatus === 'available' && <CheckCircle2 className="h-4 w-4 text-green-500" />}
                                        {usernameStatus === 'taken' && <XCircle className="h-4 w-4 text-destructive" />}
                                    </div>
                                </div>
                                {errors.username && <p className="text-[11px] text-destructive font-bold">{errors.username}</p>}
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="email" className="font-bold">{t('Email Address')}</Label>
                            <Input 
                                id="email" 
                                type="email" 
                                value={data.email} 
                                onChange={e => setData('email', e.target.value)} 
                                placeholder={t('name@example.com')} 
                                required 
                            />
                            {errors.email && <p className="text-[11px] text-destructive font-bold">{errors.email}</p>}
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="country" className="font-bold flex items-center gap-2">
                                <Globe className="w-3.5 h-3.5" /> {t('Country / Region')}
                            </Label>
                            <Select value={data.country_id} onValueChange={handleCountryChange}>
                                <SelectTrigger className={errors.country_id ? "border-destructive" : "bg-muted/30"}>
                                    <SelectValue placeholder={loadingCountries ? t('Locating...') : t('Select Country')} />
                                </SelectTrigger>
                                <SelectContent className="max-h-72">
                                    {countries.map(c => (
                                        <SelectItem key={c.id} value={c.id.toString()}>{c.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            {errors.country_id && <p className="text-[11px] text-destructive font-bold">{errors.country_id}</p>}
                        </div>

                        <div className="space-y-2">
                            <div className="flex justify-between items-center">
                                <Label htmlFor="phone" className="font-bold flex items-center gap-2">
                                    <Phone className="w-3.5 h-3.5" /> {t('Phone Number')}
                                </Label>
                                <button 
                                    type="button" 
                                    onClick={() => setIsManualPrefix(!isManualPrefix)}
                                    className="text-[10px] font-black uppercase text-primary hover:underline flex items-center gap-1"
                                >
                                    <Edit2 className="w-2.5 h-2.5" /> {isManualPrefix ? t('Use Country Code') : t('Custom Code')}
                                </button>
                            </div>
                            <div className="flex shadow-sm rounded-md overflow-hidden">
                                {isManualPrefix ? (
                                    <Input 
                                        value={data.phone_code} 
                                        onChange={e => setData('phone_code', e.target.value)} 
                                        className="w-20 rounded-r-none border-r-0 bg-primary/5 font-bold text-center focus-visible:ring-0" 
                                        placeholder="+1"
                                    />
                                ) : (
                                    <div className="flex items-center justify-center px-3 bg-muted border border-r-0 text-sm font-bold text-muted-foreground min-w-[60px]">
                                        {data.phone_code || '+'}
                                    </div>
                                )}
                                <Input 
                                    id="phone" 
                                    type="tel" 
                                    value={data.phone} 
                                    onChange={e => setData('phone', e.target.value.replace(/[^0-9]/g, ''))}
                                    placeholder="01XXXXXXXX" 
                                    className="rounded-l-none focus-visible:ring-primary" 
                                    required 
                                />
                            </div>
                            {errors.phone && <p className="text-[11px] text-destructive font-bold">{errors.phone}</p>}
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2 border-t border-dashed">
                            <div className="space-y-2">
                                <Label htmlFor="password" title={t('At least 8 characters')} className="font-bold">{t('Password')}</Label>
                                <Input id="password" type="password" value={data.password} onChange={e => setData('password', e.target.value)} required />
                                {errors.password && <p className="text-[11px] text-destructive font-bold">{errors.password}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="password_confirmation" className="font-bold">{t('Confirm')}</Label>
                                <Input id="password_confirmation" type="password" value={data.password_confirmation} onChange={e => setData('password_confirmation', e.target.value)} required />
                            </div>
                        </div>

                        <Button className="w-full mt-2 h-12 text-base font-bold shadow-lg" type="submit" disabled={processing || usernameStatus === 'taken'}>
                            {processing ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : t('Create My Account')}
                        </Button>
                    </form>
                </CardContent>

                <CardFooter className="flex justify-center border-t py-6 bg-muted/20">
                    <p className="text-sm text-muted-foreground">
                        {t('Joined us before?')} <Link href={route('login')} className="text-primary font-black hover:underline ml-1">{t('Log in here')}</Link>
                    </p>
                </CardFooter>
            </Card>
        </AuthLayout>
    );
}