import { Head } from '@inertiajs/react';
import { Building2, Plus, Search } from 'lucide-react';
import { useState } from 'react';

import { type BreadcrumbItem } from '@/types';
import AppLayout from '@/layouts/app-layout';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { usePage } from '@inertiajs/react';
import { SharedData } from '@/types';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/' },
    { title: 'Clients', href: '/user-management/clients' },
];

interface Client {
    id: number;
    name: string;
    code: string;
    email: string | null;
    phone: string | null;
    is_active: boolean;
    users_count?: number;
    created_at: string;
}

export default function Clients() {
    const [search, setSearch] = useState('');
    const [clients, setClients] = useState<Client[]>([]);
    const [loading, setLoading] = useState(false);
    const { auth } = usePage<SharedData>().props;

    const fetchClients = async () => {
        setLoading(true);
        try {
            const res = await fetch(`/api/v1/clients?search=${encodeURIComponent(search)}`, {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('jwt_token') || ''}`,
                },
            });
            const json = await res.json();
            setClients(json.data?.data || json.data || []);
        } catch {
            // fallback - use cookie auth
        }
        setLoading(false);
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Clients" />
            <div className="flex h-full flex-1 flex-col gap-6 p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">Clients</h1>
                        <p className="text-muted-foreground text-sm mt-1">Gestion des comptes clients</p>
                    </div>
                    <Button className="gap-2">
                        <Plus className="size-4" />
                        Nouveau client
                    </Button>
                </div>

                <Card>
                    <CardHeader>
                        <div className="flex items-center gap-3">
                            <div className="relative flex-1 max-w-sm">
                                <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                                <Input
                                    placeholder="Rechercher un client..."
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && fetchClients()}
                                    className="pl-9"
                                />
                            </div>
                            <Button variant="secondary" onClick={fetchClients} disabled={loading}>
                                {loading ? 'Chargement...' : 'Rechercher'}
                            </Button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Nom</TableHead>
                                    <TableHead>Code</TableHead>
                                    <TableHead>Email</TableHead>
                                    <TableHead>Statut</TableHead>
                                    <TableHead>Créé le</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {clients.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={5} className="text-center text-muted-foreground py-12">
                                            <Building2 className="size-8 mx-auto mb-2 opacity-50" />
                                            Cliquez sur « Rechercher » pour charger les clients
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    clients.map((client) => (
                                        <TableRow key={client.id}>
                                            <TableCell className="font-medium">{client.name}</TableCell>
                                            <TableCell>
                                                <code className="text-xs bg-muted px-1.5 py-0.5 rounded">{client.code}</code>
                                            </TableCell>
                                            <TableCell className="text-sm">{client.email || '—'}</TableCell>
                                            <TableCell>
                                                <Badge variant={client.is_active ? 'default' : 'destructive'} className="text-xs">
                                                    {client.is_active ? 'Actif' : 'Inactif'}
                                                </Badge>
                                            </TableCell>
                                            <TableCell className="text-sm text-muted-foreground">
                                                {new Date(client.created_at).toLocaleDateString('fr-FR')}
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
