import { Link } from '@inertiajs/react';
import { FileText, Pencil, Receipt } from 'lucide-react';
import { edit as purchasesEdit } from '@/actions/App/Http/Controllers/PurchaseController';
import { StorageFilePreview } from '@/components/employees/storage-file-preview';
import { PurchasePaymentStatusBadge } from '@/components/purchases/purchase-payment-status-badge';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useLanguage } from '@/contexts/language-context';
import {
    formatAppDateOrDash,
    formatMoneyAmountOrDash,
    formatPurchaseCurrencyLabel,
    formatPurchaseMoneyOrDash,
} from '@/lib/dates';
import { formatBaseQuantity } from '@/lib/purchase-quantity';

function DetailItem({ label, children }) {
    return (
        <div className="space-y-1">
            <dt className="text-muted-foreground text-xs font-medium">{label}</dt>
            <dd className="text-sm font-medium">{children}</dd>
        </div>
    );
}

/**
 * @param {object} props
 * @param {object|null} props.purchase
 * @param {boolean} props.open
 * @param {(open: boolean) => void} props.onOpenChange
 * @param {Record<string, string>} props.labels
 * @param {boolean} [props.canUpdate]
 */
export function PurchaseDetailsDialog({
    purchase,
    open,
    onOpenChange,
    labels,
    canUpdate = false,
}) {
    const { locale } = useLanguage();

    if (!purchase) {
        return null;
    }

    const items = purchase.items ?? [];
    const hasNotes = Boolean(purchase.notes?.trim());
    const canEdit = canUpdate && !purchase.has_payments;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="gap-0 overflow-hidden p-0 sm:max-w-2xl">
                <div className="bg-muted/40 border-b border-border px-6 py-5">
                    <DialogHeader className="space-y-3 text-start">
                        <div className="flex items-start gap-3">
                            <div className="bg-background flex size-11 shrink-0 items-center justify-center rounded-lg border border-border shadow-xs">
                                <Receipt className="text-muted-foreground size-5" />
                            </div>
                            <div className="min-w-0 flex-1 space-y-2">
                                <DialogTitle className="text-start text-xl tracking-tight">
                                    {purchase.bill_number || '—'}
                                </DialogTitle>
                                <DialogDescription className="text-start">
                                    {labels.viewPurchaseSubtitle}
                                </DialogDescription>
                                <div className="flex flex-wrap items-center gap-2">
                                    <Badge variant="outline" className="font-normal">
                                        {formatAppDateOrDash(purchase.purchased_at, locale)}
                                    </Badge>
                                    <Badge variant="secondary" className="font-normal">
                                        {formatPurchaseCurrencyLabel(purchase.currency, locale)}
                                    </Badge>
                                    <PurchasePaymentStatusBadge
                                        status={purchase.payment_status}
                                        labels={labels}
                                    />
                                </div>
                            </div>
                        </div>
                    </DialogHeader>
                </div>

                <div className="max-h-[min(62vh,36rem)] space-y-5 overflow-y-auto px-6 py-5">
                    <dl className="grid gap-4 sm:grid-cols-2">
                        <DetailItem label={labels.supplier}>
                            {purchase.supplier_name || '—'}
                        </DetailItem>
                        <DetailItem label={labels.totalAmount}>
                            {formatPurchaseMoneyOrDash(
                                purchase.total_amount,
                                purchase.currency,
                                locale,
                            )}
                        </DetailItem>
                        <DetailItem label={labels.colPaid}>
                            {formatMoneyAmountOrDash(purchase.paid_amount, locale)}
                        </DetailItem>
                        <DetailItem label={labels.colDue}>
                            {formatMoneyAmountOrDash(purchase.due_amount, locale)}
                        </DetailItem>
                    </dl>

                    <div className="space-y-3">
                        <h3 className="flex items-center gap-2 text-sm font-semibold">
                            <FileText className="size-4" />
                            {labels.productsSection}
                        </h3>
                        <div className="overflow-x-auto rounded-lg border border-border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="w-10">{labels.colSerial}</TableHead>
                                        <TableHead>{labels.product}</TableHead>
                                        <TableHead>{labels.colUnit}</TableHead>
                                        <TableHead>{labels.quantity}</TableHead>
                                        <TableHead>{labels.totalInBase}</TableHead>
                                        <TableHead>{labels.unitPrice}</TableHead>
                                        <TableHead>{labels.lineTotal}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {items.length === 0 ? (
                                        <TableRow>
                                            <TableCell
                                                colSpan={7}
                                                className="text-muted-foreground h-16 text-center text-sm"
                                            >
                                                {labels.noProductsOnBill}
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        items.map((item, index) => (
                                            <TableRow key={index}>
                                                <TableCell className="text-muted-foreground tabular-nums">
                                                    {index + 1}
                                                </TableCell>
                                                <TableCell className="font-medium">
                                                    {item.product_name || '—'}
                                                </TableCell>
                                                <TableCell>{item.unit_name || '—'}</TableCell>
                                                <TableCell className="tabular-nums">
                                                    {formatMoneyAmountOrDash(
                                                        item.quantity,
                                                        locale,
                                                    )}
                                                </TableCell>
                                                <TableCell className="tabular-nums">
                                                    {item.uses_base_unit && item.base_unit_name ? (
                                                        labels.totalInBaseValue
                                                            .replace(
                                                                '{qty}',
                                                                formatBaseQuantity(
                                                                    Number(item.total_in_base),
                                                                    locale,
                                                                ),
                                                            )
                                                            .replace('{unit}', item.base_unit_name)
                                                    ) : (
                                                        '—'
                                                    )}
                                                </TableCell>
                                                <TableCell className="tabular-nums">
                                                    {formatMoneyAmountOrDash(
                                                        item.unit_price,
                                                        locale,
                                                    )}
                                                </TableCell>
                                                <TableCell className="tabular-nums font-medium">
                                                    {formatMoneyAmountOrDash(
                                                        item.line_total,
                                                        locale,
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </div>

                    {hasNotes ? (
                        <div className="space-y-2">
                            <h3 className="text-sm font-semibold">{labels.notes}</h3>
                            <p className="text-muted-foreground rounded-lg border border-border bg-muted/20 p-3 text-sm whitespace-pre-wrap">
                                {purchase.notes}
                            </p>
                        </div>
                    ) : null}

                    {purchase.bill_file_url ? (
                        <div className="space-y-2">
                            <h3 className="text-sm font-semibold">{labels.billFile}</h3>
                            <StorageFilePreview
                                url={purchase.bill_file_url}
                                alt={labels.billFile}
                                linkLabel={labels.viewCurrentBillFile}
                                size="md"
                            />
                        </div>
                    ) : null}
                </div>

                <DialogFooter className="border-t border-border px-6 py-4">
                    <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                        {labels.closeDetails}
                    </Button>
                    {canEdit ? (
                        <Button asChild>
                            <Link href={purchasesEdit.url(purchase.id)} prefetch>
                                <Pencil className="size-4" />
                                {labels.editPurchase}
                            </Link>
                        </Button>
                    ) : null}
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
