import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { ArrowDownLeft, X, Check, Truck, ShoppingBag, Calendar, AlertTriangle, AlertCircle, Store } from 'lucide-react';
import { SearchableSelect } from './SearchableSelect';
import { requiredRule, minValueRule, validateForm, isInvalid } from '../rules';

interface Props {
  isOpen: boolean;
  onClose: () => void;
}

export const InboundModal: React.FC<Props> = ({ isOpen, onClose }) => {
  const { db, addInboundRecord } = useStore();

  const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
  const [sourceType, setSourceType] = useState<'Supplier' | 'Beli Sendiri'>('Supplier');
  const [supplierName, setSupplierName] = useState('');
  const [invoiceNumber, setInvoiceNumber] = useState('');
  const [selectedProductId, setSelectedProductId] = useState('');
  const [selectedVariantId, setSelectedVariantId] = useState('');
  const [quantity, setQuantity] = useState(10);
  const [buyPrice, setBuyPrice] = useState(0);
  const [shouldUpdateSellPrice, setShouldUpdateSellPrice] = useState(false);
  const [newSellPrice, setNewSellPrice] = useState(0);
  const [newWholesalePrice, setNewWholesalePrice] = useState(0);
  const [notes, setNotes] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  // Preset choices for self-purchase sources
  const selfPurchasePresets = [
    'Agen Beras / Grosir',
    'Pasar Induk Tradisional',
    'Supermarket / Hypermart',
    'Grosir Indogrosir',
    'Warung / Toko Kelontong Lain'
  ];

  // Set default product/variant when opened
  useEffect(() => {
    if (isOpen) {
      if (db.products.length > 0) {
        const firstProd = db.products[0];
        setSelectedProductId(firstProd.id);
        if (firstProd.variants.length > 0) {
          const v = firstProd.variants[0];
          setSelectedVariantId(v.id);
          setBuyPrice(v.buyPrice);
          setNewSellPrice(v.sellPrice);
          setNewWholesalePrice(v.wholesalePrice || Math.round(v.sellPrice * 0.95));
        }
      }
      setSourceType('Supplier');
      if (db.suppliers.length > 0) {
        setSupplierName(db.suppliers[0].name);
      } else {
        setSupplierName('Distributor Mayora Indah');
      }
      setInvoiceNumber(`INV/${new Date().getFullYear()}/${Math.floor(1000 + Math.random() * 9000)}`);
      setDate(new Date().toISOString().slice(0, 10));
      setQuantity(10);
      setShouldUpdateSellPrice(false);
      setNotes('');
      setError(null);
      setFieldErrors({});
    }
  }, [isOpen]);

  const selectedProduct = db.products.find(p => p.id === selectedProductId);
  const selectedVariant = selectedProduct?.variants.find(v => v.id === selectedVariantId);

  const handleSourceTypeChange = (type: 'Supplier' | 'Beli Sendiri') => {
    setSourceType(type);
    setFieldErrors({});
    if (type === 'Supplier') {
      if (db.suppliers.length > 0) {
        setSupplierName(db.suppliers[0].name);
      } else {
        setSupplierName('Distributor Sembako');
      }
      setInvoiceNumber(`INV/${new Date().getFullYear()}/${Math.floor(1000 + Math.random() * 9000)}`);
    } else {
      setSupplierName('Agen Beras / Grosir');
      setInvoiceNumber(''); // Opsional untuk Beli Sendiri
    }
  };

  const handleProductChange = (prodId: string) => {
    setSelectedProductId(prodId);
    const prod = db.products.find(p => p.id === prodId);
    if (prod && prod.variants.length > 0) {
      const v = prod.variants[0];
      setSelectedVariantId(v.id);
      setBuyPrice(v.buyPrice);
      setNewSellPrice(v.sellPrice);
      setNewWholesalePrice(v.wholesalePrice || Math.round(v.sellPrice * 0.95));
    } else {
      setSelectedVariantId('');
      setBuyPrice(0);
      setNewSellPrice(0);
      setNewWholesalePrice(0);
    }
  };

  const handleVariantChange = (varId: string) => {
    setSelectedVariantId(varId);
    if (selectedProduct) {
      const v = selectedProduct.variants.find(varItem => varItem.id === varId);
      if (v) {
        setBuyPrice(v.buyPrice);
        setNewSellPrice(v.sellPrice);
        setNewWholesalePrice(v.wholesalePrice || Math.round(v.sellPrice * 0.95));
      }
    }
  };

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

    const finalInvoiceNumber = invoiceNumber.trim() || (sourceType === 'Beli Sendiri' ? 'Tanpa Struk' : `INV/${new Date().getFullYear()}/${Math.floor(1000 + Math.random() * 9000)}`);

    const { isValid, errors } = validateForm(
      {
        date,
        invoiceNumber: finalInvoiceNumber,
        supplierName,
        selectedProductId,
        selectedVariantId,
        quantity,
        buyPrice
      },
      {
        date: [requiredRule('Tanggal masuk wajib diisi!')],
        ...(sourceType === 'Supplier' ? { invoiceNumber: [requiredRule('Nomor faktur / surat jalan wajib diisi!')] } : {}),
        supplierName: [requiredRule(sourceType === 'Supplier' ? 'Nama supplier / distributor wajib diisi!' : 'Nama agen / tempat beli wajib diisi!')],
        selectedProductId: [requiredRule('Harus memilih barang!')],
        selectedVariantId: [requiredRule('Harus memilih varian barang!')],
        quantity: [requiredRule('Jumlah barang wajib diisi!'), minValueRule(1, 'Jumlah minimal 1!')],
        buyPrice: [requiredRule('Harga beli wajib diisi!'), minValueRule(0, 'Harga beli tidak boleh negatif!')]
      }
    );

    if (!isValid) {
      setFieldErrors(errors as Record<string, string>);
      setError('Harap perbaiki data yang belum lengkap / tidak valid!');
      return;
    }

    if (!selectedProduct || !selectedVariant) {
      const msg = 'Pilih barang dan varian yang valid!';
      setError(msg);
      return;
    }

    setFieldErrors({});

    const totalCost = quantity * buyPrice;

    const priceUpdates = shouldUpdateSellPrice ? {
      sellPrice: newSellPrice,
      wholesalePrice: newWholesalePrice
    } : undefined;

    addInboundRecord({
      date,
      sourceType,
      supplierName,
      invoiceNumber: finalInvoiceNumber,
      productId: selectedProduct.id,
      productName: selectedProduct.name,
      variantId: selectedVariant.id,
      variantName: selectedVariant.variantName,
      quantity,
      unit: selectedVariant.unit,
      buyPrice,
      totalCost,
      notes: (notes ? notes + ' ' : '') + 
        (sourceType === 'Beli Sendiri' ? '[Belanja Mandiri] ' : '') + 
        (shouldUpdateSellPrice ? `[Penyesuaian Harga Jual: Rp ${newSellPrice.toLocaleString('id-ID')}]` : '')
    }, priceUpdates);

    Swal.fire({
      icon: 'success',
      title: 'Barang Masuk Dicatat!',
      text: `Stok ${selectedProduct.name} - ${selectedVariant.variantName} bertambah +${quantity} ${selectedVariant.unit} (${sourceType === 'Beli Sendiri' ? 'Belanja Sendiri' : 'Pengiriman Supplier'}).`,
      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-xl border border-slate-100 my-auto max-h-[95vh] flex flex-col overflow-hidden">
        
        {/* Header */}
        <div className="bg-gradient-to-r from-teal-700 to-emerald-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">
              <ArrowDownLeft 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">Pencatatan Barang Masuk</h3>
              <p className="text-teal-100 text-[11px] sm:text-xs">Catat penerimaan stok dari supplier atau belanja sendiri di agen</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 overflow-y-auto flex-1">
          
          {error && (
            <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>{error}</span>
            </div>
          )}

          {/* Tipe Pengadaan / Sumber Barang */}
          <div>
            <label className="block text-xs font-bold text-slate-700 mb-1.5">Tipe Pengadaan Barang</label>
            <div className="grid grid-cols-2 gap-2 p-1 bg-slate-100 rounded-xl border border-slate-200/80">
              <button
                type="button"
                onClick={() => handleSourceTypeChange('Supplier')}
                className={`py-2 px-3 rounded-lg text-xs font-bold transition flex items-center justify-center gap-2 ${
                  sourceType === 'Supplier'
                    ? 'bg-teal-700 text-white shadow-xs'
                    : 'text-slate-600 hover:text-slate-900 hover:bg-slate-200/60'
                }`}
              >
                <Truck className="w-4 h-4" />
                <span>Supplier / Distributor</span>
              </button>

              <button
                type="button"
                onClick={() => handleSourceTypeChange('Beli Sendiri')}
                className={`py-2 px-3 rounded-lg text-xs font-bold transition flex items-center justify-center gap-2 ${
                  sourceType === 'Beli Sendiri'
                    ? 'bg-amber-600 text-white shadow-xs'
                    : 'text-slate-600 hover:text-slate-900 hover:bg-slate-200/60'
                }`}
              >
                <ShoppingBag className="w-4 h-4" />
                <span>Beli Sendiri (Agen / Pasar)</span>
              </button>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Tanggal Masuk</label>
              <input
                type="date"
                value={date}
                onChange={(e) => {
                  setDate(e.target.value);
                  if (fieldErrors.date) setFieldErrors(prev => ({ ...prev, date: '' }));
                }}
                className={`w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold focus:ring-2 focus:ring-teal-500 ${isInvalid(fieldErrors.date)}`}
              />
              {fieldErrors.date && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.date}
                </span>
              )}
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">
                {sourceType === 'Supplier' ? (
                  'No. Faktur / Surat Jalan'
                ) : (
                  <>
                    No. Struk / Nota <span className="text-slate-400 font-normal">(Opsional)</span>
                  </>
                )}
              </label>
              <input
                type="text"
                value={invoiceNumber}
                onChange={(e) => {
                  setInvoiceNumber(e.target.value);
                  if (fieldErrors.invoiceNumber) setFieldErrors(prev => ({ ...prev, invoiceNumber: '' }));
                }}
                placeholder={sourceType === 'Supplier' ? 'cth: INV/2026/088' : 'Opsional (bisa dikosongkan)'}
                className={`w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-mono font-semibold focus:ring-2 focus:ring-teal-500 ${isInvalid(fieldErrors.invoiceNumber)}`}
              />
              {fieldErrors.invoiceNumber && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.invoiceNumber}
                </span>
              )}
            </div>
          </div>

          {/* Source Selection (Supplier vs Self Purchase) */}
          {sourceType === 'Supplier' ? (
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="block text-xs font-bold text-slate-700">Nama Supplier / Pemasok</label>
                {db.suppliers.length > 0 && (
                  <span className="text-[10px] text-teal-700 font-semibold">
                    {db.suppliers.length} Supplier Terdaftar
                  </span>
                )}
              </div>
              
              <SearchableSelect
                options={db.suppliers.map(s => ({
                  value: s.name,
                  label: s.name,
                  sublabel: s.companyName ? `${s.companyName} (${s.phone})` : s.phone
                }))}
                value={supplierName}
                onChange={(val) => {
                  setSupplierName(val);
                  if (fieldErrors.supplierName) setFieldErrors(prev => ({ ...prev, supplierName: '' }));
                }}
                placeholder="Pilih Supplier / Distributor..."
                searchPlaceholder="Cari Nama Supplier atau Perusahaan..."
                className={isInvalid(fieldErrors.supplierName)}
              />
              {fieldErrors.supplierName && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.supplierName}
                </span>
              )}
            </div>
          ) : (
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">
                Asal Pembelian / Nama Toko / Agen / Pasar
              </label>
              <input
                type="text"
                value={supplierName}
                onChange={(e) => {
                  setSupplierName(e.target.value);
                  if (fieldErrors.supplierName) setFieldErrors(prev => ({ ...prev, supplierName: '' }));
                }}
                placeholder="cth: Agen Beras Sumber Rejeki / Grosir Indogrosir"
                className={`w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-semibold focus:ring-2 focus:ring-teal-500 ${isInvalid(fieldErrors.supplierName)}`}
              />
              {fieldErrors.supplierName && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.supplierName}
                </span>
              )}

              {/* Quick Preset Chips */}
              <div className="flex flex-wrap items-center gap-1.5 mt-2">
                <span className="text-[10px] font-semibold text-slate-400">Pilihan Cepat:</span>
                {selfPurchasePresets.map((preset, idx) => (
                  <button
                    key={idx}
                    type="button"
                    onClick={() => {
                      setSupplierName(preset);
                      if (fieldErrors.supplierName) setFieldErrors(prev => ({ ...prev, supplierName: '' }));
                    }}
                    className={`px-2 py-0.5 rounded-lg text-[10px] font-semibold transition border ${
                      supplierName === preset
                        ? 'bg-amber-100 text-amber-900 border-amber-300'
                        : 'bg-slate-100 text-slate-600 border-slate-200 hover:bg-slate-200'
                    }`}
                  >
                    + {preset}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Product and Variant Select */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-slate-100">
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Pilih Barang</label>
              <SearchableSelect
                options={db.products.map(p => ({
                  value: p.id,
                  label: p.name,
                  badge: p.category
                }))}
                value={selectedProductId}
                onChange={(val) => {
                  handleProductChange(val);
                  if (fieldErrors.selectedProductId) setFieldErrors(prev => ({ ...prev, selectedProductId: '' }));
                }}
                placeholder="Pilih Barang..."
                searchPlaceholder="Cari Nama Barang..."
                className={isInvalid(fieldErrors.selectedProductId)}
              />
              {fieldErrors.selectedProductId && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.selectedProductId}
                </span>
              )}
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Pilih Varian / Ukuran</label>
              <SearchableSelect
                options={(selectedProduct?.variants || []).map(v => ({
                  value: v.id,
                  label: v.variantName,
                  sublabel: `Stok: ${v.stock} ${v.unit}`
                }))}
                value={selectedVariantId}
                onChange={(val) => {
                  handleVariantChange(val);
                  if (fieldErrors.selectedVariantId) setFieldErrors(prev => ({ ...prev, selectedVariantId: '' }));
                }}
                placeholder="Pilih Varian..."
                searchPlaceholder="Cari Varian / Ukuran..."
                className={isInvalid(fieldErrors.selectedVariantId)}
              />
              {fieldErrors.selectedVariantId && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.selectedVariantId}
                </span>
              )}
            </div>
          </div>

          {/* Quantity & Buy Price */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">
                Jumlah Barang Masuk ({selectedVariant?.unit || 'Pcs'})
              </label>
              <input
                type="number"
                value={quantity}
                onChange={(e) => {
                  setQuantity(Number(e.target.value));
                  if (fieldErrors.quantity) setFieldErrors(prev => ({ ...prev, quantity: '' }));
                }}
                min="1"
                className={`w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm font-bold text-slate-900 focus:ring-2 focus:ring-teal-500 ${isInvalid(fieldErrors.quantity)}`}
              />
              {fieldErrors.quantity && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.quantity}
                </span>
              )}
            </div>

            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1">Harga Beli Per Unit (Rp)</label>
              <input
                type="number"
                value={buyPrice}
                onChange={(e) => {
                  setBuyPrice(Number(e.target.value));
                  if (fieldErrors.buyPrice) setFieldErrors(prev => ({ ...prev, buyPrice: '' }));
                }}
                min="0"
                className={`w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm font-bold text-slate-900 focus:ring-2 focus:ring-teal-500 ${isInvalid(fieldErrors.buyPrice)}`}
              />
              {fieldErrors.buyPrice && (
                <span className="invalid-feedback">
                  <AlertCircle className="w-3 h-3" /> {fieldErrors.buyPrice}
                </span>
              )}
            </div>
          </div>

          {/* Total Cost Display */}
          <div className="p-3 bg-teal-50 border border-teal-200 rounded-xl flex items-center justify-between">
            <span className="text-xs font-semibold text-teal-900">Total Biaya Pembelian:</span>
            <span className="text-lg font-black text-teal-700">
              Rp {(quantity * buyPrice).toLocaleString('id-ID')}
            </span>
          </div>

          {/* Raw Material Price Change / Commodity Inflation Adjustment */}
          {selectedVariant && (
            <div className="p-3.5 bg-amber-50/90 border border-amber-200 rounded-xl space-y-3">
              <div className="flex items-start justify-between gap-2">
                <div>
                  <div className="flex items-center gap-1.5 text-amber-900 font-bold text-xs">
                    <AlertTriangle className="w-4 h-4 text-amber-600" />
                    <span>Penyesuaian Harga Modal & Harga Jual</span>
                  </div>
                  <p className="text-[11px] text-amber-800 mt-0.5">
                    {buyPrice > selectedVariant.buyPrice ? (
                      <span className="font-semibold text-rose-700">
                        ⚡ Ada Kenaikan Modal: Rp {selectedVariant.buyPrice.toLocaleString('id-ID')} &rarr; Rp {buyPrice.toLocaleString('id-ID')} (+Rp {(buyPrice - selectedVariant.buyPrice).toLocaleString('id-ID')})
                      </span>
                    ) : (
                      <span>Modal saat ini di database: Rp {selectedVariant.buyPrice.toLocaleString('id-ID')}</span>
                    )}
                  </p>
                </div>

                <label className="flex items-center gap-2 cursor-pointer shrink-0 mt-0.5">
                  <input
                    type="checkbox"
                    checked={shouldUpdateSellPrice}
                    onChange={(e) => setShouldUpdateSellPrice(e.target.checked)}
                    className="w-4 h-4 text-teal-600 rounded focus:ring-teal-500"
                  />
                  <span className="text-xs font-bold text-slate-800">Update Harga Jual</span>
                </label>
              </div>

              {shouldUpdateSellPrice && (
                <div className="grid grid-cols-2 gap-3 pt-2 border-t border-amber-200">
                  <div>
                    <label className="block text-[11px] font-bold text-amber-900 mb-1">
                      Harga Jual Eceran Baru (Rp)
                    </label>
                    <input
                      type="number"
                      value={newSellPrice}
                      onChange={(e) => setNewSellPrice(Number(e.target.value))}
                      className="w-full px-3 py-1.5 bg-white border border-amber-300 rounded-lg text-xs font-bold text-slate-900 focus:ring-2 focus:ring-amber-500"
                    />
                    <span className="text-[10px] text-amber-700 block mt-0.5 font-medium">
                      Harga Jual Lama: Rp {selectedVariant.sellPrice.toLocaleString('id-ID')}
                    </span>
                  </div>

                  <div>
                    <label className="block text-[11px] font-bold text-amber-900 mb-1">
                      Harga Grosir / Reseller (Rp)
                    </label>
                    <input
                      type="number"
                      value={newWholesalePrice}
                      onChange={(e) => setNewWholesalePrice(Number(e.target.value))}
                      className="w-full px-3 py-1.5 bg-white border border-amber-300 rounded-lg text-xs font-bold text-slate-900 focus:ring-2 focus:ring-amber-500"
                    />
                    <span className="text-[10px] text-amber-700 block mt-0.5 font-medium">
                      Harga khusus untuk dijual lagi
                    </span>
                  </div>
                </div>
              )}
            </div>
          )}

          <div>
            <label className="block text-xs font-bold text-slate-700 mb-1">Catatan / Keterangan</label>
            <input
              type="text"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="cth: Pengiriman batch Agustus, kondisi barang baik..."
              className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-teal-500"
            />
          </div>

          <div className="pt-3 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-teal-700 hover:bg-teal-800 text-white font-bold text-xs rounded-xl shadow-md transition flex items-center gap-1.5"
            >
              <Check className="w-4 h-4" /> Simpan & Update Stok
            </button>
          </div>

        </form>

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