import React, { useState, useEffect } from 'react';
import { Head, Link, router, useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import axios from 'axios';
import AdminLayout from '@/cp/Layouts/AdminLayout';
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 { Badge } from "@/Components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { MapPin, Search, Plus, Edit, Trash2, Loader2 } from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal';

export default function LocationManager({ tab, search, countriesData, statesData, citiesData, allCountries }) {
    
    const [searchTerm, setSearchTerm] = useState(search || '');
    
    // Modals State
    const [isCountryOpen, setIsCountryOpen] = useState(false);
    const [isStateOpen, setIsStateOpen] = useState(false);
    const [isCityOpen, setIsCityOpen] = useState(false);
    
    const [editingItem, setEditingItem] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [deleteInfo, setDeleteInfo] = useState(null);

    // City Dynamic State Loading
    const [selectedCityCountry, setSelectedCityCountry] = useState('');
    const [cityStates, setCityStates] = useState([]);
    const [loadingCityStates, setLoadingCityStates] = useState(false);

    // Search Debounce
    useEffect(() => {
        const delay = setTimeout(() => {
            if (searchTerm !== search) {
                router.get(route('cp.settings.locations.index'), { tab, search: searchTerm }, { preserveState: true, replace: true });
            }
        }, 500);
        return () => clearTimeout(delay);
    }, [searchTerm]);

    const changeTab = (newTab) => {
        setSearchTerm('');
        router.get(route('cp.settings.locations.index'), { tab: newTab }, { preserveState: true });
    };

    // Forms
    const countryForm = useForm({ name: '', iso2: '', iso3: '', phone_code: '', currency: '', is_active: true });
    const stateForm = useForm({ name: '', country_id: '', is_active: true });
    const cityForm = useForm({ state_id: '', name: '', latitude: '', longitude: '', is_active: true });

    // Helper to fetch states for the City Modal
    const fetchCityStates = async (countryId) => {
        if (!countryId) {
            setCityStates([]);
            return;
        }
        setLoadingCityStates(true);
        try {
            const res = await axios.get(`/api/locations/countries/${countryId}/states`);
            setCityStates(res.data);
        } catch (e) {
            toast.error("Failed to load states");
        } finally {
            setLoadingCityStates(false);
        }
    };

    // Open Modals
    const openCountryModal = (country = null) => {
        if (country) {
            setEditingItem(country);
            countryForm.setData({
                name: country.name, iso2: country.iso2, iso3: country.iso3 || '',
                phone_code: country.phone_code || '', currency: country.currency || '', is_active: country.is_active
            });
        } else {
            setEditingItem(null);
            countryForm.reset();
            countryForm.setData('is_active', true);
        }
        setIsCountryOpen(true);
    };

    const openStateModal = (state = null) => {
        if (state) {
            setEditingItem(state);
            stateForm.setData({ name: state.name, country_id: state.country_id.toString(), is_active: state.is_active });
        } else {
            setEditingItem(null);
            stateForm.reset();
            stateForm.setData('is_active', true);
        }
        setIsStateOpen(true);
    };

    const openCityModal = async (city = null) => {
        if (city) {
            setEditingItem(city);
            // Derive country ID from nested relationship
            const countryId = city.state?.country_id?.toString() || '';
            setSelectedCityCountry(countryId);
            
            // Pre-fill form data
            cityForm.setData({
                state_id: city.state_id?.toString() || '',
                name: city.name,
                latitude: city.latitude || '',
                longitude: city.longitude || '',
                is_active: city.is_active
            });

            // Fetch states for the dropdown to work
            if (countryId) await fetchCityStates(countryId);
        } else {
            setEditingItem(null);
            setSelectedCityCountry('');
            setCityStates([]);
            cityForm.reset();
            cityForm.setData('is_active', true);
        }
        setIsCityOpen(true);
    };

    // Submits
    const submitCountry = (e) => {
        e.preventDefault();
        const action = editingItem 
            ? route('cp.settings.locations.countries.update', editingItem.id) 
            : route('cp.settings.locations.countries.store');
            
        const method = editingItem ? 'put' : 'post';

        countryForm[method](action, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(`Country ${editingItem ? 'updated' : 'added'} successfully.`);
                setIsCountryOpen(false);
            },
            onError: (err) => toast.error(err.iso2 || "Form validation failed.")
        });
    };

    const submitState = (e) => {
        e.preventDefault();
        const action = editingItem 
            ? route('cp.settings.locations.states.update', editingItem.id) 
            : route('cp.settings.locations.states.store');
            
        const method = editingItem ? 'put' : 'post';

        stateForm[method](action, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(`State ${editingItem ? 'updated' : 'added'} successfully.`);
                setIsStateOpen(false);
            }
        });
    };

    const submitCity = (e) => {
        e.preventDefault();
        const action = editingItem 
            ? route('cp.settings.locations.cities.update', editingItem.id) 
            : route('cp.settings.locations.cities.store');
            
        const method = editingItem ? 'put' : 'post';

        cityForm[method](action, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(`City ${editingItem ? 'updated' : 'added'} successfully.`);
                setIsCityOpen(false);
            }
        });
    };

    // Delete
    const confirmDelete = (type, item) => {
        setDeleteInfo({ type, id: item.id, name: item.name });
        setIsDeleteOpen(true);
    };

    const executeDelete = () => {
        if (!deleteInfo) return;
        router.delete(route(`cp.settings.locations.${deleteInfo.type}.destroy`, deleteInfo.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success("Deleted successfully.");
                setIsDeleteOpen(false);
            }
        });
    };

    // STATUS RENDER COMPONENT
    const StatusBadge = ({ active }) => (
        active ? (
            <Badge className="bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20 hover:bg-green-500/20 transition-colors whitespace-nowrap">
                ● Active
            </Badge>
        ) : (
            <Badge className="bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20 hover:bg-red-500/20 transition-colors whitespace-nowrap">
                ○ Inactive
            </Badge>
        )
    );

    return (
        <AdminLayout>
            <Head title="Location Management" />
            
            <ConfirmModal 
                open={isDeleteOpen} onOpenChange={setIsDeleteOpen} onConfirm={executeDelete}
                title={`Delete ${deleteInfo?.name}?`}
                description="Are you sure? This action cannot be undone." variant="destructive"
            />

            <div className="max-w-6xl mx-auto space-y-6">
                
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-2">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-primary/10 rounded-lg shrink-0">
                            <MapPin className="w-8 h-8 text-primary" />
                        </div>
                        <div>
                            <h2 className="text-2xl font-bold tracking-tight">Location Management</h2>
                            <p className="text-muted-foreground text-sm">Manage countries, states, and cities manually.</p>
                        </div>
                    </div>
                </div>

                {/* SLEEK UNDERLINE SCROLLABLE TABS */}
                <div className="w-full border-b border-border/60 overflow-x-auto no-scrollbar bg-card rounded-t-xl px-2 pt-2">
                    <div className="flex w-max min-w-full space-x-6 px-4">
                        <button onClick={() => changeTab('countries')} className={`py-3 px-2 text-sm font-bold border-b-2 transition-all ${tab === 'countries' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                            Countries
                        </button>
                        <button onClick={() => changeTab('states')} className={`py-3 px-2 text-sm font-bold border-b-2 transition-all ${tab === 'states' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                            States / Regions
                        </button>
                        <button onClick={() => changeTab('cities')} className={`py-3 px-2 text-sm font-bold border-b-2 transition-all ${tab === 'cities' ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                            Cities
                        </button>
                    </div>
                </div>

                {/* ACTION BAR */}
                <div className="flex flex-col sm:flex-row justify-between items-center gap-4 bg-card p-4 rounded-b-xl border border-t-0 shadow-sm">
                    <div className="relative w-full sm:max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                        <Input 
                            placeholder={`Search ${tab}...`} 
                            value={searchTerm} 
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pl-9 bg-muted/50"
                        />
                    </div>
                    {tab === 'countries' && <Button onClick={() => openCountryModal()} className="w-full sm:w-auto"><Plus className="w-4 h-4 mr-2"/> Add Country</Button>}
                    {tab === 'states' && <Button onClick={() => openStateModal()} className="w-full sm:w-auto"><Plus className="w-4 h-4 mr-2"/> Add State</Button>}
                    {tab === 'cities' && <Button onClick={() => openCityModal()} className="w-full sm:w-auto"><Plus className="w-4 h-4 mr-2"/> Add City</Button>}
                </div>

                {/* DATA TABLES */}
                <Card className="shadow-sm border-border/50 overflow-hidden w-full">
                    <CardContent className="p-0 overflow-x-auto w-full">
                        <table className="w-full text-sm text-left min-w-[600px]">
                            <thead className="text-xs uppercase bg-muted/40 text-muted-foreground border-b whitespace-nowrap">
                                {tab === 'countries' && (
                                    <tr>
                                        <th className="px-6 py-4">ID</th>
                                        <th className="px-6 py-4">Country Name</th>
                                        <th className="px-6 py-4">ISO-2 / 3</th>
                                        <th className="px-6 py-4">Phone / Currency</th>
                                        <th className="px-6 py-4">Status</th>
                                        <th className="px-6 py-4 text-right">Actions</th>
                                    </tr>
                                )}
                                {tab === 'states' && (
                                    <tr>
                                        <th className="px-6 py-4">ID</th>
                                        <th className="px-6 py-4">State Name</th>
                                        <th className="px-6 py-4">Country</th>
                                        <th className="px-6 py-4">Status</th>
                                        <th className="px-6 py-4 text-right">Actions</th>
                                    </tr>
                                )}
                                {tab === 'cities' && (
                                    <tr>
                                        <th className="px-6 py-4">ID</th>
                                        <th className="px-6 py-4">City Name</th>
                                        <th className="px-6 py-4">State / Country</th>
                                        <th className="px-6 py-4">Status</th>
                                        <th className="px-6 py-4 text-right">Actions</th>
                                    </tr>
                                )}
                            </thead>
                            <tbody className="divide-y divide-border">
                                {tab === 'countries' && countriesData.data.map(item => (
                                    <tr key={item.id} className="hover:bg-muted/20 transition-colors">
                                        <td className="px-6 py-4 font-mono text-muted-foreground whitespace-nowrap">{item.id}</td>
                                        <td className="px-6 py-4 font-bold min-w-[150px]">{item.name}</td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex gap-2">
                                                <Badge variant="outline" className="font-mono">{item.iso2}</Badge>
                                                {item.iso3 && <Badge variant="secondary" className="font-mono">{item.iso3}</Badge>}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 text-muted-foreground whitespace-nowrap">
                                            {item.phone_code || '-'} / {item.currency || '-'}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <StatusBadge active={item.is_active} />
                                        </td>
                                        <td className="px-6 py-4 text-right whitespace-nowrap">
                                            <Button size="icon" variant="ghost" onClick={() => openCountryModal(item)} className="hover:text-blue-500 transition-colors"><Edit className="w-4 h-4"/></Button>
                                            <Button size="icon" variant="ghost" onClick={() => confirmDelete('countries', item)} className="hover:text-red-500 transition-colors"><Trash2 className="w-4 h-4"/></Button>
                                        </td>
                                    </tr>
                                ))}
                                
                                {tab === 'states' && statesData.data.map(item => (
                                    <tr key={item.id} className="hover:bg-muted/20 transition-colors">
                                        <td className="px-6 py-4 font-mono text-muted-foreground whitespace-nowrap">{item.id}</td>
                                        <td className="px-6 py-4 font-bold min-w-[150px]">{item.name}</td>
                                        <td className="px-6 py-4 text-muted-foreground min-w-[150px]">{item.country?.name}</td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <StatusBadge active={item.is_active} />
                                        </td>
                                        <td className="px-6 py-4 text-right whitespace-nowrap">
                                            <Button size="icon" variant="ghost" onClick={() => openStateModal(item)} className="hover:text-blue-500 transition-colors"><Edit className="w-4 h-4"/></Button>
                                            <Button size="icon" variant="ghost" onClick={() => confirmDelete('states', item)} className="hover:text-red-500 transition-colors"><Trash2 className="w-4 h-4"/></Button>
                                        </td>
                                    </tr>
                                ))}

                                {tab === 'cities' && citiesData.data.map(item => (
                                    <tr key={item.id} className="hover:bg-muted/20 transition-colors">
                                        <td className="px-6 py-4 font-mono text-muted-foreground whitespace-nowrap">{item.id}</td>
                                        <td className="px-6 py-4 font-bold min-w-[150px]">{item.name}</td>
                                        <td className="px-6 py-4 text-muted-foreground min-w-[200px]">{item.state?.name}, {item.state?.country?.name}</td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <StatusBadge active={item.is_active} />
                                        </td>
                                        <td className="px-6 py-4 text-right whitespace-nowrap">
                                            <Button size="icon" variant="ghost" onClick={() => openCityModal(item)} className="hover:text-blue-500 transition-colors"><Edit className="w-4 h-4"/></Button>
                                            <Button size="icon" variant="ghost" onClick={() => confirmDelete('cities', item)} className="hover:text-red-500 transition-colors"><Trash2 className="w-4 h-4"/></Button>
                                        </td>
                                    </tr>
                                ))}

                                {/* Empty States */}
                                {tab === 'countries' && countriesData.data.length === 0 && (
                                    <tr><td colSpan={6} className="px-6 py-8 text-center text-muted-foreground">No countries found.</td></tr>
                                )}
                                {tab === 'states' && statesData.data.length === 0 && (
                                    <tr><td colSpan={5} className="px-6 py-8 text-center text-muted-foreground">No states found.</td></tr>
                                )}
                                {tab === 'cities' && citiesData.data.length === 0 && (
                                    <tr><td colSpan={5} className="px-6 py-8 text-center text-muted-foreground">No cities found.</td></tr>
                                )}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>

                {/* Pagination */}
                <div className="flex flex-col sm:flex-row justify-between items-center bg-card p-4 rounded-xl border gap-4">
                    <span className="text-sm text-muted-foreground">
                        Showing {(tab === 'countries' ? countriesData : tab === 'states' ? statesData : citiesData).from || 0} to {(tab === 'countries' ? countriesData : tab === 'states' ? statesData : citiesData).to || 0}
                    </span>
                    <div className="flex gap-1 overflow-x-auto no-scrollbar max-w-full">
                        {(tab === 'countries' ? countriesData : tab === 'states' ? statesData : citiesData).links?.map((link, i) => (
                            <Link
                                key={i} href={link.url || '#'}
                                className={`px-3 py-1 border rounded-md text-sm shrink-0 ${link.active ? 'bg-primary text-primary-foreground border-primary shadow-sm' : 'hover:bg-muted bg-background text-muted-foreground'} ${!link.url && 'opacity-30 cursor-not-allowed'}`}
                                dangerouslySetInnerHTML={{ __html: link.label }}
                            />
                        ))}
                    </div>
                </div>

            </div>

            {/* COUNTRY MODAL */}
            <Dialog open={isCountryOpen} onOpenChange={setIsCountryOpen}>
                <DialogContent className="max-w-md">
                    <DialogHeader><DialogTitle>{editingItem ? 'Edit Country' : 'Add Country'}</DialogTitle></DialogHeader>
                    <form onSubmit={submitCountry} className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label>Country Name <span className="text-red-500">*</span></Label>
                            <Input value={countryForm.data.name} onChange={e => countryForm.setData('name', e.target.value)} required placeholder="e.g. Australia" />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>ISO-2 Code <span className="text-red-500">*</span></Label>
                                <Input value={countryForm.data.iso2} onChange={e => countryForm.setData('iso2', e.target.value.toUpperCase())} maxLength={2} placeholder="AU" required />
                            </div>
                            <div className="space-y-2">
                                <Label>ISO-3 Code</Label>
                                <Input value={countryForm.data.iso3} onChange={e => countryForm.setData('iso3', e.target.value.toUpperCase())} maxLength={3} placeholder="AUS" />
                            </div>
                            <div className="space-y-2">
                                <Label>Phone Code</Label>
                                <Input value={countryForm.data.phone_code} onChange={e => countryForm.setData('phone_code', e.target.value)} placeholder="+61" />
                            </div>
                            <div className="space-y-2">
                                <Label>Currency Code</Label>
                                <Input value={countryForm.data.currency} onChange={e => countryForm.setData('currency', e.target.value.toUpperCase())} maxLength={3} placeholder="AUD" />
                            </div>
                        </div>
                        <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
                            <input type="checkbox" id="c_active" checked={countryForm.data.is_active} onChange={e => countryForm.setData('is_active', e.target.checked)} className="rounded text-primary focus:ring-primary w-4 h-4 cursor-pointer" />
                            <Label htmlFor="c_active" className="cursor-pointer font-semibold">Enabled (Visible in Frontend)</Label>
                        </div>
                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={() => setIsCountryOpen(false)} className="flex-1">Cancel</Button>
                            <Button type="submit" disabled={countryForm.processing} className="flex-1">
                                {countryForm.processing ? <Loader2 className="animate-spin w-4 h-4 mr-2"/> : null} 
                                Save Country
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* STATE MODAL */}
            <Dialog open={isStateOpen} onOpenChange={setIsStateOpen}>
                <DialogContent className="max-w-md">
                    <DialogHeader><DialogTitle>{editingItem ? 'Edit State' : 'Add State'}</DialogTitle></DialogHeader>
                    <form onSubmit={submitState} className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label>Select Country <span className="text-red-500">*</span></Label>
                            <Select value={stateForm.data.country_id} onValueChange={v => stateForm.setData('country_id', v)}>
                                <SelectTrigger className="w-full bg-muted/50"><SelectValue placeholder="Search country..." /></SelectTrigger>
                                <SelectContent className="max-h-80">
                                    {allCountries.map(c => <SelectItem key={c.id} value={c.id.toString()}>{c.name}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>State / Region Name <span className="text-red-500">*</span></Label>
                            <Input value={stateForm.data.name} onChange={e => stateForm.setData('name', e.target.value)} required placeholder="e.g. New South Wales" />
                        </div>
                        <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
                            <input type="checkbox" id="s_active" checked={stateForm.data.is_active} onChange={e => stateForm.setData('is_active', e.target.checked)} className="rounded text-primary focus:ring-primary w-4 h-4 cursor-pointer" />
                            <Label htmlFor="s_active" className="cursor-pointer font-semibold">Enabled (Visible in Frontend)</Label>
                        </div>
                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={() => setIsStateOpen(false)} className="flex-1">Cancel</Button>
                            <Button type="submit" disabled={stateForm.processing} className="flex-1">
                                {stateForm.processing ? <Loader2 className="animate-spin w-4 h-4 mr-2"/> : null} 
                                Save State
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* CITY MODAL (FIXED) */}
            <Dialog open={isCityOpen} onOpenChange={setIsCityOpen}>
                <DialogContent className="max-w-md">
                    <DialogHeader><DialogTitle>{editingItem ? 'Edit City' : 'Add City'}</DialogTitle></DialogHeader>
                    <form onSubmit={submitCity} className="space-y-4 py-4">
                        
                        <div className="space-y-2">
                            <Label>Select Country <span className="text-red-500">*</span></Label>
                            <Select 
                                value={selectedCityCountry} 
                                onValueChange={(v) => {
                                    setSelectedCityCountry(v);
                                    cityForm.setData('state_id', '');
                                    fetchCityStates(v);
                                }}
                            >
                                <SelectTrigger className="w-full bg-muted/50"><SelectValue placeholder="Select country first..." /></SelectTrigger>
                                <SelectContent className="max-h-64">
                                    {allCountries.map(c => <SelectItem key={c.id} value={c.id.toString()}>{c.name}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-2">
                            <Label>Select State / Region <span className="text-red-500">*</span></Label>
                            <Select 
                                value={cityForm.data.state_id} 
                                onValueChange={v => cityForm.setData('state_id', v)}
                                disabled={!selectedCityCountry || loadingCityStates}
                            >
                                <SelectTrigger className="w-full bg-muted/50">
                                    <SelectValue placeholder={loadingCityStates ? "Loading states..." : "Select state..."} />
                                </SelectTrigger>
                                <SelectContent className="max-h-64">
                                    {cityStates.map(s => <SelectItem key={s.id} value={s.id.toString()}>{s.name}</SelectItem>)}
                                    {cityStates.length === 0 && <SelectItem value="none" disabled>No states found</SelectItem>}
                                </SelectContent>
                            </Select>
                            {cityForm.errors.state_id && <p className="text-xs text-destructive">{cityForm.errors.state_id}</p>}
                        </div>

                        <div className="space-y-2">
                            <Label>City Name <span className="text-red-500">*</span></Label>
                            <Input value={cityForm.data.name} onChange={e => cityForm.setData('name', e.target.value)} required placeholder="e.g. Sydney" />
                            {cityForm.errors.name && <p className="text-xs text-destructive">{cityForm.errors.name}</p>}
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label>Latitude (Optional)</Label>
                                <Input type="number" step="any" value={cityForm.data.latitude} onChange={e => cityForm.setData('latitude', e.target.value)} placeholder="-33.8688" />
                            </div>
                            <div className="space-y-2">
                                <Label>Longitude (Optional)</Label>
                                <Input type="number" step="any" value={cityForm.data.longitude} onChange={e => cityForm.setData('longitude', e.target.value)} placeholder="151.2093" />
                            </div>
                        </div>

                        <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
                            <input type="checkbox" id="ci_active" checked={cityForm.data.is_active} onChange={e => cityForm.setData('is_active', e.target.checked)} className="rounded text-primary focus:ring-primary w-4 h-4 cursor-pointer" />
                            <Label htmlFor="ci_active" className="cursor-pointer font-semibold">Enabled (Visible in Frontend)</Label>
                        </div>

                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={() => setIsCityOpen(false)} className="flex-1">Cancel</Button>
                            <Button type="submit" disabled={cityForm.processing} className="flex-1">
                                {cityForm.processing ? <Loader2 className="animate-spin w-4 h-4 mr-2"/> : null} 
                                Save City
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

        </AdminLayout>
    );
}