import { Head } from '@inertiajs/react';
import Heading from '@/components/heading';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatCurrency } from '@/lib/utils';
import { dashboard } from '@/routes';
import { services } from '@/routes/admin/dashboards';
import {
    DashboardExportButtons,
    DashboardFiltersBar,
    type DashboardFilters,
    type FilterOptions,
} from './dashboard-filters';
import { KpiCard, LineChart } from './dashboard-widgets';

export default function DashboardsServices({
    overview,
    filters,
    filterOptions,
    can,
}: {
    overview: {
        kpis: {
            revenue: string;
            revenue_ht?: string;
            services_sold: string;
            invoices_count: number;
            top_service: string | null;
            avg_unit_price: string;
            vat_rate: string;
        };
        ranking: Array<{
            service_id: number;
            code: string;
            name: string;
            category: string | null;
            quantity: string;
            revenue: string;
            unit_price: string;
            vat_rate: string;
        }>;
        by_category: Array<{
            category_id: number;
            code: string;
            name: string;
            revenue: string;
            quantity: string;
            productivity: string;
            vat_rate: string;
        }>;
        trend: Array<{ key: string; label: string; revenue: string }>;
    };
    filters: DashboardFilters;
    filterOptions: FilterOptions;
    can: { export: boolean };
}) {
    return (
        <>
            <Head title="Performance Services" />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                    <Heading
                        title="Performance Services"
                        description="CA des lignes de prestations uniquement (hors produits / lignes libres)"
                    />
                    <DashboardExportButtons view="services" filters={filters} canExport={can.export} />
                </div>

                <DashboardFiltersBar
                    active="services"
                    filters={filters}
                    filterOptions={filterOptions}
                    showServiceFilter
                />

                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
                    <KpiCard label="CA prestations" value={overview.kpis.revenue} hint="Lignes avec prestation" />
                    <KpiCard label="Quantités vendues" value={overview.kpis.services_sold} format="number" />
                    <KpiCard label="Factures" value={overview.kpis.invoices_count} format="number" />
                    <KpiCard label="Prix moyen" value={overview.kpis.avg_unit_price} hint="CA TTC ÷ quantité" />
                    <KpiCard label="Taux de TVA moyen" value={overview.kpis.vat_rate} format="percent" />
                </div>

                <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-sm text-muted-foreground">
                    {overview.kpis.top_service ? (
                        <p>
                            Top prestation :{' '}
                            <span className="font-medium text-foreground">{overview.kpis.top_service}</span>
                        </p>
                    ) : null}
                    {overview.kpis.revenue_ht ? (
                        <p>
                            CA HT global :{' '}
                            <span className="font-medium text-foreground">
                                {formatCurrency(overview.kpis.revenue_ht)}
                            </span>
                        </p>
                    ) : null}
                </div>

                <div className="grid gap-6 lg:grid-cols-2">
                    <Card>
                        <CardHeader>
                            <CardTitle>Évolution du CA prestations</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <LineChart
                                items={overview.trend}
                                exportTitle="Évolution du CA prestations"
                                series={[
                                    { key: 'revenue', label: 'CA prestations', color: '#2563eb' },
                                ]}
                            />
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Comparatif par pôle (catégorie)</CardTitle>
                            <CardDescription>Productivité et rentabilité par catégorie de prestation</CardDescription>
                        </CardHeader>
                        <CardContent>
                            {overview.by_category.length === 0 ? (
                                <p className="text-sm text-muted-foreground">Aucune donnée.</p>
                            ) : (
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Pôle</TableHead>
                                            <TableHead className="text-right">CA</TableHead>
                                            <TableHead className="text-right">Prod.</TableHead>
                                            <TableHead className="text-right">TVA</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {overview.by_category.map((row) => (
                                            <TableRow key={row.category_id}>
                                                <TableCell>{row.name}</TableCell>
                                                <TableCell className="text-right tabular-nums">
                                                    {formatCurrency(row.revenue)}
                                                </TableCell>
                                                <TableCell className="text-right tabular-nums">
                                                    {formatCurrency(row.productivity)}
                                                </TableCell>
                                                <TableCell className="text-right tabular-nums">
                                                    {row.vat_rate} %
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            )}
                        </CardContent>
                    </Card>
                </div>

                {overview.ranking.length > 0 && (
                    <Card>
                        <CardHeader>
                            <CardTitle>Classement des prestations</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Prestation</TableHead>
                                        <TableHead>Pôle</TableHead>
                                        <TableHead className="text-right">Qté</TableHead>
                                        <TableHead className="text-right">CA</TableHead>
                                        <TableHead className="text-right">Prix unit.</TableHead>
                                        <TableHead className="text-right">TVA</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {overview.ranking.map((row) => (
                                        <TableRow key={row.service_id}>
                                            <TableCell>
                                                <div className="font-medium">{row.name}</div>
                                                <div className="text-xs text-muted-foreground">{row.code}</div>
                                            </TableCell>
                                            <TableCell>{row.category ?? '—'}</TableCell>
                                            <TableCell className="text-right tabular-nums">{row.quantity}</TableCell>
                                            <TableCell className="text-right tabular-nums">{formatCurrency(row.revenue)}</TableCell>
                                            <TableCell className="text-right tabular-nums">{formatCurrency(row.unit_price)}</TableCell>
                                            <TableCell className="text-right tabular-nums">{row.vat_rate} %</TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                )}
            </div>
        </>
    );
}

DashboardsServices.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Performance Services', href: services() },
    ],
};
