import { router } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import { CheckCircle, ChevronRight, Clock, Pencil, RotateCw, Trash2, XCircle } from 'lucide-react';
import { RowActions } from '@/components/data-display';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { formatNumber } from '@/lib/format';

export type ProductVariant = {
    id: number;
    name: string;
    stock: number;
    formatted_stock: string;
    reject_stock: number;
    formatted_reject_stock: string;
    retail_stock: number;
    formatted_retail_stock: string;
    photo_urls: string[];
    photo_conversion_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;
    is_featured: boolean;
    rejection_reason: string | null;
    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',
        pending: 'Menunggu Verifikasi',
        rejected: 'Ditolak',
    };

    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',
        pending: 'bg-orange-100 text-orange-800',
        rejected: 'bg-red-100 text-red-800',
    };

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

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;
    handleReject: (product: Product) => void;
    toggleStatusUrl: (id: number) => string;
    approveUrl: (id: number) => string;
    resubmitUrl: (id: number) => string;
    can: (permission: string) => boolean;
    hasRole: (role: string) => boolean;
};

export function createProductColumns(
    params: CreateColumnsParams,
): ColumnDef<Product>[] {
    const {
        handleEdit,
        handleDeleteClick,
        handleReject,
        toggleStatusUrl,
        approveUrl,
        resubmitUrl,
        can,
        hasRole,
    } = params;

    const isVerifier = hasRole('developer') || hasRole('owner');

    const columns: ColumnDef<Product>[] = [
        {
            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">
                        <div className="flex items-center gap-2">
                            <span className="font-medium">{product.name}</span>
                            {product.status === 'pending' && (
                                <Badge variant="secondary" className="bg-orange-100 text-orange-800 hover:bg-orange-100">
                                    <Clock className="mr-1 h-3 w-3" />
                                    Menunggu Verifikasi
                                </Badge>
                            )}
                            {product.status === 'rejected' && (
                                <Badge variant="secondary" className="bg-red-100 text-red-800 hover:bg-red-100">
                                    <XCircle className="mr-1 h-3 w-3" />
                                    Ditolak
                                </Badge>
                            )}
                        </div>
                        <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 isChecked = product.status === 'active';

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

                if (product.status === 'active' || product.status === 'inactive') {
                    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>
                    );
                }

                if (product.status === 'rejected' && product.rejection_reason) {
                    return (
                        <div className="flex flex-col gap-1">
                            <span className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ${getStatusVariant(product.status)}`}>
                                {getStatusLabel(product.status)}
                            </span>
                            <span className="text-[0.65rem] text-muted-foreground max-w-[200px] truncate block" title={product.rejection_reason}>
                                Alasan: {product.rejection_reason}
                            </span>
                        </div>
                    );
                }

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

    // Actions column
    columns.push({
        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;

            // Pending + verifier: Setujui / Tolak
            if (product.status === 'pending' && isVerifier) {
                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Setujui',
                                icon: <CheckCircle className="h-4 w-4 text-green-600" />,
                                onClick: () => router.post(approveUrl(product.id), {}, { preserveScroll: true }),
                            },
                            {
                                label: 'Tolak',
                                icon: <XCircle className="h-4 w-4 text-destructive" />,
                                onClick: () => handleReject(product),
                            },
                        ]}
                    />
                );
            }

            // Pending + non-verifier: no actions
            if (product.status === 'pending') {
                return null;
            }

            // Rejected + verifier: no actions
            if (product.status === 'rejected' && isVerifier) {
                return null;
            }

            // Rejected + non-verifier: Ajukan Ulang / Edit / Hapus
            if (product.status === 'rejected') {
                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Ajukan Ulang',
                                icon: <RotateCw className="h-4 w-4 text-blue-600" />,
                                onClick: () => router.post(resubmitUrl(product.id), {}, { preserveScroll: true }),
                            },
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show: can('products.update'),
                                onClick: () => handleEdit(product),
                            },
                            {
                                label: 'Hapus',
                                icon: <Trash2 className="h-4 w-4 text-destructive" />,
                                show: can('products.delete'),
                                onClick: () => handleDeleteClick(product),
                            },
                        ]}
                    />
                );
            }

            // Active/Inactive/Draft: Edit / Hapus
            if (can('products.update') || can('products.delete')) {
                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show: can('products.update'),
                                onClick: () => handleEdit(product),
                            },
                            {
                                label: 'Hapus',
                                icon: <Trash2 className="h-4 w-4 text-destructive" />,
                                show: can('products.delete'),
                                onClick: () => handleDeleteClick(product),
                            },
                        ]}
                    />
                );
            }

            return null;
        },
    });

    return columns;
}
