import React, { useState, useEffect, useRef } from 'react';
import { Head, useForm, router } from '@inertiajs/react';
import { toast } from 'sonner';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { Card, CardContent } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Badge } from "@/Components/ui/badge";
import { Switch } from "@/Components/ui/switch";
import { 
    Select, SelectContent, SelectItem, SelectTrigger, SelectValue 
} from "@/Components/ui/select";
import { 
    MapPin, Plus, Edit, Trash2, CheckCircle2, Phone, User, 
    Home, Map, Loader2, ChevronLeft, ChevronRight, Edit2 
} from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal';
import LocationSelector from '@/Components/LocationSelector';
import { useTranslation } from '@/hooks/useTranslation';

export default function AddressBook({ shippingAddresses, billingAddresses, userCountryId }) {
    const { t } = useTranslation();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingAddress, setEditingAddress] = useState(null);
    const [activeTab, setActiveTab] = useState('shipping');
    
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [deleteId, setDeleteId] = useState(null);
    
    const [phonePrefix, setPhonePrefix] = useState('');
    const [isManualPrefix, setIsManualPrefix] = useState(false);

    const scrollRef = useRef(null);
    const [showLeftArrow, setShowLeftArrow] = useState(false);
    const [showRightArrow, setShowRightArrow] = useState(false);

    const checkScroll = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeftArrow(scrollLeft > 0);
            setShowRightArrow(scrollLeft < scrollWidth - clientWidth - 5);
        }
    };

    useEffect(() => {
        checkScroll();
        window.addEventListener('resize', checkScroll);
        return () => window.removeEventListener('resize', checkScroll);
    }, [shippingAddresses, billingAddresses]);

    const scroll = (direction) => {
        if (scrollRef.current) {
            const offset = direction === 'left' ? -200 : 200;
            scrollRef.current.scrollBy({ left: offset, behavior: 'smooth' });
        }
    };

    const { data, setData, post, processing, errors, reset, clearErrors, transform } = useForm({
        _method: 'POST', // <-- Added _method for spoofing
        type: 'shipping',
        contact_name: '',
        contact_phone: '',
        country_id: userCountryId || '',
        state_id: '',
        city_id: '',
        custom_state_name: '',
        custom_city_name: '',
        zip_code: '',
        address_line_1: '',
        address_line_2: '',
        is_default: false,
    });

    transform((data) => {
        const finalPrefix = phonePrefix ? (phonePrefix.startsWith('+') ? phonePrefix : `+${phonePrefix}`) : '';
        return {
            ...data,
            contact_phone: finalPrefix ? `${finalPrefix} ${data.contact_phone}`.trim() : data.contact_phone
        };
    });

    const openModal = (address = null, type = activeTab) => {
        clearErrors();
        if (address) {
            setEditingAddress(address);
            
            let localPhone = address.contact_phone || '';
            let currentPrefix = '';
            if (localPhone.startsWith('+')) {
                const parts = localPhone.split(' ');
                if (parts.length > 1) {
                    currentPrefix = parts[0];
                    localPhone = parts.slice(1).join(' ');
                }
            }
            setPhonePrefix(currentPrefix);
            setIsManualPrefix(false);

            setData({
                _method: 'PUT', // <-- Tells Laravel this is an update, despite using post()
                type: address.type,
                contact_name: address.contact_name,
                contact_phone: localPhone,
                country_id: address.country_id,
                state_id: address.state_id || '',
                city_id: address.city_id || '',
                custom_state_name: '',
                custom_city_name: '',
                zip_code: address.zip_code || '',
                address_line_1: address.address_line_1,
                address_line_2: address.address_line_2 || '',
                is_default: address.is_default,
            });
        } else {
            setEditingAddress(null);
            reset();
            setPhonePrefix('');
            setIsManualPrefix(false);
            setData(prev => ({ ...prev, _method: 'POST', type: type, country_id: userCountryId || '', is_default: false }));
        }
        setIsModalOpen(true);
    };

    const submitForm = (e) => {
        e.preventDefault();
        
        const action = editingAddress 
            ? route('buyer.addresses.update', editingAddress.id) 
            : route('buyer.addresses.store');

        // --- FIX: We ONLY use POST to bypass Namecheap ModSecurity limits ---
        post(action, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t('Address saved successfully.'));
                setIsModalOpen(false);
            }
        });
    };

    const handleDelete = () => {
        if (!deleteId) return;
        router.delete(route('buyer.addresses.destroy', deleteId), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t('Address removed.'));
                setIsDeleteOpen(false);
            }
        });
    };

    const setAsDefault = (id) => {
        router.post(route('buyer.addresses.default', id), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success(t("Default address updated."))
        });
    };

    const handleLocationChange = (locData) => {
        if (locData.phone_code !== undefined && !isManualPrefix) {
            setPhonePrefix(locData.phone_code);
        }
        setData(prev => ({
            ...prev,
            country_id: locData.country_id,
            state_id: locData.state_id,
            city_id: locData.city_id,
            custom_state_name: locData.custom_state_name,
            custom_city_name: locData.custom_city_name
        }));
    };

    const displayPhoneCode = phonePrefix 
        ? (phonePrefix.startsWith('+') ? phonePrefix : `+${phonePrefix}`)
        : '+';

    const AddressCard = ({ address }) => (
        <Card className={`border ${address.is_default ? 'border-primary shadow-md bg-primary/5' : 'border-border/50 bg-card hover:border-primary/30'} transition-all`}>
            <CardContent className="p-5 flex flex-col h-full">
                <div className="flex justify-between items-start mb-4">
                    <div className="flex items-center gap-2">
                        {address.is_default ? (
                            <Badge className="bg-primary text-primary-foreground gap-1"><CheckCircle2 className="w-3 h-3"/> {t('Default')}</Badge>
                        ) : (
                            <Badge variant="secondary" className="text-muted-foreground uppercase text-[10px]">{t('Alternative')}</Badge>
                        )}
                    </div>
                    <div className="flex gap-2">
                        <Button variant="ghost" size="icon" className="h-8 w-8 text-blue-500 hover:bg-blue-50" onClick={() => openModal(address)}>
                            <Edit className="w-4 h-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500 hover:bg-red-50" onClick={() => { setDeleteId(address.id); setIsDeleteOpen(true); }}>
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    </div>
                </div>

                <div className="space-y-3 text-sm flex-1">
                    <div className="flex items-start gap-2">
                        <User className="w-4 h-4 text-muted-foreground shrink-0 mt-0.5" />
                        <span className="font-bold text-foreground">{address.contact_name}</span>
                    </div>
                    <div className="flex items-start gap-2">
                        <Phone className="w-4 h-4 text-muted-foreground shrink-0 mt-0.5" />
                        <span>{address.contact_phone}</span>
                    </div>
                    <div className="flex items-start gap-2">
                        <Home className="w-4 h-4 text-muted-foreground shrink-0 mt-0.5" />
                        <span>
                            {address.address_line_1}
                            {address.address_line_2 && <><br/>{address.address_line_2}</>}
                        </span>
                    </div>
                    <div className="flex items-start gap-2">
                        <Map className="w-4 h-4 text-muted-foreground shrink-0 mt-0.5" />
                        <span>
                            {address.city?.name ? `${address.city.name}, ` : ''}
                            {address.state?.name ? `${address.state.name}, ` : ''}
                            <span className="font-bold">{address.country?.name}</span>
                            {address.zip_code && ` - ${address.zip_code}`}
                        </span>
                    </div>
                </div>

                {!address.is_default && (
                    <div className="mt-4 pt-4 border-t">
                        <Button variant="outline" className="w-full text-xs h-8" onClick={() => setAsDefault(address.id)}>
                            {t('Set as Default')}
                        </Button>
                    </div>
                )}
            </CardContent>
        </Card>
    );

    return (
        <DashboardLayout mode="buyer">
            <Head title={t('Address Book')} />

            <ConfirmModal 
                open={isDeleteOpen} onOpenChange={setIsDeleteOpen} onConfirm={handleDelete}
                title={t('Delete Address?')} description={t('This address will be permanently removed.')} variant="destructive"
            />

            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{t('Address Book')}</h1>
                    <p className="text-muted-foreground text-sm">{t('Manage your shipping and billing addresses.')}</p>
                </div>
            </div>

            <div className="sm:hidden mb-4">
                <Button onClick={() => openModal(null, activeTab)} className="w-full gap-2">
                    <Plus className="w-4 h-4" /> {t('Add New Address')}
                </Button>
            </div>

            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-end border-b border-border/60 bg-card rounded-t-xl mb-6 relative">
                <div className="relative group w-full sm:w-auto overflow-hidden">
                     {showLeftArrow && (
                        <button 
                            onClick={() => scroll('left')}
                            className="absolute left-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-r from-card to-transparent flex items-center justify-start pl-1 text-primary md:hidden"
                        >
                            <ChevronLeft className="w-6 h-6 animate-pulse" />
                        </button>
                    )}

                    <div 
                        ref={scrollRef}
                        onScroll={checkScroll}
                        className="flex w-full overflow-x-auto no-scrollbar scroll-smooth px-4 sm:px-0 sm:ml-4"
                    >
                        <div className="flex w-max space-x-6">
                            {[
                                { id: 'shipping', label: t('Shipping Addresses'), count: shippingAddresses.length },
                                { id: 'billing', label: t('Billing Addresses'), count: billingAddresses.length }
                            ].map(tab => (
                                <button 
                                    key={tab.id}
                                    onClick={() => setActiveTab(tab.id)}
                                    className={`py-4 px-1 text-sm font-bold border-b-2 transition-all whitespace-nowrap flex items-center gap-2 ${
                                        activeTab === tab.id ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
                                    }`}
                                >
                                    {tab.label} 
                                    <span className={`px-2 py-0.5 rounded-full text-[10px] ${activeTab === tab.id ? 'bg-primary/10' : 'bg-muted'}`}>
                                        {tab.count}
                                    </span>
                                </button>
                            ))}
                        </div>
                    </div>

                    {showRightArrow && (
                        <button 
                            onClick={() => scroll('right')}
                            className="absolute right-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-l from-card to-transparent flex items-center justify-end pr-1 text-primary md:hidden"
                        >
                            <ChevronRight className="w-6 h-6 animate-pulse" />
                        </button>
                    )}
                </div>

                <div className="hidden sm:block pb-3 pr-4">
                     <Button onClick={() => openModal(null, activeTab)} size="sm" className="gap-2">
                        <Plus className="w-4 h-4" /> {t('Add New Address')}
                    </Button>
                </div>
            </div>

            {activeTab === 'shipping' && (
                <div className="mt-0 animate-in fade-in duration-300">
                    {shippingAddresses.length === 0 ? (
                        <div className="text-center py-20 bg-card border border-dashed rounded-xl text-muted-foreground">
                            <MapPin className="w-12 h-12 mx-auto mb-3 opacity-20" />
                            <p>{t('No shipping addresses found.')}</p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {shippingAddresses.map(addr => <AddressCard key={addr.id} address={addr} />)}
                        </div>
                    )}
                </div>
            )}

            {activeTab === 'billing' && (
                <div className="mt-0 animate-in fade-in duration-300">
                    {billingAddresses.length === 0 ? (
                        <div className="text-center py-20 bg-card border border-dashed rounded-xl text-muted-foreground">
                            <MapPin className="w-12 h-12 mx-auto mb-3 opacity-20" />
                            <p>{t('No billing addresses found.')}</p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {billingAddresses.map(addr => <AddressCard key={addr.id} address={addr} />)}
                        </div>
                    )}
                </div>
            )}

            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{editingAddress ? t('Edit Address') : t('Add New Address')}</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={submitForm} className="space-y-6 py-2">
                        
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>{t('Address Type')}</Label>
                                <Select value={data.type} onValueChange={v => setData('type', v)}>
                                    <SelectTrigger className="bg-background"><SelectValue/></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="shipping">{t('Shipping Address')}</SelectItem>
                                        <SelectItem value="billing">{t('Billing Address')}</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>{t('Contact Name')} <span className="text-red-500">*</span></Label>
                                <Input value={data.contact_name} onChange={e => setData('contact_name', e.target.value)} required placeholder={t('John Doe')} className="bg-background" />
                                {errors.contact_name && <p className="text-xs text-destructive">{errors.contact_name}</p>}
                            </div>
                            
                            <div className="space-y-2">
                                <div className="flex justify-between items-center mb-1">
                                    <Label>{t('Phone Number')} <span className="text-red-500">*</span></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 Auto Code") : t("Custom Code")}
                                    </button>
                                </div>

                                <div className="flex rounded-md overflow-hidden border border-input shadow-sm focus-within:ring-1 focus-within:ring-primary focus-within:border-primary transition-all bg-background">
                                    {isManualPrefix ? (
                                        <Input 
                                            value={phonePrefix} 
                                            onChange={e => setPhonePrefix(e.target.value)} 
                                            className="w-20 rounded-none border-0 border-r border-border bg-primary/5 font-bold text-center focus-visible:ring-0 shadow-none" 
                                            placeholder="+1"
                                        />
                                    ) : (
                                        <div className="flex items-center justify-center px-3 bg-muted border-r border-border text-sm font-bold text-muted-foreground min-w-[60px] select-none">
                                            {displayPhoneCode}
                                        </div>
                                    )}
                                    <Input 
                                        value={data.contact_phone} 
                                        onChange={e => setData('contact_phone', e.target.value.replace(/[^0-9]/g, ''))} 
                                        required 
                                        placeholder="1700000000" 
                                        className="rounded-none border-0 focus-visible:ring-0 shadow-none bg-transparent flex-1" 
                                    />
                                </div>
                                {errors.contact_phone && <p className="text-xs text-destructive mt-1">{errors.contact_phone}</p>}
                            </div>
                        </div>

                        <div className="p-4 border rounded-xl bg-muted/10">
                            <LocationSelector 
                                onLocationChange={handleLocationChange}
                                initialCountry={data.country_id}
                                initialState={data.state_id}
                                initialCity={data.city_id}
                                errorCountry={errors.country_id}
                            />
                            {errors.country_id && <p className="text-xs text-destructive mt-1">{t('Country is required.')}</p>}
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div className="space-y-2 sm:col-span-2">
                                <Label>{t('House / Building / Street')} <span className="text-red-500">*</span></Label>
                                <Input value={data.address_line_1} onChange={e => setData('address_line_1', e.target.value)} required placeholder={t('123 Main Street')} className="bg-background" />
                                {errors.address_line_1 && <p className="text-xs text-destructive">{errors.address_line_1}</p>}
                            </div>
                            <div className="space-y-2">
                                <Label>{t('Apartment / Suite (Optional)')}</Label>
                                <Input value={data.address_line_2} onChange={e => setData('address_line_2', e.target.value)} placeholder={t('Apt 4B')} className="bg-background" />
                            </div>
                            <div className="space-y-2">
                                <Label>{t('ZIP / Postal Code')}</Label>
                                <Input value={data.zip_code} onChange={e => setData('zip_code', e.target.value)} placeholder="10001" className="bg-background" />
                            </div>
                        </div>

                        <div className="flex items-center justify-between p-4 border rounded-xl bg-primary/5">
                            <div>
                                <Label className="text-base font-bold">{t('Set as Default')}</Label>
                                <p className="text-xs text-muted-foreground">{t('Use this address automatically for deliveries or payments.')}</p>
                            </div>
                            <Switch checked={data.is_default} onCheckedChange={v => setData('is_default', v)} />
                        </div>

                        <DialogFooter className="pt-2 border-t">
                            <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>{t('Cancel')}</Button>
                            <Button type="submit" disabled={processing}>
                                {processing && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                {t('Save Address')}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

        </DashboardLayout>
    );
}