import React, { useState, useEffect } from 'react';
import { AlertCircle, Package, Search, Save, CheckCircle, Target, TrendingDown, RefreshCw, Check } from 'lucide-react';

const getTenantHeaders = () => ({
  'Content-Type': 'application/json',
  'X-Tenant-Token': localStorage.getItem('tenant_token') || ''
});

function StockTab({ products, updateProducts, API_BASE, showToast }: {
  products: any[];
  updateProducts: (p: any[]) => void;
  API_BASE: string;
  showToast: (m: string, t?: 'success' | 'error') => void;
}) {
  // variantEdits: { [productId]: { [size]: stock } }
  const [variantEdits, setVariantEdits] = React.useState<Record<string, Record<string, number>>>({});
  const [thresholdEdits, setThresholdEdits] = React.useState<Record<string, number>>({});
  const [saving, setSaving] = React.useState<string | null>(null);
  const [search, setSearch] = React.useState('');

  // Helper: parse variant_stock whether it's a string or object
  const parseVariantStock = (vs: any): Record<string, number> | null => {
    if (!vs) return null;
    if (typeof vs === 'string') {
      try { return JSON.parse(vs); } catch { return null; }
    }
    if (typeof vs === 'object' && !Array.isArray(vs)) return vs as Record<string, number>;
    return null;
  };

  // Build initial variant stock from product
  const getVariantEdit = (p: any): Record<string, number> => {
    if (variantEdits[p.id]) return variantEdits[p.id];
    // Use variant_stock if available (handle both string and object)
    const parsed = parseVariantStock(p.variant_stock);
    if (parsed && Object.keys(parsed).length > 0) {
      return { ...parsed };
    }
    // Fallback: distribute total stock evenly across sizes
    const sizes: string[] = p.sizes ?? [];
    if (sizes.length > 0) {
      const perSize = Math.floor((p.stock ?? 0) / sizes.length);
      const result: Record<string, number> = {};
      sizes.forEach(s => { result[s] = perSize; });
      return result;
    }
    // No sizes — just show total
    return { 'Total': p.stock ?? 0 };
  };

  const getThresholdEdit = (p: any): number =>
    thresholdEdits[p.id] ?? (p.lowStockThreshold ?? p.low_stock_threshold ?? 20);

  const setVariantQty = (productId: string, size: string, qty: number, p: any) => {
    const current = getVariantEdit(p);
    setVariantEdits(prev => ({
      ...prev,
      [productId]: { ...current, [size]: Math.max(0, qty) }
    }));
  };

  const isDirty = (p: any): boolean => {
    if (variantEdits[p.id] !== undefined) return true;
    const origThreshold = p.lowStockThreshold ?? p.low_stock_threshold ?? 20;
    return (thresholdEdits[p.id] ?? origThreshold) !== origThreshold;
  };


  const handleSave = async (p: any) => {
    const variantStock = getVariantEdit(p);
    const threshold = getThresholdEdit(p);
    const totalStock = Object.values(variantStock).reduce((a, b) => a + b, 0);
    setSaving(p.id);
    try {
      const res = await fetch(`/api/admin/products/${p.id}`, {
        method: 'PUT',
        headers: getTenantHeaders(),
        body: JSON.stringify({
          id: p.id,
          variant_stock: variantStock,
          stock: totalStock,
          low_stock_threshold: threshold
        })
      });
      const data = await res.json();
      if (!data.success) throw new Error(data.error || 'Failed');
      updateProducts(products.map(prod =>
        prod.id === p.id
          ? { ...prod, variant_stock: variantStock, stock: totalStock, lowStockThreshold: threshold, low_stock_threshold: threshold }
          : prod
      ));
      // Clear dirty state
      setVariantEdits(prev => { const n = { ...prev }; delete n[p.id]; return n; });
      setThresholdEdits(prev => { const n = { ...prev }; delete n[p.id]; return n; });
      showToast(`✅ Stock updated for ${p.name}`, 'success');
    } catch (e: any) {
      showToast('Error: ' + e.message, 'error');
    } finally {
      setSaving(null);
    }
  };

  const [refreshing, setRefreshing] = React.useState(false);

  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      localStorage.removeItem('shophyfast_cache_products');
      const res = await fetch('/api/products', { headers: getTenantHeaders() });
      const data = await res.json();
      if (data.success && data.data) {
        // Parse variant_stock for each product
        const parsed = data.data.map((p: any) => {
          if (p.variant_stock && typeof p.variant_stock === 'string') {
            try { p.variant_stock = JSON.parse(p.variant_stock); } catch { }
          }
          return p;
        });
        updateProducts(parsed);
        showToast('✅ Stock data refreshed from DB', 'success');
      }
    } catch {
      showToast('Refresh failed', 'error');
    } finally {
      setRefreshing(false);
    }
  };

  const getVariantStatus = (qty: number, threshold: number) => {
    if (qty === 0) return { label: 'শেষ', bg: 'bg-red-100', text: 'text-red-700', bar: 'bg-red-500', dot: 'bg-red-500' };
    if (qty < threshold) return { label: 'কম', bg: 'bg-amber-100', text: 'text-amber-700', bar: 'bg-amber-500', dot: 'bg-amber-400' };
    return { label: 'আছে', bg: 'bg-green-100', text: 'text-green-700', bar: 'bg-green-500', dot: 'bg-green-500' };
  };

  const filtered = products.filter(p =>
    p.name?.toLowerCase().includes(search.toLowerCase())
  );

  // Low stock: any variant below threshold
  const lowStockProducts = products.filter(p => {
    const vs = p.variant_stock;
    const threshold = p.lowStockThreshold ?? p.low_stock_threshold ?? 20;
    if (vs && typeof vs === 'object') {
      return Object.values(vs).some((qty: any) => Number(qty) < threshold);
    }
    return (p.stock ?? 0) < threshold;
  });

  return (
    <div className="animate-fade-in-up space-y-8">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4 bg-white dark:bg-slate-900 p-8 rounded-[32px] border shadow-sm">
        <div>
          <h2 className="text-3xl font-black flex items-center gap-3">
            <Package className="text-red-600" size={32} /> Variant Stock Management
          </h2>
          <p className="text-slate-500 dark:text-slate-400 font-medium mt-1">
            {products.length} products · {lowStockProducts.length} low stock alerts · প্রতিটি size এর আলাদা stock
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={handleRefresh}
            disabled={refreshing}
            className="flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-2xl text-sm font-black transition-all disabled:opacity-50"
          >
            <RefreshCw size={15} className={refreshing ? 'animate-spin' : ''} />
            {refreshing ? 'Loading...' : 'DB থেকে Refresh'}
          </button>
          <input
            type="text"
            placeholder="Search products..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="border border-slate-200 rounded-2xl px-4 py-3 text-sm font-bold outline-none focus:ring-2 focus:ring-red-400 w-56"
          />
        </div>
      </div>


      {/* Low-stock alert banner */}
      {lowStockProducts.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-[24px] p-5 flex items-start gap-4">
          <AlertCircle className="text-red-600 shrink-0 mt-0.5" size={22} />
          <div>
            <p className="font-black text-red-700 text-sm">
              ⚠️ {lowStockProducts.length}টি product এর কোনো variant এ stock কম!
            </p>
            <p className="text-red-500 text-xs mt-1 font-bangla">
              {lowStockProducts.map(p => getBanglaName(p.nameBangla, p.name)).join(' · ')}
            </p>
          </div>
        </div>
      )}

      {/* Product cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
        {filtered.map(p => {
          const variantStock = getVariantEdit(p);
          const threshold = getThresholdEdit(p);
          const totalStock = Object.values(variantStock).reduce((a, b) => a + b, 0);
          const dirty = isDirty(p);
          const sizes = Object.keys(variantStock);

          return (
            <div key={p.id} className={`bg-white dark:bg-slate-900 rounded-[28px] border shadow-sm p-6 flex flex-col gap-5 ${dirty ? 'border-red-300 ring-2 ring-red-100' : ''}`}>
              {/* Product header */}
              <div className="flex items-center gap-3">
                {p.image
                  ? <img src={p.image} className="w-14 h-14 rounded-2xl object-cover bg-slate-100 shrink-0" />
                  : <div className="w-14 h-14 rounded-2xl bg-slate-100 flex items-center justify-center shrink-0"><Package size={22} className="text-slate-500 dark:text-slate-400" /></div>
                }
                <div className="min-w-0 flex-1">
                  <p className="font-black text-slate-800 text-sm truncate font-bangla">{getBanglaName(p.nameBangla, p.name)}</p>
                  <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase tracking-wide">{p.name}</p>
                  <p className="text-xs font-black text-slate-600 mt-0.5">
                    Total: <span className="text-red-600">{totalStock}</span> pcs
                  </p>
                </div>
              </div>

              {/* Per-variant stock rows */}
              <div className="space-y-2.5">
                <p className="text-[10px] font-black uppercase text-slate-500 dark:text-slate-400 tracking-wider">Size-wise Stock</p>
                {sizes.map(size => {
                  const qty = variantStock[size] ?? 0;
                  const status = getVariantStatus(qty, threshold);
                  const pct = threshold > 0 ? Math.min((qty / (threshold * 2)) * 100, 100) : 100;
                  return (
                    <div key={size} className="bg-slate-50 dark:bg-slate-800 rounded-2xl p-3">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                          <div className={`w-2 h-2 rounded-full ${status.dot}`} />
                          <span className="text-xs font-black text-slate-700 dark:text-slate-200">{size}</span>
                          <span className={`text-[9px] font-black px-1.5 py-0.5 rounded-full ${status.bg} ${status.text}`}>
                            {status.label}
                          </span>
                        </div>
                        <input
                          type="number"
                          min={0}
                          value={qty}
                          onChange={e => setVariantQty(p.id, size, parseInt(e.target.value) || 0, p)}
                          className="w-20 border border-slate-200 rounded-xl px-2 py-1 text-xs font-black text-slate-800 focus:ring-2 focus:ring-red-400 outline-none text-right bg-white"
                        />
                      </div>
                      <div className="w-full bg-slate-200 rounded-full h-1.5">
                        <div className={`h-1.5 rounded-full transition-all ${status.bar}`} style={{ width: `${pct}%` }} />
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Alert threshold */}
              <div className="flex items-center gap-3">
                <label className="text-[10px] font-black text-slate-500 dark:text-slate-400 uppercase whitespace-nowrap">Alert Below</label>
                <input
                  type="number" min={1}
                  value={threshold}
                  onChange={e => setThresholdEdits(prev => ({ ...prev, [p.id]: Math.max(1, parseInt(e.target.value) || 20) }))}
                  className="flex-1 border border-slate-200 rounded-xl px-3 py-1.5 text-xs font-black text-slate-800 focus:ring-2 focus:ring-red-600 outline-none"
                />
                <span className="text-[10px] text-slate-500 dark:text-slate-400">pcs</span>
              </div>

              {/* Save button */}
              <button
                disabled={saving === p.id || !dirty}
                onClick={() => handleSave(p)}
                className={`w-full py-2.5 rounded-xl text-sm font-black transition-all flex items-center justify-center gap-2 ${dirty
                  ? 'bg-red-600 text-white hover:bg-red-700 shadow-lg shadow-red-600/20 active:scale-95'
                  : 'bg-slate-100 text-slate-500 dark:text-slate-400 cursor-default'
                  }`}
              >
                {saving === p.id
                  ? <><RefreshCw size={14} className="animate-spin" /> Saving...</>
                  : dirty ? <><Check size={14} /> Save Changes</> : <><CheckCircle size={14} /> Saved</>
                }
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Helper: detect corrupted Bangla (????) and use English name as fallback
// Bangla Unicode range: U+0980–U+09FF
const getBanglaName = (nameBangla?: string, nameEn?: string): string => {
  const bn = nameBangla || '';
  const isBanglaOk = /[\u0980-\u09FF]/.test(bn);
  return isBanglaOk ? bn : (nameEn || bn || 'No Name');
};

const VARIATION_OPTIONS = {
  weight: ["৫০ গ্রাম", "১০০ গ্রাম", "২৫০ গ্রাম", "৫০০ গ্রাম", "১ কেজি", "২ কেজি", "৫ কেজি"],
  pieces: ["1 Pc", "2 Pcs", "3 Pcs", "1 Set"],
  clothing: ["S", "M", "L", "XL", "XXL", "Free Size"]
};
const NavItem = ({ active, onClick, icon, label, count, disabled = false }: any) => (
  <button
    onClick={onClick}
    disabled={disabled}
    style={active ? {
      background: 'linear-gradient(135deg, rgba(139,92,246,0.25), rgba(99,102,241,0.15))',
      borderLeft: '2.5px solid #a78bfa',
      boxShadow: '0 0 20px rgba(139,92,246,0.12)'
    } : {}}
    className={`w-full flex items-center justify-between px-4 py-2.5 rounded-xl transition-all duration-200 text-sm group border border-transparent ${disabled
      ? 'opacity-20 cursor-not-allowed'
      : active
        ? 'text-slate-800 dark:text-white'
        : 'text-slate-500 dark:text-slate-400 hover:text-white hover:bg-white/5 hover:border-white/8'
      }`}
  >
    <div className="flex items-center gap-3">
      <span
        className="w-7 h-7 rounded-lg flex items-center justify-center transition-all"
        style={active ? {
          background: 'linear-gradient(135deg, #8b5cf6, #6366f1)',
          boxShadow: '0 0 12px rgba(139,92,246,0.4)',
          color: '#fff'
        } : {}}
      >
        <span className={active ? '' : 'text-slate-500 group-hover:text-violet-400 transition-colors'}>
          {icon}
        </span>
      </span>
      <span className={`text-[13px] tracking-tight ${active ? 'font-bold text-slate-800 dark:text-white' : 'font-medium'}`}>{label}</span>
    </div>
    {count !== undefined && count > 0 && !disabled && (
      <span
        className="px-2 py-0.5 rounded-full text-[9px] font-black"
        style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', color: '#fff', boxShadow: '0 2px 8px rgba(124,58,237,0.4)' }}
      >
        {count}
      </span>
    )}
  </button>
);


export default StockTab;
