import { router } from '@inertiajs/react';
import { Pencil, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/dialogs';
import { ImagePreviewButton } from '@/components/dialogs';
import { RowActions } from '@/components/data-display';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useCan } from '@/hooks/use-can';
import { formatNumber } from '@/lib/format';
import { formatCurrency } from '@/lib/utils';
import {
    edit as variantEdit,
    destroy as variantDestroy,
} from '@/routes/admin/master/raw-materials/variants';
import type { RawMaterial, RawMaterialVariant } from '../columns';

export function RawMaterialVariantSubRow({
    rawMaterial,
}: {
    rawMaterial: RawMaterial;
}) {
    const { can } = useCan();
    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),
            },
        );
    }

    const canAnyAction = can('raw_materials.update') || can('raw_materials.delete');

    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>
                        {canAnyAction && (
                            <TableHead className="w-[100px] text-center">
                                Aksi
                            </TableHead>
                        )}
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {variants.length === 0 ? (
                        <TableRow>
                            <TableCell
                                colSpan={canAnyAction ? 6 : 5}
                                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 ? (
                                        <ImagePreviewButton
                                            srcs={[variant.photo_conversion_url ?? variant.photo_url]}
                                            modalSrc={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>
                                {canAnyAction && (
                                    <TableCell>
                                        <RowActions
                                            actions={[
                                                {
                                                    label: 'Edit',
                                                    icon: (
                                                        <Pencil className="h-4 w-4" />
                                                    ),
                                                    show: can('raw_materials.update'),
                                                    onClick: () => {
                                                        router.visit(
                                                            variantEdit.url({
                                                                rawMaterial:
                                                                    rawMaterial.id,
                                                                variant: variant.id,
                                                            }),
                                                        );
                                                    },
                                                },
                                                {
                                                    label: 'Hapus',
                                                    icon: (
                                                        <Trash2 className="h-4 w-4 text-destructive" />
                                                    ),
                                                    show: can('raw_materials.delete'),
                                                    onClick: () =>
                                                        setDeletingVariant(variant),
                                                },
                                            ]}
                                        />
                                    </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>
    );
}
