import { router } from '@inertiajs/react';
import { Pencil, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { ImagePreviewModal } from '@/components/image-preview-modal';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import type { RawMaterial, RawMaterialVariant } from '../columns';
import { edit as variantEdit, destroy as variantDestroy } from '@/routes/admin/master/raw-materials/variants';

function formatCurrency(amount: number): string {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0,
    }).format(amount);
}

function formatNumber(num: number): string {
    return new Intl.NumberFormat('id-ID', { maximumFractionDigits: 4 }).format(num);
}

function VariantPhotoPreview({ url, title }: { url: string; title: string }) {
    const [open, setOpen] = useState(false);

    return (
        <>
            <button
                onClick={() => setOpen(true)}
                className="relative block h-10 w-10 overflow-hidden rounded-md border bg-muted transition-opacity hover:opacity-80"
            >
                <img
                    src={url}
                    alt={title}
                    className="h-full w-full object-cover"
                />
            </button>
            <ImagePreviewModal
                open={open}
                onOpenChange={setOpen}
                src={url}
                sources={[url]}
                title={title}
            />
        </>
    );
}

export function RawMaterialVariantSubRow({
    rawMaterial,
}: {
    rawMaterial: RawMaterial;
}) {
    const variants = rawMaterial.raw_material_prices ?? [];
    const [deletingVariant, setDeletingVariant] = useState<RawMaterialVariant | null>(null);

    function handleDeleteVariant() {
        if (!deletingVariant) return;

        router.delete(
            variantDestroy.url({
                rawMaterial: rawMaterial.id,
                variant: deletingVariant.id,
            }),
            {
                onSuccess: () => setDeletingVariant(null),
            },
        );
    }

    return (
        <div className="overflow-x-auto">
            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead className="w-[50px] text-center">
                            No
                        </TableHead>
                        <TableHead className="w-[60px]">Foto</TableHead>
                        <TableHead>Nama Varian</TableHead>
                        <TableHead>Harga</TableHead>
                        <TableHead className="text-center">Stok</TableHead>
                        <TableHead className="w-[100px] text-center">
                            Aksi
                        </TableHead>
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {variants.length === 0 ? (
                        <TableRow>
                            <TableCell
                                colSpan={6}
                                className="text-center text-muted-foreground"
                            >
                                Tidak ada varian.
                            </TableCell>
                        </TableRow>
                    ) : (
                        variants.map((variant, index) => (
                            <TableRow key={variant.id}>
                                <TableCell className="text-center">
                                    {index + 1}
                                </TableCell>
                                <TableCell>
                                    {variant.photo_url ? (
                                        <VariantPhotoPreview
                                            url={variant.photo_url}
                                            title={variant.variant}
                                        />
                                    ) : (
                                        <div className="flex h-10 w-10 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
                                            N/A
                                        </div>
                                    )}
                                </TableCell>
                                <TableCell className="font-medium">
                                    {variant.variant}
                                </TableCell>
                                <TableCell>
                                    {formatCurrency(variant.price)}
                                </TableCell>
                                <TableCell className="text-center">
                                    {formatNumber(variant.stock)}
                                </TableCell>
                                <TableCell>
                                    <TooltipProvider>
                                        <div className="flex items-center justify-center gap-1">
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={() => {
                                                            window.location.href = variantEdit.url({
                                                                rawMaterial: rawMaterial.id,
                                                                variant: variant.id,
                                                            });
                                                        }}
                                                    >
                                                        <Pencil className="h-4 w-4" />
                                                    </Button>
                                                </TooltipTrigger>
                                                <TooltipContent side="top">
                                                    Edit
                                                </TooltipContent>
                                            </Tooltip>
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        onClick={() =>
                                                            setDeletingVariant(variant)
                                                        }
                                                    >
                                                        <Trash2 className="h-4 w-4 text-destructive" />
                                                    </Button>
                                                </TooltipTrigger>
                                                <TooltipContent side="top">
                                                    Hapus
                                                </TooltipContent>
                                            </Tooltip>
                                        </div>
                                    </TooltipProvider>
                                </TableCell>
                            </TableRow>
                        ))
                    )}
                </TableBody>
            </Table>

            {deletingVariant && (
                <ConfirmDialog
                    open={deletingVariant !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeletingVariant(null);
                        }
                    }}
                    title="Hapus Varian"
                    description={`Apakah Anda yakin ingin menghapus varian "${deletingVariant.variant}" dari bahan baku "${rawMaterial.name}"? Tindakan ini tidak dapat dibatalkan.`}
                    confirmLabel="Hapus"
                    onConfirm={handleDeleteVariant}
                />
            )}
        </div>
    );
}
