import { ChevronDown, Pencil, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import type { Restock, RestockStockType } from './columns';

function formatDateTime(dateString: string): string {
    const date = new Date(dateString);

    return date.toLocaleDateString('id-ID', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });
}

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);
}

const STOCK_TYPE_CONFIG: Record<
    RestockStockType,
    { label: string; className: string }
> = {
    good: {
        label: 'Bagus',
        className: 'bg-green-100 text-green-800 hover:bg-green-100',
    },
    reject: {
        label: 'Reject',
        className: 'bg-red-100 text-red-800 hover:bg-red-100',
    },
};

export type RestockCardRowParams = {
    restock: Restock;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onEdit: (restock: Restock) => void;
    onDelete: (restock: Restock) => void;
};

export function RestockCardRow({
    restock,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
}: RestockCardRowParams) {
    const items = restock.restock_items ?? [];
    const variantCount = items.length;
    const productNames = [
        ...new Set(
            items.map((item) => item.product_variant?.product?.name).filter(Boolean),
        ),
    ];
    const totalQty = items.reduce(
        (sum, item) => sum + Number(item.quantity),
        0,
    );
    const stockTypeConfig =
        STOCK_TYPE_CONFIG[restock.stock_type] ?? STOCK_TYPE_CONFIG.good;

    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">
                                {productNames.length > 0
                                    ? productNames.join(', ')
                                    : '-'}
                            </h3>
                            <Badge
                                variant="secondary"
                                className={stockTypeConfig.className}
                            >
                                {stockTypeConfig.label}
                            </Badge>
                        </div>

                        <div className="mt-1 text-xs text-muted-foreground">
                            {variantCount > 0 && (
                                <span>({variantCount} varian)</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(restock.created_at)}
                            </span>
                            <span className="text-muted-foreground">
                                Oleh:{' '}
                                <span className="font-medium text-foreground">
                                    {restock.created_by?.user_profile
                                        ?.full_name ?? '-'}
                                </span>
                            </span>
                            {restock.notes && (
                                <span className="max-w-[200px] truncate">
                                    {restock.notes}
                                </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">
                                    Qty:{' '}
                                </span>
                                {formatNumber(totalQty)}
                            </span>
                            <span>
                                <span className="text-muted-foreground">
                                    Sub:{' '}
                                </span>
                                {formatCurrency(restock.subtotal)}
                            </span>
                            <span className="font-semibold">
                                <span className="text-muted-foreground font-normal">
                                    Total:{' '}
                                </span>
                                {formatCurrency(restock.total)}
                            </span>
                        </div>
                    </div>

                    <TooltipProvider>
                        <div className="flex shrink-0 items-center gap-1">
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => onEdit(restock)}
                                    >
                                        <Pencil className="h-4 w-4" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">Edit</TooltipContent>
                            </Tooltip>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => onDelete(restock)}
                                    >
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">
                                    Hapus
                                </TooltipContent>
                            </Tooltip>
                        </div>
                    </TooltipProvider>
                </div>
            </CardContent>
        </Card>
    );
}
