
'use client';

import React, { useState, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { MoreHorizontal, Edit, Trash2, PlusCircle } from "lucide-react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Switch } from "@/components/ui/switch";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { useToast } from '@/hooks/use-toast';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useFirestore, useCollection, useMemoFirebase } from '@/firebase';
import { collection, doc } from 'firebase/firestore';
import type { Country, City } from '@/lib/types';
import Link from 'next/link';
import { updateDocumentNonBlocking } from '@/firebase/non-blocking-updates';


interface EnrichedCountry extends Country {
    cityCount: number;
    businessCount: number; // Placeholder, as we don't have business data linked directly here
    isActive: boolean;
}

export default function AdminCountriesPage() {
    const firestore = useFirestore();
    const countriesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'countries') : null, [firestore]);
    const { data: countries, isLoading: isLoadingCountries } = useCollection<Country>(countriesQuery);
    
    const citiesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'cities') : null, [firestore]);
    const { data: cities, isLoading: isLoadingCities } = useCollection<City>(citiesQuery);
    
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingCountry, setEditingCountry] = useState<EnrichedCountry | null>(null);
    const { toast } = useToast();

    const enrichedCountries = useMemo(() => {
        if (!countries || !cities) return [];
        
        const cityCounts = cities.reduce((acc, city) => {
            acc[city.countryId] = (acc[city.countryId] || 0) + 1;
            return acc;
        }, {} as Record<string, number>);

        return countries.map(country => ({
            ...country,
            cityCount: cityCounts[country.id] || 0,
            businessCount: 0, // This needs business data to be calculated correctly
            isActive: true, // Default to active
        }));
    }, [countries, cities]);

    const handleActiveChange = (countryId: string, isActive: boolean) => {
        if (!firestore) return;
        updateDocumentNonBlocking(doc(firestore, 'countries', countryId), { isActive });
    };

    const handleOpenDialog = (country: EnrichedCountry | null = null) => {
        setEditingCountry(country);
        setIsDialogOpen(true);
    };

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!firestore || !editingCountry) return;
        const formData = new FormData(e.currentTarget);
        const name = formData.get('name') as string;

        updateDocumentNonBlocking(doc(firestore, 'countries', editingCountry.id), { name });

        toast({ title: "Country Updated", description: "This country has been updated." });
        setIsDialogOpen(false);
        setEditingCountry(null);
    };

    if (isLoadingCountries || isLoadingCities) {
        return <p>Loading...</p>
    }

    return (
        <>
            <Card>
                <CardHeader>
                    <div className="flex items-center justify-between">
                        <div>
                            <CardTitle>Countries</CardTitle>
                            <CardDescription>Manage all available countries.</CardDescription>
                        </div>
                        <Button asChild size="sm" className="gap-1">
                            <Link href="/admin/countries/add">
                                <PlusCircle className="h-4 w-4" />
                                Add New Country
                            </Link>
                        </Button>
                    </div>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Name</TableHead>
                                <TableHead>Cities</TableHead>
                                <TableHead>Active</TableHead>
                                <TableHead>
                                    <span className="sr-only">Actions</span>
                                </TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {enrichedCountries.map((country) => (
                                <TableRow key={country.id}>
                                    <TableCell className="font-medium">{country.name}</TableCell>
                                    <TableCell>{country.cityCount}</TableCell>
                                    <TableCell>
                                        <Switch
                                            checked={country.isActive}
                                            onCheckedChange={(checked) => handleActiveChange(country.id, checked)}
                                        />
                                    </TableCell>
                                    <TableCell className='text-right'>
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button aria-haspopup="true" size="icon" variant="ghost">
                                                    <MoreHorizontal className="h-4 w-4" />
                                                    <span className="sr-only">Toggle menu</span>
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuItem onClick={() => handleOpenDialog(country)}>
                                                    <Edit className="mr-2 h-4 w-4" />
                                                    Edit
                                                </DropdownMenuItem>
                                                <DropdownMenuItem className="text-destructive">
                                                    <Trash2 className="mr-2 h-4 w-4" />
                                                    Delete
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

             <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent>
                    <form onSubmit={handleSubmit}>
                        <DialogHeader>
                            <DialogTitle>Edit Country</DialogTitle>
                            <DialogDescription>Update the details for this country.</DialogDescription>
                        </DialogHeader>
                        {editingCountry && (
                            <div className="space-y-4 py-4">
                                <div className="space-y-2">
                                    <Label htmlFor="name">Country Name</Label>
                                    <Input id="name" name="name" placeholder="e.g. United States" defaultValue={editingCountry?.name} required />
                                </div>
                            </div>
                        )}
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                            {editingCountry && <Button type="submit">Save Changes</Button>}
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
}
