import { Head, router } from '@inertiajs/react';

import { IconButton } from '@/components/common/IconButton';
import { Badge } from '@/components/ui/badge';
import { Icon } from '@/components/ui/icon';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { useI18n } from '@/hooks/use-i18n';
import { ClientShowLayout } from '@/layouts/clients/client-show-layout';

interface ClientSummary {
    id: number;
    name: string;
    cif: string | null;
    active?: boolean;
    efactura_auth_url: string | null;
    efactura_has_anaf_token: boolean;
    efactura_anaf_token_synced_at: string | null;
    efactura_anaf_token_expires_at: string | null;
    efactura_token_needs_refresh: boolean;
}

interface FlowSummary {
    count: number;
    total: number;
    vat: number;
    subtotal: number;
}

interface TopSupplier {
    name: string | null;
    identifier: string | null;
    total: number;
    vat: number;
    count: number;
}

interface DayEntry {
    date: string | null;
    incoming: number;
    outgoing: number;
}

interface ReportDocument {
    document_id: number;
    document_number: string | null;
    document_type: string | null;
    document_direction: 'incoming' | 'outgoing' | null;
    issuer_name: string | null;
    customer_name: string | null;
    total_amount: string | null;
    vat_amount: string | null;
    currency: string | null;
    issue_date: string | null;
    accountant_status: string | null;
}

interface FinancialReportProps {
    client: ClientSummary;
    period: string;
    summary: {
        incoming: FlowSummary;
        outgoing: FlowSummary;
    };
    top_suppliers: TopSupplier[];
    by_day: DayEntry[];
    documents: ReportDocument[];
}

function formatAmount(value: number): string {
    return new Intl.NumberFormat('ro-RO', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value);
}

function SummaryCard({ title, data, variant }: { title: string; data: FlowSummary; variant: 'incoming' | 'outgoing' }) {
    const isIncoming = variant === 'incoming';
    return (
        <Card>
            <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground uppercase tracking-wide">
                    <Icon
                        icon={isIncoming ? 'solar:arrow-down-bold-duotone' : 'solar:arrow-up-bold-duotone'}
                        className={isIncoming ? 'size-4 text-[var(--success)]' : 'size-4 text-destructive'}
                    />
                    {title}
                </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
                <div className="flex items-baseline justify-between">
                    <span className="text-xs text-muted-foreground">Total</span>
                    <span className="font-semibold tabular-nums">{formatAmount(data.total)} RON</span>
                </div>
                <div className="flex items-baseline justify-between">
                    <span className="text-xs text-muted-foreground">TVA</span>
                    <span className="text-sm tabular-nums">{formatAmount(data.vat)} RON</span>
                </div>
                <div className="flex items-baseline justify-between">
                    <span className="text-xs text-muted-foreground">Fără TVA</span>
                    <span className="text-sm tabular-nums">{formatAmount(data.subtotal)} RON</span>
                </div>
                <Separator />
                <div className="flex items-baseline justify-between">
                    <span className="text-xs text-muted-foreground">Documente</span>
                    <Badge variant="secondarySoft">{data.count}</Badge>
                </div>
            </CardContent>
        </Card>
    );
}

