import { ImagePreviewButton } from '@/components/image-preview-button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatNumber } from '@/lib/format';
import type { Cutting } from './columns';

export function CuttingItemSubRow({ cutting }: { cutting: Cutting }) {
    const items = cutting.cutting_materials ?? [];
    const combinations = cutting.cutting_material_combinations ?? [];

    const groupedMaterials = items.reduce(
        (acc, item) => {
            const key = item.combination_id ?? `single-${item.id}`;

            if (!acc[key]) {
                acc[key] = {
                    combination: item.combination_id
                        ? (combinations.find((c) => c.id === item.combination_id) ?? null)
                        : null,
                    materials: [],
                };
            }

            acc[key].materials.push(item);

            return acc;
        },
        {} as Record<
            string,
            {
                combination: { id: number; material_result: number | null } | null;
                materials: typeof items;
            }
        >,
    );

    return (
        <div className="space-y-4 overflow-x-auto">
            {Object.entries(groupedMaterials).map(([key, group]) => (
                <div key={key} className="space-y-2">
                    {group.combination && (
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                            <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                Kombinasi
                            </span>
                            {group.combination.material_result !== null && (
                                <span>
                                    Hasil: {formatNumber(group.combination.material_result)}
                                </span>
                            )}
                        </div>
                    )}

                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-[50px] text-center">
                                    No
                                </TableHead>
                                <TableHead className="w-[60px]">Foto</TableHead>
                                <TableHead>Bahan Baku</TableHead>
                                <TableHead>Varian</TableHead>
                                <TableHead className="text-right">Pemakaian</TableHead>
                                <TableHead className="text-right">Hasil</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {group.materials.length === 0 ? (
                                <TableRow>
                                    <TableCell
                                        colSpan={6}
                                        className="text-center text-muted-foreground"
                                    >
                                        Tidak ada item.
                                    </TableCell>
                                </TableRow>
                            ) : (
                                group.materials.map((item, index) => (
                                    <TableRow key={item.id}>
                                        <TableCell className="text-center">
                                            {index + 1}
                                        </TableCell>
                                        <TableCell>
                                            {item.raw_material_price?.photo_url ? (
                                                <ImagePreviewButton
                                                    srcs={[
                                                        item.raw_material_price
                                                            .photo_url,
                                                    ]}
                                                    title={
                                                        item.raw_material_price.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>
                                            {item.raw_material_price?.raw_material?.name ?? '-'}
                                        </TableCell>
                                        <TableCell>
                                            {item.raw_material_price?.variant ?? '-'}
                                        </TableCell>
                                        <TableCell className="text-right">
                                            {formatNumber(item.material_usage)}
                                        </TableCell>
                                        <TableCell className="text-right">
                                            {group.combination
                                                ? '-'
                                                : (item.material_result !== null
                                                    ? formatNumber(item.material_result)
                                                    : '-')}
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </div>
            ))}
        </div>
    );
}
