// components/StockUpdateModal.tsx
import { useMemo, useState, useEffect } from 'react';
import Modal from '../components/Modal';
import Tabs, { TabItem } from '../components/Tabs';
import Button from '../components/Buttons';
import IconInstagram from '../components/Icon/IconInstagram';
import IconGlobe from '../components/Icon/IconGlobe';
import IconWhatsapp from '../components/Icon/IconWhatsapp';
import { Product } from '../utils/product';

type ChannelKey = 'instagram' | 'web' | 'whatsapp';
type ChannelStock = Record<ChannelKey, number>;

// productId -> channel stock (for single products)
type SingleStockMap = Record<string, ChannelStock>;
// productId -> variantId -> channel stock (for variable products)
type VariantStockMap = Record<string, Record<string, ChannelStock>>;

type Props = {
    open: boolean;
    onClose: () => void;
    products: Product[]; // selectedRecords passed in
    onSubmit: (payload: { singles: SingleStockMap; variants: VariantStockMap }) => void;
};

const CHANNELS: { key: ChannelKey; label: string; icon: React.ReactNode; wrap: string; readonly?: boolean }[] = [
    { key: 'instagram', label: 'Instagram', icon: <IconInstagram />, wrap: 'bg-pink-100 text-pink-600' },
    { key: 'web', label: 'Website', icon: <IconGlobe />, wrap: 'bg-blue-100 text-blue-600', readonly: true },
    { key: 'whatsapp', label: 'WhatsApp', icon: <IconWhatsapp />, wrap: 'bg-emerald-100 text-emerald-600' },
];

function clsxLike(...classes: (string | false | undefined)[]) {
    return classes.filter(Boolean).join(' ');
}