export default function ClientFinancialReportPage({
    client,
    period,
    summary,
    top_suppliers,
    documents,
}: FinancialReportProps) {
    const { t } = useI18n();

    const [year, month] = period.split('-');
    const prevMonth = new Date(Number(year), Number(month) - 2, 1);
    const nextMonth = new Date(Number(year), Number(month), 1);
    const now = new Date();
    const isNextFuture = nextMonth > now;

    const goToPeriod = (date: Date) => {
        const p = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        router.get(`/admin/clients/${client.id}/financial-report`, { month: p }, { preserveScroll: true });
    };

    const periodLabel = new Date(Number(year), Number(month) - 1, 1).toLocaleDateString('ro-RO', {
        month: 'long',
        year: 'numeric',
    });

    return (
        <ClientShowLayout client={{ ...client, active: client.active ?? true }}>
            <Head title={`${client.name} — ${t('clients.show.nav.financial_report')}`} />

            <div className="mb-6 flex items-center justify-between">
                <h2 className="text-base font-semibold">{t('clients.show.nav.financial_report')}</h2>
                <div className="flex items-center gap-2">
                    <IconButton
                        variant="outlined"
                        size="sm"
                        onClick={() => goToPeriod(prevMonth)}
                        icon="solar:alt-arrow-left-linear"
                        aria-label={t('clients.show.financial_report.previous_period')}
                    />
                    <span className="min-w-[130px] text-center text-sm font-medium capitalize">{periodLabel}</span>
                    <IconButton
                        variant="outlined"
                        size="sm"
                        onClick={() => goToPeriod(nextMonth)}
                        disabled={isNextFuture}
                        icon="solar:alt-arrow-right-linear"
                        aria-label={t('clients.show.financial_report.next_period')}
                    />
                </div>
            </div>

            <div className="space-y-6">
                <div className="grid gap-4 sm:grid-cols-2">
                    <SummaryCard title="Intrări" data={summary.incoming} variant="incoming" />
                    <SummaryCard title="Ieșiri" data={summary.outgoing} variant="outgoing" />
                </div>

                {top_suppliers.length > 0 && (
                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                                Top furnizori
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="divide-y divide-border/50 p-0">
                            {top_suppliers.map((supplier, i) => (
                                <div key={i} className="flex items-center justify-between px-4 py-2.5">
                                    <div className="min-w-0">
                                        <p className="truncate text-sm font-medium">{supplier.name ?? '—'}</p>
                                        {supplier.identifier && (
                                            <p className="text-xs text-muted-foreground">{supplier.identifier}</p>
                                        )}
                                    </div>
                                    <div className="ml-4 shrink-0 text-right">
                                        <p className="text-sm font-semibold tabular-nums">{formatAmount(supplier.total)} RON</p>
                                        <p className="text-xs text-muted-foreground">{supplier.count} doc.</p>
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                )}

                {documents.length > 0 && (
                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                                Documente ({documents.length})
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="divide-y divide-border/50 p-0">
                            {documents.map((doc) => (
                                <div
                                    key={doc.document_id}
                                    className="flex cursor-pointer items-start gap-3 px-4 py-3 hover:bg-muted/50 transition-colors"
                                    onClick={() => router.visit(`/admin/documents/${doc.document_id}`)}
                                >
                                    <Icon
                                        icon={doc.document_direction === 'incoming'
                                            ? 'solar:arrow-down-bold-duotone'
                                            : 'solar:arrow-up-bold-duotone'}
                                        className={doc.document_direction === 'incoming'
                                            ? 'mt-0.5 size-4 shrink-0 text-[var(--success)]'
                                            : 'mt-0.5 size-4 shrink-0 text-destructive'}
                                    />
                                    <div className="min-w-0 flex-1">
                                        <div className="flex items-baseline justify-between gap-2">
                                            <span className="truncate text-sm font-medium">
                                                {doc.document_number ?? '—'}
                                            </span>
                                            {doc.total_amount && (
                                                <span className="shrink-0 text-xs font-medium tabular-nums">
                                                    {formatAmount(Number(doc.total_amount))} {doc.currency ?? ''}
                                                </span>
                                            )}
                                        </div>
                                        <p className="text-xs text-muted-foreground truncate">
                                            {[doc.issuer_name, doc.issue_date].filter(Boolean).join(' · ')}
                                        </p>
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                )}

                {documents.length === 0 && (
                    <div className="py-16 text-center text-sm text-muted-foreground">
                        {t('clients.show.financial_report.empty')}
                    </div>
                )}
            </div>
        </ClientShowLayout>
    );
}
