import type { ColumnDef } from '@tanstack/react-table';
import { router } from '@inertiajs/react';
import { ChevronRight, Pencil, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';

export type ProductVariant = {
    id: number;
    name: string;
    stock: number;
    reject_stock: number;
    retail_stock: number;
    photo_urls: string[];
    product_prices: {
        id: number;
        type: string;
        type_label: string;
        price: number;
    }[];
};

export type Product = {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    status: string;
    categories: {
        id: number;
        name: string;
    }[];
    product_variants: ProductVariant[];
};

function getStatusLabel(status: string): string {
    const labels: Record<string, string> = {
        active: 'Aktif',
        inactive: 'Non Aktif',
        draft: 'Draft',
    };

    return labels[status] ?? status;
}

function getStatusVariant(status: string): string {
    const variants: Record<string, string> = {
        active: 'bg-green-100 text-green-800',
        inactive: 'bg-red-100 text-red-800',
        draft: 'bg-yellow-100 text-yellow-800',
    };

    return variants[status] ?? 'bg-gray-100 text-gray-800';
}

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').format(num);
}

function getFilteredVariants(
    allVariants: ProductVariant[],
    searchValue: string,
): ProductVariant[] {
    const query = searchValue.toLowerCase().trim();
    return query
        ? allVariants.filter((v) => v.name.toLowerCase().includes(query))
        : allVariants;
}

type CreateColumnsParams = {
    handleEdit: (product: Product) => void;
    handleDeleteClick: (product: Product) => void;
    handleVariantEdit: (product: Product) => void;
    handleVariantDeleteClick: (
        product: Product,
        variant: ProductVariant,
    ) => void;
    toggleStatusUrl: (id: number) => string;
};