const StockUpdateModal = ({ open, onClose, products, onSubmit }: Props) => {
    const singleProducts = useMemo(
        () => products.filter((p: any) => (p.variant ?? 'single') === 'single'),
        [products]
    );
    const variableProducts = useMemo(
        () => products.filter((p: any) => p.variant === 'variable'),
        [products]
    );

    const [activeProductId, setActiveProductId] = useState<string | null>(null);
    const [singleStock, setSingleStock] = useState<SingleStockMap>({});
    const [variantStock, setVariantStock] = useState<VariantStockMap>({});

    useEffect(() => {
        if (open) {
            setActiveProductId(products[0]?.id ?? null);
            
            const sMap: SingleStockMap = {};
            const vMap: VariantStockMap = {};
            
            products.forEach((p: any) => {
                if ((p.variant ?? 'single') === 'single') {
                    sMap[p.id] = {
                        instagram: p.stock?.instagram ?? 0,
                        web: p.stock?.web ?? 0,
                        whatsapp: p.stock?.whatsapp ?? 0,
                    };
                }
                
                if (p.variant === 'variable' && Array.isArray(p.variants)) {
                    vMap[p.id] = {};
                    p.variants.forEach((v: any) => {
                        vMap[p.id][v.id] = {
                            instagram: v.stock?.instagram ?? 0,
                            web: v.stock?.web ?? 0,
                            whatsapp: v.stock?.whatsapp ?? 0,
                        };
                    });
                }
            });
            
            setSingleStock(sMap);
            setVariantStock(vMap);
        }
    }, [open, products]);

    const activeProduct = products.find((p) => p.id === activeProductId) as any;
    const isVariable = activeProduct?.variant === 'variable';

    const handleSingleChange = (productId: string, channel: ChannelKey, value: string) => {
        const num = Math.max(0, Number(value) || 0);
        setSingleStock((prev) => ({
            ...prev,
            [productId]: {
                ...prev[productId],
                [channel]: num,
            },
        }));
    };

    const handleVariantChange = (
        productId: string,
        variantId: string,
        channel: ChannelKey,
        value: string
    ) => {
        const num = Math.max(0, Number(value) || 0);
        setVariantStock((prev) => ({
            ...prev,
            [productId]: {
                ...prev[productId],
                [variantId]: {
                    ...prev[productId]?.[variantId],
                    [channel]: num,
                },
            },
        }));
    };

    const [bulkInput, setBulkInput] = useState<ChannelStock>({ instagram: 0, web: 0, whatsapp: 0 });

    const handleBulkChange = (channel: ChannelKey, value: string) => {
        const num = Math.max(0, Number(value) || 0);
        
        // Update bulk input state for the UI
        const newBulkInput = { ...bulkInput, [channel]: num };
        setBulkInput(newBulkInput);

        // Apply to all single products
        setSingleStock(prev => {
            const next = { ...prev };
            singleProducts.forEach(p => {
                next[p.id] = { ...next[p.id], [channel]: num };
            });
            return next;
        });

        // Apply to all variant products
        setVariantStock(prev => {
            const next = { ...prev };
            variableProducts.forEach(p => {
                const pVars = { ...(next[p.id] || {}) };
                (p.variants || []).forEach(v => {
                    pVars[v.id] = { ...pVars[v.id], [channel]: num };
                });
                next[p.id] = pVars;
            });
            return next;
        });
    };

    const handleApplyToAllVariants = () => {
        if (!activeProduct || !activeProduct.variants || activeProduct.variants.length <= 1) return;
        const firstVariantId = activeProduct.variants[0].id;
        const currentVals = variantStock[activeProduct.id]?.[firstVariantId] ?? { instagram: 0, web: 0, whatsapp: 0 };

        setVariantStock((prev) => {
            const productVars = { ...(prev[activeProduct.id] || {}) };
            activeProduct.variants.forEach((v: any) => {
                productVars[v.id] = { ...currentVals };
            });
            return {
                ...prev,
                [activeProduct.id]: productVars
            };
        });
    };

    const ProductList = ({ list }: { list: Product[] }) => (
        <div className="max-h-[420px] overflow-y-auto -mx-1 px-1 space-y-1">
            {list.length === 0 && (
                <p className="text-sm text-slate-400 px-2 py-4">No products in this group.</p>
            )}
            {list.map((p: any) => {
                const isActive = p.id === activeProductId;
                
                // Calculate live stock from local state
                let liveStock = 0;
                if (p.variant === 'variable') {
                    const vStocks = variantStock[p.id] || {};
                    liveStock = Object.values(vStocks).reduce(
                        (sum: number, ch: any) => sum + (ch.instagram || 0) + (ch.web || 0) + (ch.whatsapp || 0), 
                        0
                    );
                } else {
                    const sStock = singleStock[p.id] || { instagram: 0, web: 0, whatsapp: 0 };
                    liveStock = (sStock.instagram || 0) + (sStock.web || 0) + (sStock.whatsapp || 0);
                }

                return (
                    <button
                        key={p.id}
                        onClick={() => setActiveProductId(p.id)}
                        className={clsxLike(
                            'w-full flex items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors',
                            isActive
                                ? 'bg-amber-50 border border-amber-300'
                                : 'border border-transparent hover:bg-slate-50'
                        )}
                    >
                        <img
                            src={p.image}
                            className="h-9 w-9 rounded-lg object-cover flex-shrink-0"
                        />
                        <div className="min-w-0 flex-1">
                            <div className="text-sm font-medium text-slate-800 truncate">
                                {p.name}{' '}
                                <span className="text-amber-600 font-semibold">
                                    ({liveStock})
                                </span>
                            </div>
                            <div className="text-xs text-slate-400 truncate">{p.sku}</div>
                        </div>
                        {p.variant === 'variable' && (
                            <span className="flex-shrink-0 text-[10px] font-semibold text-amber-600 bg-amber-50 rounded-full px-2 py-0.5">
                                {p.variants?.length ?? 0} variants
                            </span>
                        )}
                    </button>
                );
            })}
        </div>
    );

    const tabItems: TabItem[] = [];
    
    if (singleProducts.length > 0) {
        tabItems.push({ label: 'Single Product', content: <ProductList list={singleProducts} /> });
    }
    if (variableProducts.length > 0) {
        tabItems.push({ label: 'Variable Product', content: <ProductList list={variableProducts} /> });
    }

    // total across whatever is currently editable for the active product
    const totalStock = useMemo(() => {
        if (!activeProduct) return 0;
        if (isVariable) {
            const perVariant = variantStock[activeProduct.id] ?? {};
            return Object.values(perVariant).reduce(
                (sum, ch) => sum + ch.instagram + ch.web + ch.whatsapp,
                0
            );
        }
        const ch = singleStock[activeProduct.id];
        return ch ? ch.instagram + ch.web + ch.whatsapp : 0;
    }, [activeProduct, isVariable, singleStock, variantStock]);

    const [isSaving, setIsSaving] = useState(false);

    const handleSubmit = async () => {
        setIsSaving(true);
        try {
            await onSubmit({ singles: singleStock, variants: variantStock });
            onClose();
        } finally {
            setIsSaving(false);
        }
    };

    const ChannelRow = ({
        value,
        onChange,
    }: {
        value: ChannelStock;
        onChange: (channel: ChannelKey, val: string) => void;
    }) => (
        <div className="space-y-2">
            {CHANNELS.map((ch) => (
                <div
                    key={ch.key}
                    className="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white px-2.5 py-2 hover:border-slate-300 transition-colors"
                >
                    <div className="flex items-center gap-2 min-w-0">
                        <span
                            className={`flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full ${ch.wrap}`}
                        >
                            {ch.icon}
                        </span>
                        <span className="text-xs font-medium text-slate-700 truncate">
                            {ch.label}
                        </span>
                    </div>
                    <input
                        type="number"
                        min={0}
                        disabled={ch.readonly}
                        value={value[ch.key]}
                        onChange={(e) => onChange(ch.key, e.target.value)}
                        className={clsxLike(
                            "w-16 flex-shrink-0 rounded-md border px-2 py-1 text-right text-xs font-medium focus:outline-none focus:ring-2",
                            ch.readonly 
                                ? "bg-slate-50 text-slate-400 border-slate-200 cursor-not-allowed opacity-70" 
                                : "text-slate-800 border-slate-200 focus:ring-amber-400/40 focus:border-amber-400"
                        )}
                    />
                </div>
            ))}
        </div>
    );

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Stock Update"
            width="4xl"
            footer={
                <>
                    <Button type='button' size="sm" variant="secondary" onClick={onClose} disabled={isSaving}>
                        Cancel
                    </Button>
                    <Button type='button' size="sm" variant="primary" styleType="filled" onClick={handleSubmit} isLoading={isSaving}>
                        Stock Update
                    </Button>
                </>
            }
        >
            <div className="flex gap-5 min-h-[420px]">
                <div className="w-[50%] border-r pr-4">
                    <Tabs items={tabItems} variant="line" />
                </div>

                <div className="w-[50%] space-y-3 max-h-[460px] overflow-y-auto pr-1">
                    {products.length > 1 ? (
                        <>
                            <div className="mb-2">
                                <h2 className="text-sm font-semibold text-slate-800">Bulk Stock Update</h2>
                                <p className="text-xs text-slate-500 mt-1">
                                    Values entered here will be instantly applied to all {products.length} selected products (including all variants).
                                </p>
                            </div>
                            <ChannelRow
                                value={bulkInput}
                                onChange={(channel, val) => handleBulkChange(channel, val)}
                            />
                            <div className="flex items-center justify-between rounded-xl border border-amber-200 bg-amber-50 px-3 py-3 mt-1">
                                <span className="text-sm font-medium text-amber-900">Total stock per item</span>
                                <span className="text-xl font-bold text-amber-900">
                                    {bulkInput.instagram + bulkInput.web + bulkInput.whatsapp}
                                </span>
                            </div>
                        </>
                    ) : !activeProduct ? (
                        <div className="flex h-full items-center justify-center text-sm text-slate-400">
                            Select a product to update stock
                        </div>
                    ) : isVariable ? (
                        <>
                            <div className="flex items-center justify-between">
                                <h2 className="text-sm font-semibold text-slate-800">
                                    Update Stock — {activeProduct.variants?.length ?? 0} Variants
                                </h2>
                                {(activeProduct.variants?.length ?? 0) > 1 && (
                                    <button
                                        onClick={handleApplyToAllVariants}
                                        className="text-xs font-semibold text-amber-600 hover:underline"
                                    >
                                        Apply top variant to all
                                    </button>
                                )}
                            </div>
                            {(activeProduct.variants ?? []).map((v: any) => (
                                <div
                                    key={v.id}
                                    className="rounded-xl border border-slate-200 p-3 space-y-2.5"
                                >
                                    <div className="flex items-center gap-2.5">
                                        {(v.image || v.image_url) && (
                                            <img
                                                src={v.image || v.image_url}
                                                className="h-8 w-8 rounded-md object-cover flex-shrink-0"
                                            />
                                        )}
                                        <div className="min-w-0 flex-1">
                                            <div className="text-xs font-semibold text-slate-800 truncate">
                                                {v.color}
                                            </div>
                                            <div className="text-[10px] font-mono text-slate-400 truncate">
                                                {v.sku}
                                            </div>
                                        </div>
                                    </div>

                                    <ChannelRow
                                        value={
                                            variantStock[activeProduct.id]?.[v.id] ?? {
                                                instagram: 0,
                                                web: 0,
                                                whatsapp: 0,
                                            }
                                        }
                                        onChange={(channel, val) =>
                                            handleVariantChange(activeProduct.id, v.id, channel, val)
                                        }
                                    />
                                </div>
                            ))}
                        </>
                    ) : (
                        <>
                            <div className="flex items-center justify-between mb-2">
                                <h2 className="text-sm font-semibold text-slate-800">Update Stock</h2>
                            </div>
                            <ChannelRow
                                value={
                                    singleStock[activeProduct.id] ?? {
                                        instagram: 0,
                                        web: 0,
                                        whatsapp: 0,
                                    }
                                }
                                onChange={(channel, val) =>
                                    handleSingleChange(activeProduct.id, channel, val)
                                }
                            />
                        </>
                    )}

                    {activeProduct && products.length === 1 && (
                        <div className="flex items-center justify-between rounded-xl border border-amber-200 bg-amber-50 px-3 py-3 mt-1">
                            <span className="text-sm font-medium text-amber-900">Total stock</span>
                            <span className="text-xl font-bold text-amber-900">{totalStock}</span>
                        </div>
                    )}
                </div>
            </div>
        </Modal>
    );
};

export default StockUpdateModal;