import { Fragment, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { useDispatch } from 'react-redux';
import { Tab } from '@headlessui/react';
import dynamic from 'next/dynamic';
import { setPageTitle } from '../../store/themeConfigSlice';
import Link from 'next/link';
import { logActivity } from '@/utils/activityLogger';
import Dropdown from '../../components/Dropdown';
import { coloredToast } from '@/lib/toast';
const AllProduct = dynamic(() => import('@/components/Products/AllProduct'), { ssr: false });
const Published = dynamic(() => import('@/components/Products/Published'), { ssr: false });
const Draft = dynamic(() => import('@/components/Products/Draft'), { ssr: false });
const Archived = dynamic(() => import('@/components/Products/Archived'), { ssr: false });
const ProductIndex = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Products'));
    }, []);

    const savedTab = typeof window !== 'undefined' ? localStorage.getItem('productTab') : null;

    const [value, setValue] = useState('list');
    const [isMounted, setIsMounted] = useState(false);
    const [selectedIndex, setSelectedIndex] = useState(savedTab ? parseInt(savedTab, 10) : 0);
    const [isLoading, setIsLoading] = useState(false);
    const [isLoadingVariant, setIsLoadingVariant] = useState(false);
    const [isImporting, setIsImporting] = useState(false);
    const [isApplyingImport, setIsApplyingImport] = useState(false);
    const [importPreview, setImportPreview] = useState<any | null>(null);
    const [showImportPreview, setShowImportPreview] = useState(false);
    const [conflictStrategy, setConflictStrategy] = useState<'' | 'rename' | 'merge' | 'swap'>('');
    const [previewDetailChange, setPreviewDetailChange] = useState<any | null>(null);
    const [importProgress, setImportProgress] = useState<{
        visible: boolean;
        label: string;
        current: number;
        total: number;
    }>({ visible: false, label: '', current: 0, total: 0 });
    const [status, setStatus] = useState('');
    const [productRefreshKey, setProductRefreshKey] = useState(0);
    const importFileRef = useRef<HTMLInputElement>(null);
    const isBulkProcessing = isImporting || isApplyingImport;
    useEffect(() => {
        setIsMounted(true);
    }, []);

    useEffect(() => {
        localStorage.setItem('productTab', selectedIndex.toString());
    }, [selectedIndex]);

    async function handleDownloadExcel(data: any, sheetName: string, fileName: string, headers?: string[]) {
        const XLSX = await import('xlsx');
        const workbook = XLSX.utils.book_new();
        const worksheet = headers?.length
            ? XLSX.utils.json_to_sheet(data, { header: headers })
            : XLSX.utils.json_to_sheet(data);

        const textColumns = new Set(['product_id', 'variant_id']);
        const headerRow = headers?.length ? headers : data[0] ? Object.keys(data[0]) : [];
        const textColumnIndexes = headerRow
            .map((name, idx) => (textColumns.has(name) ? idx : -1))
            .filter((idx) => idx >= 0);

        if (worksheet['!ref'] && textColumnIndexes.length > 0) {
            const range = XLSX.utils.decode_range(worksheet['!ref']);
            for (let r = range.s.r + 1; r <= range.e.r; r += 1) {
                textColumnIndexes.forEach((c) => {
                    const addr = XLSX.utils.encode_cell({ r, c });
                    const cell = worksheet[addr];
                    if (!cell || cell.v == null || cell.v === '') return;
                    cell.t = 's';
                    cell.v = String(cell.v);
                    cell.z = '@';
                });
            }
        }

        XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);

        XLSX.writeFile(workbook, fileName + '.xlsx', { compression: true });
    }

    const fetchAllProducts = async (status: string) => {
        const api_url = process.env.API_URL;
        let allData: any[] = [];
        let page = 1;
        let hasMoreData = true;

        while (hasMoreData) {
            const statusQuery = status ? `&product_status=${encodeURIComponent(status)}` : '';
            const response = await fetch(`${api_url}api/products/list?page=${page}&per_page=100${statusQuery}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });

            const { data, currentPage, totalPages } = await response.json();
            allData = [...allData, ...(data || [])];

            if (currentPage < totalPages) {
                page++;
            } else {
                hasMoreData = false;
            }
        }
        return allData;
    };

    const getAttributeValue = (attr: any): string => {
        if (!attr || attr.value == null || attr.value === '') return '';
        if (typeof attr.value === 'object') {
            return String(attr.value.label ?? attr.value.value ?? '');
        }
        return String(attr.value);
    };

    const normalizeAttributeName = (name: unknown): string => {
        return String(name || '')
            .trim()
            .replace(/\s+/g, ' ');
    };

    const joinCategories = (categories: any): string => {
        if (!Array.isArray(categories)) return '';
        return categories
            .map((cat) => {
                if (cat == null) return '';
                if (typeof cat === 'string') return cat;
                return String(cat.label ?? cat.name ?? cat.value ?? cat.slug ?? '');
            })
            .filter(Boolean)
            .join(', ');
    };

    const joinImages = (images: any): string => {
        if (!Array.isArray(images)) return '';
        return images.filter(Boolean).join(' | ');
    };

    /** Semua status: GET /api/products/list tanpa product_status, 1 baris = 1 variant + kolom attr:* dinamis */
    const fetchAllProductsWithAllAttributes = async () => {
        const products = await fetchAllProducts('');
        const attributeNames = new Set<string>();

        products.forEach((product) => {
            (product.product_items || []).forEach((variant: any) => {
                (variant.attributes || []).forEach((attr: any) => {
                    const name = normalizeAttributeName(attr?.name);
                    if (name) attributeNames.add(name);
                });
            });
        });

        const sortedAttrNames = Array.from(attributeNames).sort((a, b) => a.localeCompare(b));
        const attrHeaders = sortedAttrNames.map((name) => `attr:${name}`);
        const baseHeaders = [
            'no',
            'product_id',
            'variant_id',
            'parent_sku',
            'sku_variation',
            'product_title',
            'product_status',
            'product_reg_price',
            'product_sale_price',
            'product_qty',
            'variant_reg_price',
            'variant_sale_price',
            'variant_qty',
            'variant_gold_weight',
            'product_categories',
            'product_images',
        ];
        const headers = [...baseHeaders, ...attrHeaders];

        const emptyAttrs = Object.fromEntries(attrHeaders.map((h) => [h, '']));
        const rows: Record<string, any>[] = [];
        let no = 1;

        products.forEach((product) => {
            const productId = String(product.id || product._id || '');
            const variants = Array.isArray(product.product_items) ? product.product_items : [];

            const parentFields = {
                product_id: productId,
                parent_sku: product.product_sku ?? '',
                product_title: product.product_title ?? '',
                product_status: product.product_status ?? '',
                product_reg_price: product.product_reg_price ?? product.product_reg_price_display ?? '',
                product_sale_price: product.product_sale_price ?? product.product_sale_price_display ?? '',
                product_qty: product.product_qty ?? 0,
                product_images: joinImages(product.product_images),
                product_categories: joinCategories(product.product_categories),
            };

            if (variants.length === 0) {
                const row: Record<string, any> = {
                    ...Object.fromEntries(headers.map((h) => [h, ''])),
                    ...parentFields,
                    ...emptyAttrs,
                    no: no++,
                    variant_id: '',
                    sku_variation: '',
                    variant_reg_price: '',
                    variant_sale_price: '',
                    variant_qty: '',
                    variant_gold_weight: '',
                };
                rows.push(row);
                return;
            }

            variants.forEach((variant: any) => {
                const attrColumns = { ...emptyAttrs };
                (variant.attributes || []).forEach((attr: any) => {
                    const name = normalizeAttributeName(attr?.name);
                    if (!name) return;
                    attrColumns[`attr:${name}`] = getAttributeValue(attr);
                });

                const row: Record<string, any> = {
                    ...Object.fromEntries(headers.map((h) => [h, ''])),
                    ...parentFields,
                    no: no++,
                    variant_id: variant.id != null && variant.id !== '' ? String(variant.id) : '',
                    sku_variation: variant.sku_variation ?? '',
                    variant_reg_price: variant.reg_price ?? '',
                    variant_sale_price: variant.sale_price ?? '',
                    variant_qty: variant.qty == null || variant.qty === '' ? '' : variant.qty,
                    variant_gold_weight:
                        variant.gold_weight == null || variant.gold_weight === '' ? '' : variant.gold_weight,
                    ...attrColumns,
                };
                rows.push(row);
            });
        });

        return { rows, headers };
    };

    const formatFBCatalogPrice = (price: number) => {
        if (price === 0) {
            return '';
        }
        return price.toLocaleString('id-ID', { minimumFractionDigits: 0 }) + ' IDR';
    };

    const FAQ_CANCEL_NOTICE =
        'Pesanan yang sudah diproses TIDAK BISA dicancel. Harap membaca semua FAQ sebelum membeli.';

    const handleDownload = async () => {
        setIsLoading(true);
        try {
            const allData = await fetchAllProducts(status);
            if (allData.length > 0) {
                let no = 1;
                const newProductDownload = allData.map((item) => {
                    const calculatedQty =
                        item.product_qty > 0
                            ? item.product_qty
                            : item.product_items
                                ? item.product_items.reduce((sum: number, i: any) => sum + (i.qty || 0), 0)
                                : 0;
                    let availability = 'out of stock';
                    if (item.product_status === 'publish' && calculatedQty > 0) {
                        availability = 'in stock';
                    }
                    const prodDescription = String(item.product_sort_description || '')
                        .replaceAll(FAQ_CANCEL_NOTICE, '')
                        .replace(/\s+/g, ' ')
                        .trim();
                    return {
                        no: no++,
                        SKU: item.product_sku,
                        productName: item.product_title,
                        description: prodDescription,
                        availability: availability,
                        condition: 'new',
                        price: formatFBCatalogPrice(item.product_reg_price_display),
                        link: 'https://theaurumlab.com/product/' + item.product_url,
                        image_link: item.product_images?.[0],
                        brand: 'Aurum Lab',
                        google_product_category: 'Apparel & Accessories > Jewelry',
                        fb_product_category: '',
                        quantity_to_sell: '',
                        sale_price: formatFBCatalogPrice(item.product_sale_price_display),
                        quantity: calculatedQty,
                        product_status: item.product_status,
                    };
                });

                handleDownloadExcel(newProductDownload, `${status || 'all'}`, `Product ${status || 'all'}`);
                await logActivity({
                    location: 'Products',
                    description: `Download Product data ${status || 'all'}`,
                });
            }
        } finally {
            setIsLoading(false);
        }
    };

    const handleDownloadVariant = async () => {
        setIsLoadingVariant(true);
        try {
            const { rows, headers } = await fetchAllProductsWithAllAttributes();
            if (rows.length > 0) {
                handleDownloadExcel(rows, 'All Attributes', 'Product all status with All Attributes', headers);
                await logActivity({
                    location: 'Products',
                    description: 'Download Product data all status with All Attributes',
                });
            }
        } finally {
            setIsLoadingVariant(false);
        }
    };

    const flattenPreviewRows = (preview: any) => {
        const lines: Array<{ sku: string; target: string; field: string; from: string; to: string; isConflict?: boolean }> = [];
        for (const change of preview?.changes || []) {
            if (change.sku_rename) {
                lines.push({
                    sku: change.product_sku,
                    target: 'parent',
                    field: change.sku_conflict ? 'product_sku (CONFLICT)' : 'product_sku',
                    from: String(change.sku_rename.from ?? ''),
                    to: String(change.sku_rename.to ?? ''),
                    isConflict: Boolean(change.sku_conflict),
                });
            }
            for (const [field, diff] of Object.entries(change.parent_updates || {})) {
                const d: any = diff;
                lines.push({
                    sku: change.product_sku,
                    target: 'parent',
                    field,
                    from: Array.isArray(d.from) ? d.from.join(', ') : String(d.from ?? ''),
                    to: Array.isArray(d.to) ? d.to.join(', ') : String(d.to ?? ''),
                });
            }
            for (const variant of change.variant_updates || []) {
                const target =
                    variant.match_variant_id != null && variant.match_variant_id !== ''
                        ? `id:${variant.match_variant_id}${variant.match_sku_variation || variant.sku_variation
                            ? ` (${variant.match_sku_variation || variant.sku_variation})`
                            : ''
                        }`
                        : variant.match_sku_variation || variant.sku_variation;
                for (const [field, diff] of Object.entries(variant.fields || {})) {
                    const d: any = diff;
                    lines.push({
                        sku: change.product_sku,
                        target,
                        field,
                        from: String(d.from ?? ''),
                        to: String(d.to ?? ''),
                    });
                }
                for (const [field, diff] of Object.entries(variant.attributes || {})) {
                    const d: any = diff;
                    lines.push({
                        sku: change.product_sku,
                        target,
                        field: `attr:${field}`,
                        from: String(d.from ?? ''),
                        to: String(d.to ?? ''),
                    });
                }
            }
        }
        return lines;
    };

    const getChangeDetailLines = (change: any) => {
        if (!change) return [];
        return flattenPreviewRows({ changes: [change] });
    };

    const getChangeFieldCount = (change: any) => getChangeDetailLines(change).length;

    const updateImportProgress = (label: string, current: number, total: number) => {
        setImportProgress({ visible: true, label, current, total });
    };

    const closeImportProgress = () => {
        setImportProgress({ visible: false, label: '', current: 0, total: 0 });
    };

    const chunkRowsByProductId = (rows: any[], chunkSize = 40) => {
        const byId = new Map<string, any[]>();
        for (const row of rows) {
            const id = String(row?.product_id || row?._id || '').trim();
            if (!id) continue;
            if (!byId.has(id)) byId.set(id, []);
            byId.get(id)!.push(row);
        }

        const keys = [...byId.keys()];
        const chunks: any[][] = [];
        for (let i = 0; i < keys.length; i += chunkSize) {
            const slice = keys.slice(i, i + chunkSize);
            const chunkRows: any[] = [];
            slice.forEach((id) => chunkRows.push(...(byId.get(id) || [])));
            chunks.push(chunkRows);
        }
        return { chunks, productCount: keys.length };
    };

    const handleImportFile = async (event: ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        event.target.value = '';
        if (!file) return;

        setIsImporting(true);
        updateImportProgress('Membaca file Excel', 0, 4);
        try {
            coloredToast('success', `File dipilih: ${file.name}`);
            const XLSX = await import('xlsx');
            updateImportProgress('Parse Excel', 1, 4);
            const buffer = await file.arrayBuffer();
            const workbook = XLSX.read(buffer, { type: 'array' });
            const sheetName = workbook.SheetNames[0];
            const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' });

            if (!rows.length) {
                coloredToast('warning', 'File Excel kosong');
                return;
            }

            const api_url = process.env.API_URL;
            if (!api_url) {
                throw new Error('API_URL belum dikonfigurasi di dashboard');
            }

            const { chunks, productCount } = chunkRowsByProductId(rows, 40);
            if (!chunks.length) {
                throw new Error('Tidak ada product_id valid di Excel. Download ulang file Attributes terbaru.');
            }

            const merged = {
                changes: [] as any[],
                skipped: [] as any[],
                errors: [] as any[],
                conflicts: [] as any[],
                requires_conflict_strategy: false,
                summary: {
                    rows: rows.length,
                    productsGrouped: productCount,
                    productsWithChanges: 0,
                    skipped: 0,
                    errors: 0,
                    conflicts: 0,
                    warnings: 0,
                },
            };

            updateImportProgress('Preview ke server', 0, chunks.length);
            for (let i = 0; i < chunks.length; i += 1) {
                const response = await fetch(`${api_url}api/products/bulk-update-from-export/preview`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({ rows: chunks[i] }),
                });

                let data: any = null;
                try {
                    data = await response.json();
                } catch (_) {
                    throw new Error(`Preview gagal (HTTP ${response.status}) — response bukan JSON`);
                }

                if (!response.ok) {
                    throw new Error(data?.message || `Gagal preview import (HTTP ${response.status})`);
                }

                merged.changes.push(...(data.changes || []));
                merged.skipped.push(...(data.skipped || []));
                merged.errors.push(...(data.errors || []));
                merged.conflicts.push(...(data.conflicts || []));
                updateImportProgress('Preview ke server', i + 1, chunks.length);
            }

            merged.requires_conflict_strategy = merged.conflicts.length > 0 || merged.changes.some((c) => c.requires_conflict_strategy);
            merged.summary.productsWithChanges = merged.changes.length;
            merged.summary.skipped = merged.skipped.length;
            merged.summary.errors = merged.errors.length;
            merged.summary.conflicts = merged.conflicts.length;
            merged.summary.warnings = merged.changes.reduce(
                (n: number, c: any) => n + (c.warnings?.length || 0),
                0
            );

            setConflictStrategy('');
            setImportPreview(merged);
            setShowImportPreview(true);
            await logActivity({
                location: 'Products',
                description: `Preview bulk import attributes: ${merged.summary.productsWithChanges} products with changes`,
            });

            if (!merged.changes.length) {
                coloredToast('warning', 'Tidak ada perubahan terdeteksi');
            } else {
                coloredToast('success', `Preview siap: ${merged.changes.length} produk berubah`);
            }
        } catch (error: any) {
            console.error(error);
            coloredToast('danger', error.message || 'Gagal membaca file');
        } finally {
            setIsImporting(false);
            closeImportProgress();
        }
    };

    const handleApplyImport = async () => {
        if (!importPreview?.changes?.length) return;

        if (importPreview.requires_conflict_strategy && !conflictStrategy) {
            coloredToast('warning', 'Pilih strategy konflik SKU dulu (rename / merge / swap)');
            return;
        }

        setIsApplyingImport(true);
        try {
            const api_url = process.env.API_URL;
            const batchSize = 15;
            const changes = importPreview.changes;
            const totalBatches = Math.ceil(changes.length / batchSize) || 1;
            let updatedCount = 0;
            let failedCount = 0;

            updateImportProgress('Apply update', 0, totalBatches);
            for (let i = 0; i < changes.length; i += batchSize) {
                const batch = changes.slice(i, i + batchSize);
                const response = await fetch(`${api_url}api/products/bulk-update-from-export`, {
                    method: 'PATCH',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({
                        changes: batch,
                        conflict_strategy: importPreview.requires_conflict_strategy ? conflictStrategy : null,
                    }),
                });
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.message || 'Gagal apply bulk update');
                }
                updatedCount += data.summary?.updated || 0;
                failedCount += data.summary?.failed || 0;
                updateImportProgress('Apply update', Math.floor(i / batchSize) + 1, totalBatches);
            }

            await logActivity({
                location: 'Products',
                description: `Bulk import attributes applied: updated ${updatedCount}, failed ${failedCount}, strategy ${conflictStrategy || 'none'}`,
            });

            coloredToast(
                failedCount > 0 ? 'warning' : 'success',
                `Update selesai. Sukses: ${updatedCount}, Gagal: ${failedCount}`
            );
            setShowImportPreview(false);
            setImportPreview(null);
            setConflictStrategy('');
            setProductRefreshKey((key) => key + 1);
        } catch (error: any) {
            console.error(error);
            coloredToast('danger', error.message || 'Gagal menerapkan update');
        } finally {
            setIsApplyingImport(false);
            closeImportProgress();
        }
    };

    return (
        <>
            {isMounted && (
                <div>
                    <div className="flex flex-wrap items-center justify-between gap-4">
                        <div className="mb-2 flex items-center gap-2">
                            <Link href="/products/add" className="btn btn-outline-primary gap-2">
                                <svg className="h-5 w-5" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round">
                                    <line x1="12" y1="5" x2="12" y2="19"></line>
                                    <line x1="5" y1="12" x2="19" y2="12"></line>
                                </svg>
                                Add New Product
                            </Link>
                        </div>
                        <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                            <div className="flex gap-3">
                                <div>
                                    <button type="button" className={`btn btn-outline-primary p-2 ${value === 'list' && 'bg-primary text-white'}`} onClick={() => setValue('list')}>
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5">
                                            <path d="M2 5.5L3.21429 7L7.5 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                            <path opacity="0.5" d="M2 12.5L3.21429 14L7.5 10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                            <path d="M2 19.5L3.21429 21L7.5 17" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                            <path d="M22 19L12 19" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                            <path opacity="0.5" d="M22 12L12 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                            <path d="M22 5L12 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                        </svg>
                                    </button>
                                </div>
                                <div>
                                    <button type="button" className={`btn btn-outline-primary p-2 ${value === 'grid' && 'bg-primary text-white'}`} onClick={() => setValue('grid')}>
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5">
                                            <path
                                                opacity="0.5"
                                                d="M2.5 6.5C2.5 4.61438 2.5 3.67157 3.08579Y 3.08579C3.67157 2.5 4.61438 2.5 6.5 2.5C8.38562 2.5 9.32843 2.5 9.91421 3.08579C10.5 3.67157 10.5 4.61438 10.5 6.5C10.5 8.38562 10.5 9.32843 9.91421 9.91421C9.32843 10.5 8.38562 10.5 6.5 10.5C4.61438 10.5 3.67157 10.5 3.08579 9.91421C2.5 9.32843 2.5 8.38562 2.5 6.5Z"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                            <path
                                                opacity="0.5"
                                                d="M13.5 17.5C13.5 15.6144 13.5 14.6716 14.0858 14.0858C14.6716 13.5 15.6144 13.5 17.5 13.5C19.3856 13.5 20.3284 13.5 20.9142 14.0858C21.5 14.6716 21.5 15.6144 21.5 17.5C21.5 19.3856 21.5 20.3284 20.9142 20.9142C20.3284 21.5 19.3856 21.5 17.5 21.5C15.6144 21.5 14.6716 21.5 14.0858 20.9142C13.5 20.3284 13.5 19.3856 13.5 17.5Z"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                            <path
                                                d="M2.5 17.5C2.5 15.6144 2.5 14.6716 3.08579 14.0858C3.67157 13.5 4.61438 13.5 6.5 13.5C8.38562 13.5 9.32843 13.5 9.91421 14.0858C10.5 14.6716 10.5 15.6144 10.5 17.5C10.5 19.3856 10.5 20.3284 9.91421 20.9142C9.32843 21.5 8.38562 21.5 6.5 21.5C4.61438 21.5 3.67157 21.5 3.08579 20.9142C2.5 20.3284 2.5 19.3856 2.5 17.5Z"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                            <path
                                                d="M13.5 6.5C13.5 4.61438 13.5 3.67157 14.0858 3.08579C14.6716 2.5 15.6144 2.5 17.5 2.5C19.3856 2.5 20.3284 2.5 20.9142 3.08579C21.5 3.67157 21.5 4.61438 21.5 6.5C21.5 8.38562 21.5 9.32843 20.9142 9.91421C20.3284 10.5 19.3856 10.5 17.5 10.5C15.6144 10.5 14.6716 10.5 14.0858 9.91421C13.5 9.32843 13.5 8.38562 13.5 6.5Z"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <Tab.Group selectedIndex={selectedIndex} onChange={setSelectedIndex}>
                        <div className="flex flex-wrap items-center justify-between gap-4">
                            <div className="mb-2 flex items-center gap-2">
                                <Tab.List className="mt-3 flex flex-wrap">
                                    {[
                                        { label: 'All', icon: null },
                                        {
                                            label: 'Published',
                                            icon: (
                                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path
                                                        d="M14.381 9.02721C14.9767 8.81911 15.6178 8.70588 16.2857 8.70588C16.9404 8.70588 17.5693 8.81468 18.1551 9.01498M7.11616 11.6089C6.8475 11.5567 6.56983 11.5294 6.28571 11.5294C3.91878 11.5294 2 13.4256 2 15.7647C2 18.1038 3.91878 20 6.28571 20H16.2857C19.4416 20 22 17.4717 22 14.3529C22 11.8811 20.393 9.78024 18.1551 9.01498M7.11616 11.6089C6.88706 10.9978 6.7619 10.3369 6.7619 9.64706C6.7619 6.52827 9.32028 4 12.4762 4C15.4159 4 17.8371 6.19371 18.1551 9.01498M7.11616 11.6089C7.68059 11.7184 8.20528 11.9374 8.66667 12.2426"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        strokeLinecap="round"
                                                    />
                                                </svg>
                                            ),
                                        },
                                        {
                                            label: 'Draft',
                                            icon: (
                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" width="18" height="18">
                                                    <path
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                        d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m8.25 3v6.75m0 0l-3-3m3 3l3-3M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"
                                                    />
                                                </svg>
                                            ),
                                        },
                                        {
                                            label: 'Archived',
                                            icon: (
                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" width="18" height="18">
                                                    <path
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                        d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5m6 4.125l2.25 2.25m0 0l2.25 2.25M12 13.875l2.25-2.25M12 13.875l-2.25 2.25M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z"
                                                    />
                                                </svg>
                                            ),
                                        },
                                    ].map((tab, index) => (
                                        <Tab as={Fragment} key={index}>
                                            {({ selected }) => (
                                                <button
                                                    className={`${selected ? '!border-primary text-primary !outline-none dark:!bg-[#191e3a]' : ''
                                                        }  flex items-center border-t-2 border-transparent bg-[#f6f7f8] p-7 py-3 before:inline-block hover:border-primary hover:text-primary dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                                >
                                                    {tab.icon}
                                                    <span className="ms-2">{tab.label}</span>
                                                </button>
                                            )}
                                        </Tab>
                                    ))}
                                </Tab.List>
                            </div>

                            {/* <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                                <button className="btn btn-sm btn-outline-success flex items-center justify-center" onClick={handleDownload} disabled={isLoading}>
                                    {isLoading ? (
                                        <>
                                            <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                            <span className="ml-2">Downloading..</span>
                                        </>
                                    ) : (
                                        'Download Product'
                                    )}
                                </button>
                                <button className="btn btn-sm btn-outline-success flex items-center justify-center" onClick={handleDownloadVariant} disabled={isLoadingVariant}>
                                    {isLoadingVariant ? (
                                        <>
                                            <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                            <span className="ml-2">Downloading..</span>
                                        </>
                                    ) : (
                                        'Download Product with All Attributes'
                                    )}
                                </button>
                            </div> */}
                            <Dropdown
                                button={
                                    <span className="bg-white btn btn-sm btn-outline-success flex w-full items-center justify-center">
                                        {isLoading || isBulkProcessing ? (
                                            <>
                                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                <span className="ml-2">{isBulkProcessing ? 'Processing..' : 'Downloading..'}</span>
                                            </>
                                        ) : (
                                            <span className="flex items-center">
                                                <svg xmlns="http://www.w3.org/2000/svg" className="mr-2" width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M19.9201 8.9502L13.4001 15.4702C12.6301 16.2402 11.3701 16.2402 10.6001 15.4702L4.08008 8.9502" stroke="currentColor" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                                                Product
                                            </span>
                                        )}
                                    </span>
                                }
                                btnClassName={`!p-0 w-[280px] ${isLoading || isBulkProcessing ? 'pointer-events-none opacity-60' : ''}`}
                            >
                                <div
                                    className="w-[280px] max-h-[220px] bg-white shadow-md flex flex-col gap-2 px-3 py-2"
                                    onClick={(e) => e.stopPropagation()}
                                >
                                    <button
                                        type="button"
                                        className="bg-white btn btn-sm btn-outline-success flex items-center justify-start"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            handleDownload();
                                        }}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? (
                                            <>
                                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                <span className="ml-2">Downloading..</span>
                                            </>
                                        ) : (
                                            'Download Product for FB Catalog'
                                        )}
                                    </button>
                                    <button
                                        type="button"
                                        className="bg-white btn btn-sm btn-outline-success flex items-center justify-start"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            handleDownloadVariant();
                                        }}
                                        disabled={isLoadingVariant}
                                    >
                                        {isLoadingVariant ? (
                                            <>
                                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                <span className="ml-2">Downloading..</span>
                                            </>
                                        ) : (
                                            'Download Product with All Attributes'
                                        )}
                                    </button>
                                    <button
                                        type="button"
                                        className="bg-white btn btn-sm btn-outline-primary flex items-center justify-start"
                                        onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            importFileRef.current?.click();
                                        }}
                                        disabled={isImporting || isApplyingImport}
                                    >
                                        {isImporting ? (
                                            <>
                                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                <span className="ml-2">Importing..</span>
                                            </>
                                        ) : (
                                            'Import Attributes Excel'
                                        )}
                                    </button>
                                </div>
                            </Dropdown>
                            <input
                                ref={importFileRef}
                                type="file"
                                accept=".xls,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                                className="hidden"
                                onChange={handleImportFile}
                            />
                        </div>
                        {isBulkProcessing && (
                            <div className="mt-3 flex items-center gap-2 rounded-md border border-primary/20 bg-primary/5 px-3 py-2 text-sm text-primary">
                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                <span>
                                    {isImporting
                                        ? 'Memproses preview import Excel...'
                                        : 'Menerapkan perubahan import, mohon tunggu...'}
                                </span>
                            </div>
                        )}
                        <Tab.Panels>
                            <Tab.Panel>
                                <div className="pt-5">
                                    {selectedIndex === 0 && (
                                        <AllProduct view={value} status={setStatus} refreshKey={productRefreshKey} />
                                    )}
                                </div>
                            </Tab.Panel>
                            <Tab.Panel>
                                <div className="pt-5">
                                    {selectedIndex === 1 && (
                                        <Published view={value} status={setStatus} refreshKey={productRefreshKey} />
                                    )}
                                </div>
                            </Tab.Panel>
                            <Tab.Panel>
                                <div className="pt-5">
                                    {selectedIndex === 2 && (
                                        <Draft view={value} status={setStatus} refreshKey={productRefreshKey} />
                                    )}
                                </div>
                            </Tab.Panel>
                            <Tab.Panel>
                                <div className="pt-5">
                                    {selectedIndex === 3 && (
                                        <Archived view={value} status={setStatus} refreshKey={productRefreshKey} />
                                    )}
                                </div>
                            </Tab.Panel>
                        </Tab.Panels>
                    </Tab.Group>

                    {importProgress.visible && (
                        <div className="fixed inset-0 z-[70] flex items-center justify-center bg-black/50 p-4">
                            <div className="w-full max-w-md rounded-md bg-white p-5 shadow-xl dark:bg-[#0e1726]">
                                <div className="mb-2 flex items-center justify-between text-sm">
                                    <span className="font-semibold">{importProgress.label}</span>
                                    <span>
                                        {importProgress.current}/{importProgress.total || 1}
                                    </span>
                                </div>
                                <div className="h-3 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700">
                                    <div
                                        className="h-full rounded-full bg-primary transition-all duration-300"
                                        style={{
                                            width: `${Math.min(
                                                100,
                                                Math.round(
                                                    (importProgress.current / Math.max(importProgress.total, 1)) * 100
                                                )
                                            )}%`,
                                        }}
                                    />
                                </div>
                                <p className="mt-3 text-xs text-gray-500">Jangan tutup halaman sampai proses selesai.</p>
                            </div>
                        </div>
                    )}

                    {showImportPreview && importPreview && (
                        <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4">
                            <div className="h-full w-2/3 overflow-hidden rounded-md bg-white shadow-xl dark:bg-[#0e1726]">
                                <div className="flex items-center justify-between border-b px-4 py-3">
                                    <div>
                                        <h5 className="text-lg font-semibold">Preview Bulk Import</h5>
                                        <p className="text-xs text-gray-500">
                                            Berubah: {importPreview.summary?.productsWithChanges || 0} produk · Skip:{' '}
                                            {importPreview.summary?.skipped || 0} · Error: {importPreview.summary?.errors || 0} · Conflict:{' '}
                                            {importPreview.summary?.conflicts || 0} · Warning: {importPreview.summary?.warnings || 0}
                                        </p>
                                        <p className="mt-1 text-xs text-gray-400">
                                            Match via <code className="text-[11px]">product_id</code> +{' '}
                                            <code className="text-[11px]">variant_id</code>. Sync:{' '}
                                            <code className="text-[11px]">parent_sku</code>, harga, qty, gold weight, title, status,
                                            kategori, dan nilai kolom <code className="text-[11px]">attr:*</code>. Jangan
                                            edit <code className="text-[11px]">product_id</code> /{' '}
                                            <code className="text-[11px]">variant_id</code>. Sel kosong = tidak diubah.
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        className="btn btn-sm btn-outline-danger"
                                        onClick={() => {
                                            setShowImportPreview(false);
                                            setImportPreview(null);
                                            setPreviewDetailChange(null);
                                            setConflictStrategy('');
                                        }}
                                        disabled={isApplyingImport}
                                    >
                                        Tutup
                                    </button>
                                </div>

                                <div className="max-h-[60vh] overflow-auto px-4 py-3">
                                    {(importPreview.changes || []).length === 0 ? (
                                        <div className="py-8 text-center text-gray-500">Tidak ada field yang berubah</div>
                                    ) : (
                                        <table className="w-full text-left text-sm">
                                            <thead className="sticky top-0 bg-white dark:bg-[#0e1726]">
                                                <tr className="border-b">
                                                    <th className="py-2 pr-2">SKU lama</th>
                                                    <th className="py-2 pr-2">SKU baru</th>
                                                    <th className="py-2 pr-2">Title</th>
                                                    <th className="py-2 pr-2">Perubahan</th>
                                                    <th className="py-2 pr-2">Status</th>
                                                    <th className="py-2">Aksi</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {(importPreview.changes || []).map((change: any) => {
                                                    const isConflict = Boolean(change.requires_conflict_strategy || change.sku_conflict);
                                                    const fieldCount = getChangeFieldCount(change);
                                                    return (
                                                        <tr
                                                            key={change.product_id}
                                                            className={`border-b ${isConflict
                                                                ? 'bg-red-50 dark:bg-red-900/20'
                                                                : 'border-gray-100'
                                                                }`}
                                                        >
                                                            <td className="py-2 pr-2 align-top font-medium">{change.product_sku || '—'}</td>
                                                            <td className="py-2 pr-2 align-top">
                                                                {change.product_sku_new && change.product_sku_new !== change.product_sku ? (
                                                                    <span className={isConflict ? 'font-semibold text-red-700 dark:text-red-300' : ''}>
                                                                        {change.product_sku_new}
                                                                    </span>
                                                                ) : (
                                                                    <span className="text-gray-400">=</span>
                                                                )}
                                                            </td>
                                                            <td className="py-2 pr-2 align-top">{change.product_title || '—'}</td>
                                                            <td className="py-2 pr-2 align-top">{fieldCount} field</td>
                                                            <td className="py-2 pr-2 align-top">
                                                                {isConflict ? (
                                                                    <span className="badge bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-200">
                                                                        Conflict
                                                                    </span>
                                                                ) : change.sku_rename ? (
                                                                    <span className="badge bg-blue-100 text-blue-700">SKU rename</span>
                                                                ) : (
                                                                    <span className="badge bg-green-100 text-green-700">Update</span>
                                                                )}
                                                            </td>
                                                            <td className="py-2 align-top">
                                                                <button
                                                                    type="button"
                                                                    className="btn btn-xs btn-outline-primary"
                                                                    onClick={() => setPreviewDetailChange(change)}
                                                                    disabled={isApplyingImport}
                                                                >
                                                                    View detail
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </table>
                                    )}



                                    {importPreview.requires_conflict_strategy && (
                                        <div className="mt-4 rounded border border-red-200 bg-red-50 p-3 text-sm dark:border-red-800 dark:bg-red-900/20">
                                            <h6 className="mb-2 font-semibold text-red-800 dark:text-red-200">
                                                Konflik SKU terdeteksi ({importPreview.summary?.conflicts || importPreview.conflicts?.length || 0})
                                            </h6>
                                            <p className="mb-2 text-xs text-red-800 dark:text-red-100">
                                                Wajib pilih strategy sebelum Apply:
                                            </p>
                                            <ul className="mb-3 list-disc pl-5 text-xs text-red-900 dark:text-red-100">
                                                <li>
                                                    <b>rename</b>: aman — menolak baris yang bentrok (SKU baru sudah dipakai)
                                                </li>
                                                <li>
                                                    <b>swap</b>: tukar parent SKU + auto-rewrite sku_variation yang diawali parent (pola PARENT-... / PARENT_...); keduanya tetap publish
                                                </li>
                                                <li>
                                                    <b>merge</b>: gabung variant ke produk pemilik SKU baru; produk sumber tetap publish dengan SKU lama
                                                </li>
                                            </ul>
                                            <div className="flex flex-wrap gap-2">
                                                {(['rename', 'swap', 'merge'] as const).map((strategy) => (
                                                    <button
                                                        key={strategy}
                                                        type="button"
                                                        className={`btn btn-sm ${conflictStrategy === strategy ? 'btn-danger' : 'btn-outline-danger'
                                                            }`}
                                                        onClick={() => setConflictStrategy(strategy)}
                                                        disabled={isApplyingImport}
                                                    >
                                                        {strategy}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="flex items-center justify-end gap-2 border-t px-4 py-3">
                                    <button
                                        type="button"
                                        className="btn btn-sm btn-outline-dark"
                                        disabled={isApplyingImport}
                                        onClick={() => {
                                            setShowImportPreview(false);
                                            setImportPreview(null);
                                            setPreviewDetailChange(null);
                                            setConflictStrategy('');
                                        }}
                                    >
                                        Batal
                                    </button>
                                    <button
                                        type="button"
                                        className="btn btn-sm btn-primary"
                                        disabled={
                                            isApplyingImport ||
                                            !(importPreview.changes || []).length ||
                                            (importPreview.requires_conflict_strategy && !conflictStrategy)
                                        }
                                        onClick={handleApplyImport}
                                    >
                                        {isApplyingImport
                                            ? 'Applying..'
                                            : `Apply ${(importPreview.changes || []).length} produk${conflictStrategy ? ` (${conflictStrategy})` : ''
                                            }`}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}

                    {previewDetailChange && (
                        <div className="fixed inset-0 z-[65] flex items-center justify-center bg-black/50 p-4">
                            <div className="max-h-[85vh] w-full max-w-3xl overflow-hidden rounded-md bg-white shadow-xl dark:bg-[#0e1726]">
                                <div className="flex items-center justify-between border-b px-4 py-3">
                                    <div>
                                        <h5 className="text-lg font-semibold">Detail perubahan</h5>
                                        <p className="text-xs text-gray-500">
                                            {previewDetailChange.product_sku}
                                            {previewDetailChange.product_sku_new &&
                                                previewDetailChange.product_sku_new !== previewDetailChange.product_sku
                                                ? ` → ${previewDetailChange.product_sku_new}`
                                                : ''}
                                            {previewDetailChange.product_title ? ` · ${previewDetailChange.product_title}` : ''}
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        className="btn btn-sm btn-outline-dark"
                                        onClick={() => setPreviewDetailChange(null)}
                                    >
                                        Tutup
                                    </button>
                                </div>
                                <div className="max-h-[65vh] overflow-auto px-4 py-3">
                                    {previewDetailChange.sku_conflict && (
                                        <div className="mb-3 rounded border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-800 dark:bg-red-900/20 dark:text-red-200">
                                            Konflik dengan produk {previewDetailChange.sku_conflict.conflict_product_sku} (
                                            {previewDetailChange.sku_conflict.conflict_product_title ||
                                                previewDetailChange.sku_conflict.conflict_product_id}
                                            )
                                        </div>
                                    )}
                                    <table className="w-full text-left text-sm">
                                        <thead className="sticky top-0 bg-white dark:bg-[#0e1726]">
                                            <tr className="border-b">
                                                <th className="py-2 pr-2">Target</th>
                                                <th className="py-2 pr-2">Field</th>
                                                <th className="py-2 pr-2">From</th>
                                                <th className="py-2">To</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {getChangeDetailLines(previewDetailChange).map((line, idx) => (
                                                <tr
                                                    key={`${line.target}-${line.field}-${idx}`}
                                                    className={`border-b ${line.isConflict ? 'bg-red-50 dark:bg-red-900/20' : 'border-gray-100'
                                                        }`}
                                                >
                                                    <td className="py-1.5 pr-2 align-top">{line.target}</td>
                                                    <td className="py-1.5 pr-2 align-top">{line.field}</td>
                                                    <td className="py-1.5 pr-2 align-top text-red-600">{line.from || '—'}</td>
                                                    <td className="py-1.5 align-top text-green-700">{line.to || '—'}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                    {(previewDetailChange.warnings || []).length > 0 && (
                                        <div className="mt-3">
                                            <h6 className="mb-1 text-sm font-semibold">Warnings</h6>
                                            <ul className="list-disc pl-5 text-xs text-amber-700">
                                                {previewDetailChange.warnings.map((w: string, idx: number) => (
                                                    <li key={idx}>{w}</li>
                                                ))}
                                            </ul>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}
        </>
    );
};

export default ProductIndex;