export function createProductColumns(
    params: CreateColumnsParams,
): ColumnDef<Product>[] {
    const {
        handleEdit,
        handleDeleteClick,
        handleVariantEdit,
        handleVariantDeleteClick,
        toggleStatusUrl,
    } = params;

    return [
        {
            id: 'expand',
            header: '',
            cell: ({ row }) => {
                const hasVariants =
                    (row.original.product_variants?.length ?? 0) > 0;

                if (!hasVariants) {
                    return null;
                }

                return (
                    <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={() => row.toggleExpanded()}
                    >
                        <ChevronRight
                            className={`h-4 w-4 transition-transform ${row.getIsExpanded() ? 'rotate-90' : ''}`}
                        />
                    </Button>
                );
            },
            meta: {
                className: 'w-[40px]',
                headerClassName: 'w-[40px]',
            },
        },
        {
            id: 'variant_names',
            accessorFn: (row) =>
                row.product_variants?.map((v) => v.name).join(' ') ?? '',
            header: () => null,
            cell: () => null,
            meta: {
                className: 'hidden',
                headerClassName: 'hidden',
            },
        },
        {
            accessorKey: 'name',
            header: () => <span>Nama Produk</span>,
            cell: ({ row }) => {
                const product = row.original;

                return (
                    <div className="flex flex-col">
                        <span className="font-medium">{product.name}</span>
                        <span className="text-xs text-muted-foreground">
                            {product.categories
                                ?.map((c) => c.name)
                                .join(', ') || '-'}
                        </span>
                    </div>
                );
            },
        },
        {
            id: 'variants',
            header: () => <span>Varian</span>,
            cell: ({ row, table }) => {
                const searchValue =
                    (table
                        .getColumn('variant_names')
                        ?.getFilterValue() as string) ?? '';
                const variants = getFilteredVariants(
                    row.original.product_variants ?? [],
                    searchValue,
                );

                return (
                    <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium">
                        {variants.length} varian
                    </span>
                );
            },
        },
        {
            id: 'stock',
            header: () => <span className="block text-center">Stok Bagus</span>,
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row, table }) => {
                const searchValue =
                    (table
                        .getColumn('variant_names')
                        ?.getFilterValue() as string) ?? '';
                const variants = getFilteredVariants(
                    row.original.product_variants ?? [],
                    searchValue,
                );
                const totalStock = variants.reduce(
                    (sum, v) => sum + (v.stock ?? 0),
                    0,
                );

                return (
                    <span className="block text-center font-medium">
                        {formatNumber(totalStock)}
                    </span>
                );
            },
        },
        {
            id: 'reject_stock',
            header: () => (
                <span className="block text-center">Stok Reject</span>
            ),
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row, table }) => {
                const searchValue =
                    (table
                        .getColumn('variant_names')
                        ?.getFilterValue() as string) ?? '';
                const variants = getFilteredVariants(
                    row.original.product_variants ?? [],
                    searchValue,
                );
                const totalReject = variants.reduce(
                    (sum, v) => sum + (v.reject_stock ?? 0),
                    0,
                );

                return (
                    <span className="block text-center font-medium">
                        {formatNumber(totalReject)}
                    </span>
                );
            },
        },
        {
            id: 'retail_stock',
            header: () => <span className="block text-center">Stok Ecer</span>,
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row, table }) => {
                const searchValue =
                    (table
                        .getColumn('variant_names')
                        ?.getFilterValue() as string) ?? '';
                const variants = getFilteredVariants(
                    row.original.product_variants ?? [],
                    searchValue,
                );
                const totalRetail = variants.reduce(
                    (sum, v) => sum + (v.retail_stock ?? 0),
                    0,
                );

                return (
                    <span className="block text-center font-medium">
                        {formatNumber(totalRetail)}
                    </span>
                );
            },
        },
        {
            id: 'total_stock',
            header: () => <span className="block text-center">Total Stok</span>,
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row, table }) => {
                const searchValue =
                    (table
                        .getColumn('variant_names')
                        ?.getFilterValue() as string) ?? '';
                const variants = getFilteredVariants(
                    row.original.product_variants ?? [],
                    searchValue,
                );
                const totalStock = variants.reduce(
                    (sum, v) => sum + (v.stock ?? 0),
                    0,
                );
                const totalReject = variants.reduce(
                    (sum, v) => sum + (v.reject_stock ?? 0),
                    0,
                );
                const totalRetail = variants.reduce(
                    (sum, v) => sum + (v.retail_stock ?? 0),
                    0,
                );
                const total = totalStock + totalReject + totalRetail;

                return (
                    <span className="block text-center font-medium">
                        {formatNumber(total)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'status',
            header: () => <span>Status</span>,
            cell: ({ row }) => {
                const product = row.original;
                const isToggleable =
                    product.status === 'active' ||
                    product.status === 'inactive';
                const isChecked = product.status === 'active';

                function handleToggle(checked: boolean) {
                    router.post(
                        toggleStatusUrl(product.id),
                        {},
                        {
                            preserveScroll: true,
                        },
                    );
                }

                if (!isToggleable) {
                    return (
                        <span
                            className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ${getStatusVariant(product.status)}`}
                        >
                            {getStatusLabel(product.status)}
                        </span>
                    );
                }

                return (
                    <div className="flex items-center gap-2">
                        <Switch
                            size="sm"
                            checked={isChecked}
                            onCheckedChange={handleToggle}
                        />
                        <span
                            className={`text-xs font-medium ${isChecked ? 'text-green-700' : 'text-red-700'}`}
                        >
                            {getStatusLabel(product.status)}
                        </span>
                    </div>
                );
            },
        },
        {
            id: 'actions',
            header: () => <span className="block text-center">Aksi</span>,
            meta: {
                className: 'w-[100px] text-center',
                headerClassName: 'w-[100px] text-center',
            },
            cell: ({ row }) => {
                const product = row.original;

                return (
                    <TooltipProvider>
                        <div className="flex items-center justify-center gap-1">
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => handleEdit(product)}
                                    >
                                        <Pencil className="h-4 w-4" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">Edit</TooltipContent>
                            </Tooltip>

                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() =>
                                            handleDeleteClick(product)
                                        }
                                    >
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">
                                    Hapus
                                </TooltipContent>
                            </Tooltip>
                        </div>
                    </TooltipProvider>
                );
            },
        },
    ];
}
