import { ChevronDown, Pencil, Trash2 } from 'lucide-react';
import { ImagePreviewButton } from '@/components/dialogs';
import { RowActions } from '@/components/data-display';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/hooks/use-can';
import { formatDateTime, formatNumber } from '@/lib/format';
import { formatCurrency } from '@/lib/utils';
import type { Cutting } from './columns';

export type CuttingCardRowParams = {
    cutting: Cutting;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onEdit: (cutting: Cutting) => void;
    onDelete: (cutting: Cutting) => void;
};

export function CuttingCardRow({
    cutting,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
}: CuttingCardRowParams) {
    const { can } = useCan();
    const items = cutting.cutting_materials ?? [];
    const result = cutting.cutting_results?.[0];
    const singleCount = items.filter(
        (item) => item.combination_id === null,
    ).length;
    const comboCount = new Set(
        items
            .filter((item) => item.combination_id !== null)
            .map((item) => item.combination_id),
    ).size;
    const materialCount = singleCount + comboCount;
    const productName = result?.product_name ?? '-';
    const totalUsage = items.reduce(
        (sum, item) => sum + Number(item.material_usage),
        0,
    );

    return (
        <>
            <Card className="overflow-hidden">
                <CardContent className="p-0">
                    <div className="flex items-start gap-3 p-4">
                        <Button
                            variant="ghost"
                            size="icon"
                            className="mt-0.5 h-6 w-6 shrink-0"
                            onClick={onToggleExpand}
                        >
                            <ChevronDown
                                className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                            />
                        </Button>

                        <div className="min-w-0 flex-1">
                            <div className="flex flex-wrap items-center gap-2">
                                <span className="text-xs text-muted-foreground">
                                    {index}.
                                </span>
                                <h3 className="truncate font-medium">
                                    {productName}
                                </h3>
                            </div>

                            <div className="mt-1 text-xs text-muted-foreground">
                                {materialCount > 0 && (
                                    <span>
                                        {materialCount} bahan baku
                                    </span>
                                )}
                                {cutting.description && (
                                    <span className="ml-2">
                                        · {cutting.description}
                                    </span>
                                )}
                            </div>

                            <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                                <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                    {formatDateTime(cutting.created_at)}
                                </span>
                                <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                    {cutting.status === 'completed'
                                        ? 'Selesai'
                                        : cutting.status === 'cancelled'
                                            ? 'Dibatalkan'
                                            : 'Dikerjakan'}
                                </span>
                            </div>

                            <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
                                <span>
                                    <span className="text-muted-foreground">
                                        Pemakaian:{' '}
                                    </span>
                                    {formatNumber(totalUsage)}
                                </span>
                                {result?.cutting_result && (
                                    <span>
                                        <span className="text-muted-foreground">
                                            Hasil:{' '}
                                        </span>
                                        {formatNumber(result.cutting_result)}
                                    </span>
                                )}
                                {cutting.cost_per_unit && (
                                    <span className="font-semibold">
                                        <span className="font-normal text-muted-foreground">
                                            Per Produk:{' '}
                                        </span>
                                        {formatCurrency(cutting.cost_per_unit)}
                                    </span>
                                )}
                                {cutting.total_material_cost && (
                                    <span className="font-semibold">
                                        <span className="font-normal text-muted-foreground">
                                            Biaya Keseluruhan:{' '}
                                        </span>
                                        {formatCurrency(cutting.total_material_cost)}
                                    </span>
                                )}
                            </div>

                            {cutting.photo_url && (
                                <div className="mt-2">
                                    <ImagePreviewButton
                                        srcs={[cutting.photo_url]}
                                        title="Foto Cutting"
                                        className="h-16 w-16"
                                    />
                                </div>
                            )}
                        </div>

                        {(can('cuttings.update') || can('cuttings.delete')) && (
                            <RowActions
                                actions={[
                                    {
                                        label: 'Edit',
                                        icon: <Pencil className="h-4 w-4" />,
                                        show: can('cuttings.update'),
                                        onClick: () => onEdit(cutting),
                                    },
                                    {
                                        label: 'Hapus',
                                        icon: (
                                            <Trash2 className="h-4 w-4 text-destructive" />
                                        ),
                                        show: can('cuttings.delete'),
                                        onClick: () => onDelete(cutting),
                                    },
                                ]}
                                wrapperClassName="flex shrink-0 items-center gap-1"
                            />
                        )}
                    </div>
                </CardContent>
            </Card>
        </>
    );
}
