import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { Product, ProductVariant, ProductCategory, UnitType } from '../types';
import { X, Plus, Trash2, Barcode, Package, AlertTriangle, Layers, Check, Camera, AlertCircle } from 'lucide-react';
import { SearchableSelect } from './SearchableSelect';
import { CameraBarcodeScannerModal } from './CameraBarcodeScannerModal';
import { requiredRule, minValueRule, validateForm, isInvalid } from '../rules';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  productToEdit?: Product | null;
}

export const ProductFormModal: React.FC<Props> = ({ isOpen, onClose, productToEdit }) => {
  const { db, addProduct, updateProduct, checkDuplicateBarcode } = useStore();

  const [name, setName] = useState('');
  const [category, setCategory] = useState<ProductCategory>('Minuman & Air Mineral');
  const [description, setDescription] = useState('');
  const [variants, setVariants] = useState<Omit<ProductVariant, 'id'>[]>([]);
  const [errors, setErrors] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [activeScanningIndex, setActiveScanningIndex] = useState<number | null>(null);

  const masterCategories = (db.categories || []).map(c => c.name);
  const masterUnits = (db.units || []).map(u => u.name);
  const masterSizes = (db.sizes || []).map(s => s.name);

  useEffect(() => {
    if (productToEdit) {
      setName(productToEdit.name);
      setCategory(productToEdit.category);
      setDescription(productToEdit.description || '');
      setVariants(productToEdit.variants.map(v => ({
        variantName: v.variantName,
        size: v.size,
        unit: v.unit,
        barcode: v.barcode,
        buyPrice: v.buyPrice,
        sellPrice: v.sellPrice,
        wholesalePrice: v.wholesalePrice || Math.round(v.sellPrice * 0.95),
        stock: v.stock,
        minStock: v.minStock,
        tierPrices: v.tierPrices
      })));
    } else {
      setName('');
      setCategory(masterCategories[0] || 'Minuman & Air Mineral');
      setDescription('');
      // Default initial variant
      setVariants([
        {
          variantName: 'Sedang (300 ML)',
          size: '300',
          unit: 'ML',
          barcode: '',
          buyPrice: 3000,
          sellPrice: 3500,
          wholesalePrice: 3200,
          stock: 24,
          minStock: 10
        }
      ]);
    }
    setErrors(null);
  }, [productToEdit, isOpen]);

  const handleAddVariantRow = () => {
    setVariants(prev => [
      ...prev,
      {
        variantName: 'Besar (500 ML)',
        size: '500',
        unit: masterUnits.includes('ML') ? 'ML' : (masterUnits[0] || 'Pcs'),
        barcode: '',
        buyPrice: 4000,
        sellPrice: 5000,
        stock: 30,
        minStock: 10
      }
    ]);
  };

  const handleRemoveVariantRow = (index: number) => {
    if (variants.length <= 1) {
      Swal.fire({
        icon: 'warning',
        title: 'Tidak Bisa Dihapus',
        text: 'Setidaknya barang harus memiliki 1 varian!',
        confirmButtonColor: '#059669'
      });
      return;
    }
    const varName = variants[index]?.variantName || 'varian ini';
    Swal.fire({
      title: 'Hapus Varian?',
      text: `Apakah Anda yakin ingin menghapus ${varName}?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#e11d48',
      cancelButtonColor: '#64748b',
      confirmButtonText: 'Ya, Hapus',
      cancelButtonText: 'Batal'
    }).then((res) => {
      if (res.isConfirmed) {
        setVariants(prev => prev.filter((_, i) => i !== index));
      }
    });
  };

  const handleVariantChange = (index: number, field: keyof Omit<ProductVariant, 'id'>, value: any) => {
    setVariants(prev => prev.map((v, i) => {
      if (i === index) {
        return { ...v, [field]: value };
      }
      return v;
    }));
  };

  const handleAddTierPrice = (variantIndex: number) => {
    setVariants(prev => prev.map((v, i) => {
      if (i === variantIndex) {
        const currentTiers = v.tierPrices || [];
        const nextMinQty = currentTiers.length > 0 
          ? Math.max(...currentTiers.map(t => t.minQty)) + 1 
          : 2;
        return {
          ...v,
          tierPrices: [
            ...currentTiers,
            { minQty: nextMinQty, price: v.sellPrice * nextMinQty, priceType: 'package', label: '' }
          ]
        };
      }
      return v;
    }));
  };

  const handleRemoveTierPrice = (variantIndex: number, tierIndex: number) => {
    setVariants(prev => prev.map((v, i) => {
      if (i === variantIndex && v.tierPrices) {
        return {
          ...v,
          tierPrices: v.tierPrices.filter((_, tIdx) => tIdx !== tierIndex)
        };
      }
      return v;
    }));
  };

  const handleTierPriceChange = (variantIndex: number, tierIndex: number, field: string, value: any) => {
    setVariants(prev => prev.map((v, i) => {
      if (i === variantIndex && v.tierPrices) {
        const updatedTiers = v.tierPrices.map((tier, tIdx) => {
          if (tIdx === tierIndex) {
            return { ...tier, [field]: value };
          }
          return tier;
        });
        return { ...v, tierPrices: updatedTiers };
      }
      return v;
    }));
  };

  const generateAutoBarcode = (existingBarcodesInForm: Set<string>): string => {
    let code = '';
    let isUnique = false;
    let attempts = 0;
    while (!isUnique && attempts < 100) {
      attempts++;
      const randomNum = Math.floor(10000000 + Math.random() * 90000000);
      code = `888${randomNum}`;
      const isFormDup = existingBarcodesInForm.has(code);
      const isStoreDup = checkDuplicateBarcode(code).isDuplicate;
      if (!isFormDup && !isStoreDup) {
        isUnique = true;
      }
    }
    return code;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrors(null);

    const validationRulesMap: Record<string, any[]> = {
      name: [requiredRule('Nama barang wajib diisi!')]
    };

    const formDataToValidate: Record<string, any> = {
      name
    };

    variants.forEach((v, index) => {
      formDataToValidate[`variantName_${index}`] = v.variantName;
      formDataToValidate[`sellPrice_${index}`] = v.sellPrice;
      validationRulesMap[`variantName_${index}`] = [requiredRule(`Nama varian ke-${index + 1} wajib diisi!`)];
      validationRulesMap[`sellPrice_${index}`] = [requiredRule(`Harga jual varian ke-${index + 1} wajib diisi!`), minValueRule(1, 'Harga jual harus lebih besar dari 0!')];
    });

    const { isValid, errors: formErrs } = validateForm(formDataToValidate, validationRulesMap);

    if (!isValid) {
      setFieldErrors(formErrs as Record<string, string>);
      setErrors('Harap perbaiki kolom yang tidak valid di bawah ini!');
      return;
    }

    if (variants.length === 0) {
      setErrors('Tambahkan minimal 1 varian barang (ukuran/satuan/harga)!');
      return;
    }

    setFieldErrors({});

    // 1. Prepare clean variants list
    const updatedVariantsList = [...variants];

    // Check for duplicate barcodes within current form entries
    const formBarcodes = new Set<string>();
    for (let i = 0; i < updatedVariantsList.length; i++) {
      const v = updatedVariantsList[i];
      const cleanBc = v.barcode ? v.barcode.trim() : '';
      updatedVariantsList[i].barcode = cleanBc;

      if (cleanBc) {
        if (formBarcodes.has(cleanBc)) {
          const msg = `Terdeteksi kode Barcode / SKU ganda "${cleanBc}" pada form ini! Barcode setiap varian harus unik.`;
          setErrors(msg);
          Swal.fire({ icon: 'error', title: 'Barcode Ganda', text: msg, confirmButtonColor: '#059669' });
          return;
        }
        formBarcodes.add(cleanBc);

        // 2. Check for duplicate barcode against database
        const existingProductVariantIds = productToEdit ? productToEdit.variants.map(pvar => pvar.id) : [];
        const excludeId = existingProductVariantIds[i] || 'new_id_check';
        
        const checkResult = checkDuplicateBarcode(cleanBc, excludeId);
        if (checkResult.isDuplicate && checkResult.matchedProduct && checkResult.matchedVariant) {
          // If it belongs to another product OR another variant not in current edit
          if (checkResult.matchedProduct.id !== productToEdit?.id) {
            const msg = `Barcode "${cleanBc}" sudah terdaftar pada barang "${checkResult.matchedProduct.name} - ${checkResult.matchedVariant.variantName}". Barcode / SKU harus unik dan tidak boleh sama!`;
            setErrors(msg);
            Swal.fire({ icon: 'error', title: 'Barcode Sudah Ada', text: msg, confirmButtonColor: '#059669' });
            return;
          }
        }
      }
    }

    if (productToEdit) {
      updateProduct(productToEdit.id, {
        name,
        category,
        description,
        variants: updatedVariantsList.map((v, i) => ({
          ...v,
          id: productToEdit.variants[i]?.id || `var-${Date.now()}-${i}`
        }))
      });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil Diperbarui!',
        text: `Data barang "${name}" berhasil diubah.`,
        timer: 1800,
        showConfirmButton: false
      });
    } else {
      addProduct({
        name,
        category,
        description,
        variants: updatedVariantsList.map((v, i) => ({
          ...v,
          id: `var-${Date.now()}-${i}`
        }))
      });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil Ditambahkan!',
        text: `Barang "${name}" berhasil disimpan ke katalog.`,
        timer: 1800,
        showConfirmButton: false
      });
    }

    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl border border-slate-100 my-auto max-h-[95vh] flex flex-col overflow-hidden">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-700 text-white px-4 sm:px-6 py-3.5 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2.5">
            <div className="p-1.5 sm:p-2 bg-white/20 rounded-lg">
              <Package className="w-5 h-5 sm:w-6 sm:h-6 text-white" />
            </div>
            <div>
              <h3 className="font-bold text-base sm:text-lg leading-tight">
                {productToEdit ? 'Edit Barang Sembako' : 'Tambah Barang Sembako Baru'}
              </h3>
              <p className="text-emerald-100 text-[11px] sm:text-xs">Kelola nama barang, kategori, serta multi-varian ukuran & harga</p>
            </div>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-white/20 text-white transition">
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} noValidate className="p-4 sm:p-6 space-y-4 sm:space-y-6 overflow-y-auto flex-1">
          
          {errors && (
            <div className="p-3 bg-rose-50 border border-rose-200 rounded-xl flex items-center gap-2 text-rose-800 text-xs">
              <AlertTriangle className="w-4 h-4 text-rose-600 shrink-0" />
              <span>{errors}</span>
            </div>
          )}

          {/* Main Info Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">
                Nama Barang <span className="text-rose-500">*</span>
              </label>
              <input
                type="text"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  if (fieldErrors.name) setFieldErrors(prev => ({ ...prev, name: '' }));
                }}
                placeholder="Contoh: Le Minerale / Beras Sania / Minyak Bimoli"
                className={`w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white ${isInvalid(fieldErrors.name)}`}
              />
              {fieldErrors.name && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.name}
                </span>
              )}
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Kategori Sembako</label>
              <SearchableSelect
                options={masterCategories.map(c => ({ value: c, label: c }))}
                value={category}
                onChange={(val) => setCategory(val)}
                placeholder="Pilih Kategori..."
                searchPlaceholder="Cari Kategori Sembako..."
              />
            </div>

            <div className="md:col-span-2">
              <label className="block text-xs font-bold text-slate-700 mb-1">Deskripsi Tambahan (Opsional)</label>
              <input
                type="text"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Keterangan singkat produk..."
                className="w-full px-3.5 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"
              />
            </div>
          </div>

          {/* VARIANTS SECTION */}
          <div className="space-y-3 pt-2">
            <div className="flex items-center justify-between border-b border-slate-200 pb-2">
              <div>
                <h4 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                  <Layers className="w-4 h-4 text-emerald-600" />
                  Daftar Varian & Ukuran Barang ({variants.length})
                </h4>
                <p className="text-xs text-slate-500">
                  Satu barang dapat memiliki banyak varian ukuran (cth: Sedang 300 ML, Besar 500 ML, Kemasan 5 KG) dengan harga berbeda.
                </p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleAddVariantRow}
                  className="px-3 py-1.5 bg-emerald-100 hover:bg-emerald-200 text-emerald-800 text-xs font-bold rounded-xl flex items-center gap-1 transition"
                >
                  <Plus className="w-4 h-4" /> Tambah Varian
                </button>
              </div>
            </div>

            <div className="space-y-4">
              {variants.map((v, index) => (
                <div key={index} className="p-4 bg-slate-50 border border-slate-200 rounded-2xl space-y-3 relative group">
                  
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-extrabold text-slate-700 bg-slate-200 px-2.5 py-0.5 rounded-full">
                      Varian #{index + 1}
                    </span>
                    {variants.length > 1 && (
                      <button
                        type="button"
                        onClick={() => handleRemoveVariantRow(index)}
                        className="text-slate-400 hover:text-rose-600 p-1 transition"
                        title="Hapus Varian Ini"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3">
                    
                    {/* Varian Name */}
                    <div>
                      <label className="block text-[11px] font-semibold text-slate-600 mb-1">Nama Varian / Label</label>
                      <input
                        type="text"
                        value={v.variantName}
                        onChange={(e) => {
                          handleVariantChange(index, 'variantName', e.target.value);
                          if (fieldErrors[`variantName_${index}`]) {
                            setFieldErrors(prev => ({ ...prev, [`variantName_${index}`]: '' }));
                          }
                        }}
                        placeholder="cth: Besar (500 ML)"
                        className={`w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-semibold focus:ring-2 focus:ring-emerald-500 ${isInvalid(fieldErrors[`variantName_${index}`])}`}
                      />
                      {fieldErrors[`variantName_${index}`] && (
                        <span className="invalid-feedback">
                          <AlertCircle className="w-3 h-3" /> {fieldErrors[`variantName_${index}`]}
                        </span>
                      )}
                    </div>

                    {/* Size & Unit */}
                    <div className="grid grid-cols-2 gap-1.5">
                      <div>
                        <label className="block text-[11px] font-semibold text-slate-600 mb-1">Ukuran</label>
                        <SearchableSelect
                          options={masterSizes.map(s => ({ value: s, label: s }))}
                          value={v.size}
                          onChange={(val) => handleVariantChange(index, 'size', val)}
                          placeholder="Ukuran..."
                          searchPlaceholder="Cari ukuran..."
                        />
                      </div>
                      <div>
                        <label className="block text-[11px] font-semibold text-slate-600 mb-1">Satuan</label>
                        <SearchableSelect
                          options={masterUnits.map(u => ({ value: u, label: u }))}
                          value={v.unit}
                          onChange={(val) => handleVariantChange(index, 'unit', val as UnitType)}
                          placeholder="Satuan..."
                          searchPlaceholder="Cari Satuan..."
                        />
                      </div>
                    </div>

                    {/* Barcode */}
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-[11px] font-semibold text-slate-600">Kode Barcode / SKU</label>
                        <div className="flex items-center gap-1">
                          <button
                            type="button"
                            onClick={() => setActiveScanningIndex(index)}
                            className="text-[10px] font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200/80 px-2 py-0.5 rounded-md flex items-center gap-1 transition"
                            title="Scan Barcode Pakai Kamera"
                          >
                            <Camera className="w-3 h-3" /> Scan
                          </button>
                        </div>
                      </div>
                      <div className="relative">
                        <Barcode className="w-3.5 h-3.5 text-slate-400 absolute left-2 top-1/2 -translate-y-1/2" />
                        <input
                          type="text"
                          value={v.barcode}
                          onChange={(e) => handleVariantChange(index, 'barcode', e.target.value)}
                          placeholder="Kode barcode / SKU..."
                          className="w-full pl-7 pr-2 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-mono font-semibold focus:ring-2 focus:ring-emerald-500"
                        />
                      </div>
                    </div>

                    {/* Buy Price */}
                    <div>
                      <label className="block text-[11px] font-semibold text-slate-600 mb-1">Harga Beli (Modal)</label>
                      <input
                        type="number"
                        value={v.buyPrice}
                        onChange={(e) => handleVariantChange(index, 'buyPrice', Number(e.target.value))}
                        placeholder="4000"
                        className="w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-bold text-slate-700 focus:ring-2 focus:ring-emerald-500"
                        min="0"
                      />
                    </div>

                    {/* Sell Price */}
                    <div>
                      <label className="block text-[11px] font-semibold text-emerald-700 mb-1">Harga Jual (Eceran)</label>
                      <input
                        type="number"
                        value={v.sellPrice}
                        onChange={(e) => {
                          handleVariantChange(index, 'sellPrice', Number(e.target.value));
                          if (fieldErrors[`sellPrice_${index}`]) {
                            setFieldErrors(prev => ({ ...prev, [`sellPrice_${index}`]: '' }));
                          }
                        }}
                        placeholder="5000"
                        className={`w-full px-2.5 py-1.5 bg-white border border-emerald-300 rounded-lg text-xs font-bold text-emerald-700 focus:ring-2 focus:ring-emerald-500 ${isInvalid(fieldErrors[`sellPrice_${index}`])}`}
                        min="0"
                      />
                      {fieldErrors[`sellPrice_${index}`] && (
                        <span className="invalid-feedback">
                          <AlertCircle className="w-3 h-3" /> {fieldErrors[`sellPrice_${index}`]}
                        </span>
                      )}
                    </div>

                    {/* Wholesale Price */}
                    <div>
                      <label className="block text-[11px] font-semibold text-indigo-700 mb-1">Harga Grosir / Reseller</label>
                      <input
                        type="number"
                        value={v.wholesalePrice || ''}
                        onChange={(e) => handleVariantChange(index, 'wholesalePrice', Number(e.target.value))}
                        placeholder="4500"
                        className="w-full px-2.5 py-1.5 bg-white border border-indigo-200 rounded-lg text-xs font-bold text-indigo-700 focus:ring-2 focus:ring-indigo-500"
                        min="0"
                      />
                    </div>

                    {/* Stock */}
                    <div>
                      <label className="block text-[11px] font-semibold text-slate-600 mb-1">Stok Saat Ini</label>
                      <input
                        type="number"
                        value={v.stock}
                        onChange={(e) => handleVariantChange(index, 'stock', Number(e.target.value))}
                        placeholder="50"
                        className="w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-bold focus:ring-2 focus:ring-emerald-500"
                        min="0"
                      />
                    </div>

                    {/* Min Stock */}
                    <div>
                      <label className="block text-[11px] font-semibold text-slate-600 mb-1">Batas Minimum Stok</label>
                      <input
                        type="number"
                        value={v.minStock}
                        onChange={(e) => handleVariantChange(index, 'minStock', Number(e.target.value))}
                        placeholder="10"
                        className="w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-bold focus:ring-2 focus:ring-emerald-500"
                        min="0"
                      />
                    </div>

                    {/* TIER PRICING / HARGA BERTINGKAT SECTION */}
                    <div className="sm:col-span-2 md:col-span-3 bg-amber-50/70 border border-amber-200/80 rounded-xl p-3 space-y-3 mt-1">
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="text-xs font-bold text-amber-900 flex items-center gap-1.5">
                            <span>🏷️ Harga Bertingkat / Promo Kelipatan</span>
                            <span className="text-[10px] font-normal text-amber-700 bg-amber-100 px-2 py-0.5 rounded-full">
                              Opsional
                            </span>
                          </div>
                          <p className="text-[10px] text-amber-800/80 leading-tight mt-0.5">
                            Contoh: Beli 1 = Rp 3.000, kalau Beli 2 = Rp 5.000, kalau Beli 3 = Rp 8.000
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={() => handleAddTierPrice(index)}
                          className="px-2.5 py-1 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-[11px] font-bold flex items-center gap-1 transition shadow-2xs"
                        >
                          <Plus className="w-3.5 h-3.5" /> Tambah Level Harga
                        </button>
                      </div>

                      {/* Tier Rules List */}
                      {(!v.tierPrices || v.tierPrices.length === 0) ? (
                        <div className="text-[11px] text-amber-700/70 italic text-center py-1">
                          Belum ada level harga bertingkat untuk varian ini.
                        </div>
                      ) : (
                        <div className="space-y-2 pt-1">
                          {v.tierPrices.map((tier, tIdx) => (
                            <div key={tIdx} className="bg-white border border-amber-200 rounded-lg p-2.5 grid grid-cols-1 sm:grid-cols-12 gap-2 items-center text-xs">
                              {/* Min Qty */}
                              <div className="sm:col-span-3">
                                <label className="block text-[10px] font-bold text-slate-600 mb-0.5">Beli Min. Qty</label>
                                <div className="flex items-center gap-1">
                                  <input
                                    type="number"
                                    min="2"
                                    value={tier.minQty}
                                    onChange={(e) => handleTierPriceChange(index, tIdx, 'minQty', Math.max(1, Number(e.target.value)))}
                                    className="w-full px-2 py-1 bg-slate-50 border border-slate-200 rounded-md text-xs font-extrabold text-slate-800"
                                  />
                                  <span className="text-[11px] font-bold text-slate-500">{v.unit || 'Pcs'}</span>
                                </div>
                              </div>

                              {/* Price Type */}
                              <div className="sm:col-span-3">
                                <label className="block text-[10px] font-bold text-slate-600 mb-0.5">Tipe Harga</label>
                                <select
                                  value={tier.priceType || 'package'}
                                  onChange={(e) => handleTierPriceChange(index, tIdx, 'priceType', e.target.value)}
                                  className="w-full px-2 py-1 bg-slate-50 border border-slate-200 rounded-md text-xs font-semibold text-slate-800"
                                >
                                  <option value="package">Total Paket (Rp)</option>
                                  <option value="unit">Per Unit / Pcs (Rp)</option>
                                </select>
                              </div>

                              {/* Price */}
                              <div className="sm:col-span-4">
                                <label className="block text-[10px] font-bold text-slate-600 mb-0.5">
                                  {tier.priceType === 'unit' ? 'Harga per Unit (Rp)' : `Total Harga Paket ${tier.minQty} ${v.unit} (Rp)`}
                                </label>
                                <input
                                  type="number"
                                  min="0"
                                  value={tier.price}
                                  onChange={(e) => handleTierPriceChange(index, tIdx, 'price', Number(e.target.value))}
                                  placeholder="5000"
                                  className="w-full px-2 py-1 bg-slate-50 border border-amber-300 rounded-md text-xs font-extrabold text-amber-900"
                                />
                              </div>

                              {/* Delete Button */}
                              <div className="sm:col-span-2 flex items-center justify-end pt-3 sm:pt-0">
                                <button
                                  type="button"
                                  onClick={() => handleRemoveTierPrice(index, tIdx)}
                                  className="p-1.5 text-rose-600 hover:bg-rose-50 rounded-md transition"
                                  title="Hapus Level Harga"
                                >
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </div>

                              {/* Summary Banner */}
                              <div className="sm:col-span-12 text-[10px] text-emerald-800 font-semibold bg-emerald-50 px-2 py-1 rounded-md border border-emerald-100 flex items-center justify-between">
                                <span>
                                  💡 Promo: Beli {tier.minQty} {v.unit} = {tier.priceType === 'unit' 
                                    ? `@Rp ${tier.price.toLocaleString('id-ID')} (Total Rp ${(tier.price * tier.minQty).toLocaleString('id-ID')})`
                                    : `Total Rp ${tier.price.toLocaleString('id-ID')} (@Rp ${Math.round(tier.price / (tier.minQty || 1)).toLocaleString('id-ID')}/${v.unit})`
                                  }
                                </span>
                                {v.sellPrice > 0 && (
                                  <span className="text-emerald-700 font-bold">
                                    Hemat Rp {Math.max(0, (v.sellPrice * tier.minQty) - (tier.priceType === 'unit' ? tier.price * tier.minQty : tier.price)).toLocaleString('id-ID')}
                                  </span>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* Margin Info Badge */}
                    <div className="flex items-end pb-1">
                      <div className="text-[11px] bg-emerald-100 text-emerald-800 px-2 py-1 rounded-lg font-bold w-full text-center">
                        Margin: Rp {(v.sellPrice - v.buyPrice).toLocaleString('id-ID')}
                      </div>
                    </div>

                  </div>

                </div>
              ))}
            </div>
          </div>

          {/* Form Actions */}
          <div className="pt-4 border-t border-slate-200 flex items-center justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold text-xs rounded-xl transition"
            >
              Batal
            </button>
            <button
              type="submit"
              className="px-6 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center gap-1.5"
            >
              <Check className="w-4 h-4" /> Simpan Data Barang
            </button>
          </div>

        </form>

      </div>

      {/* Camera Barcode Scanner Modal for Variant SKU */}
      <CameraBarcodeScannerModal
        isOpen={activeScanningIndex !== null}
        onClose={() => setActiveScanningIndex(null)}
        onScanSuccess={(scannedBarcode) => {
          if (activeScanningIndex !== null) {
            handleVariantChange(activeScanningIndex, 'barcode', scannedBarcode);
          }
        }}
        title={`Scan Barcode Varian #${(activeScanningIndex ?? 0) + 1}`}
      />
    </div>
  );
};
