import { router } from '@inertiajs/react';
import { ArrowRightLeft, Pencil, ScrollText, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { ImagePreviewButton } from '@/components/dialogs';
import type { ImagePreviewItem } 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 { stockMutations } from '@/routes/admin/master/products/variants';
import type { Product, ProductVariant } from '../columns';
import { TransferStockDialog } from './transfer-stock-dialog';

export function VariantSubRow({
    product,
    allPreviewItems,
    onEditVariant,
    onDeleteVariantClick,
}: {
    product: Product;
    allPreviewItems: ImagePreviewItem[];
    onEditVariant: (product: Product, variant: ProductVariant) => void;
    onDeleteVariantClick: (product: Product, variant: ProductVariant) => void;
}) {
    const { can, hasRole } = useCan();
    const isVerifier = hasRole('developer') || hasRole('owner');
    const isPending = product.status === 'pending';
    const isRejected = product.status === 'rejected';
    const variants = product.product_variants ?? [];
    const [transferVariant, setTransferVariant] = useState<{
        product: Product;
        variant: ProductVariant;
    } | null>(null);

    // Pending: no actions at all
    // Rejected: only edit/delete for non-verifier
    // Active/Inactive/Draft: all actions
    const showTransfer = !isPending && !isRejected && can('products.transfer_stock');
    const showMutations = !isPending && !isRejected && can('products.view_stock_mutations');
    const showEdit = !isPending && (isRejected ? !isVerifier && can('products.update') : can('products.update'));
    const showDelete = !isPending && (isRejected ? !isVerifier && can('products.delete') : can('products.delete'));
    const canAnyAction = showTransfer || showMutations || showEdit || showDelete;

    return (
        <div className="overflow-x-auto">
            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead className="w-[50px] text-center">
                            No
                        </TableHead>
                        <TableHead className="w-[60px]">Foto</TableHead>
                        <TableHead className="w-[200px]">Nama Varian</TableHead>
                        <TableHead className="text-center">
                            Stok Bagus
                        </TableHead>
                        <TableHead className="text-center">
                            Stok Reject
                        </TableHead>
                        <TableHead className="text-center">Stok Ecer</TableHead>
                        <TableHead>Harga</TableHead>
                        {canAnyAction && (
                            <TableHead className="w-[120px] text-center">
                                Aksi
                            </TableHead>
                        )}
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {variants.length === 0 ? (
                        <TableRow>
                            <TableCell
                                colSpan={canAnyAction ? 8 : 7}
                                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_urls?.length > 0 ? (
                                        <ImagePreviewButton
                                            srcs={variant.photo_conversion_urls?.length > 0 ? variant.photo_conversion_urls : variant.photo_urls}
                                            modalSrcs={variant.photo_urls}
                                            title={variant.name}
                                            description={`Stok Bagus: ${variant.formatted_stock} | Stok Reject: ${variant.formatted_reject_stock} | Stok Ecer: ${variant.formatted_retail_stock}`}
                                            items={allPreviewItems}
                                            startIndex={allPreviewItems.findIndex((item) => item.id === `${product.id}-${variant.id}`)}
                                        />
                                    ) : (
                                        <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.name}
                                </TableCell>
                                <TableCell className="text-center">
                                    {formatNumber(variant.stock)}
                                </TableCell>
                                <TableCell className="text-center">
                                    {formatNumber(variant.reject_stock)}
                                </TableCell>
                                <TableCell className="text-center">
                                    {formatNumber(variant.retail_stock)}
                                </TableCell>
                                <TableCell>
                                    {variant.product_prices?.length > 0 ? (
                                        <div className="flex flex-col gap-0.5">
                                            {variant.product_prices.map((p) => (
                                                <span
                                                    key={p.id}
                                                    className="text-xs"
                                                >
                                                    <span className="text-muted-foreground">
                                                        {p.type_label}:
                                                    </span>{' '}
                                                    {formatCurrency(p.price)}
                                                </span>
                                            ))}
                                        </div>
                                    ) : (
                                        '-'
                                    )}
                                </TableCell>
                                {canAnyAction && (
                                    <TableCell>
                                        <RowActions
                                            actions={[
                                                {
                                                    label: 'Transfer Stok',
                                                    icon: (
                                                        <ArrowRightLeft className="h-4 w-4" />
                                                    ),
                                                    show: showTransfer,
                                                    onClick: () =>
                                                        setTransferVariant({
                                                            product,
                                                            variant,
                                                        }),
                                                },
                                                {
                                                    label: 'Mutasi Stok',
                                                    icon: (
                                                        <ScrollText className="h-4 w-4" />
                                                    ),
                                                    show: showMutations,
                                                    onClick: () => {
                                                        router.visit(
                                                            stockMutations.url({
                                                                product: product.id,
                                                                variant: variant.id,
                                                            }),
                                                        );
                                                    },
                                                },
                                                {
                                                    label: 'Edit',
                                                    icon: (
                                                        <Pencil className="h-4 w-4" />
                                                    ),
                                                    show: showEdit,
                                                    onClick: () =>
                                                        onEditVariant(
                                                            product,
                                                            variant,
                                                        ),
                                                },
                                                {
                                                    label: 'Hapus',
                                                    icon: (
                                                        <Trash2 className="h-4 w-4 text-destructive" />
                                                    ),
                                                    show: showDelete,
                                                    onClick: () =>
                                                        onDeleteVariantClick(
                                                            product,
                                                            variant,
                                                        ),
                                                },
                                            ]}
                                        />
                                    </TableCell>
                                )}
                            </TableRow>
                        ))
                    )}
                </TableBody>
            </Table>

            {transferVariant && (
                <TransferStockDialog
                    open={transferVariant !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setTransferVariant(null);
                        }
                    }}
                    product={transferVariant.product}
                    variant={transferVariant.variant}
                />
            )}
        </div>
    );
}
