import React, { useState } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { InboundModal } from '../components/InboundModal';
import { PaginationControl } from '../components/PaginationControl';
import { ArrowDownLeft, Plus, Search, Truck, Trash2, FileText, DollarSign, ShoppingBag, Layers } from 'lucide-react';

export const InboundPage: React.FC = () => {
  const { db, deleteInboundRecord } = useStore();
  const [searchQuery, setSearchQuery] = useState('');
  const [sourceFilter, setSourceFilter] = useState<'all' | 'Supplier' | 'Beli Sendiri'>('all');
  const [isInboundModalOpen, setIsInboundModalOpen] = useState(false);

  // Pagination state
  const [inboundPage, setInboundPage] = useState(1);
  const [inboundPageSize, setInboundPageSize] = useState(10);

  const inboundRecords = db.inboundRecords || [];

  const filteredInbound = inboundRecords.filter(r => {
    // Filter by source type
    if (sourceFilter !== 'all') {
      const isSelfPurchase = r.sourceType === 'Beli Sendiri';
      if (sourceFilter === 'Beli Sendiri' && !isSelfPurchase) return false;
      if (sourceFilter === 'Supplier' && isSelfPurchase) return false;
    }

    const queryLower = searchQuery.toLowerCase().trim();
    if (!queryLower) return true;
    return (
      r.productName.toLowerCase().includes(queryLower) ||
      r.variantName.toLowerCase().includes(queryLower) ||
      r.supplierName.toLowerCase().includes(queryLower) ||
      r.invoiceNumber.toLowerCase().includes(queryLower) ||
      (r.notes && r.notes.toLowerCase().includes(queryLower))
    );
  });

  const totalInboundCost = filteredInbound.reduce((acc, r) => acc + r.totalCost, 0);
  const totalInboundQty = filteredInbound.reduce((acc, r) => acc + r.quantity, 0);

  // Count breakdown
  const supplierCount = inboundRecords.filter(r => r.sourceType !== 'Beli Sendiri').length;
  const selfPurchaseCount = inboundRecords.filter(r => r.sourceType === 'Beli Sendiri').length;

  // Paginated data
  const totalInboundPages = Math.ceil(filteredInbound.length / inboundPageSize);
  const paginatedInbound = filteredInbound.slice((inboundPage - 1) * inboundPageSize, inboundPage * inboundPageSize);

  const handleSearchChange = (q: string) => {
    setSearchQuery(q);
    setInboundPage(1);
  };

  const handleFilterChange = (filter: 'all' | 'Supplier' | 'Beli Sendiri') => {
    setSourceFilter(filter);
    setInboundPage(1);
  };

  return (
    <div className="space-y-6">
      
      {/* Header */}
      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-2xs flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <ArrowDownLeft className="w-6 h-6 text-teal-600" />
            <h2 className="text-xl font-bold text-slate-900">Kelola Stok Barang Masuk (Inbound)</h2>
          </div>
          <p className="text-xs text-slate-500 mt-1">
            Riwayat penerimaan stok dari supplier resmi maupun hasil belanja sendiri di agen/pasar.
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => setIsInboundModalOpen(true)}
            className="px-5 py-2.5 bg-teal-700 hover:bg-teal-800 text-white font-bold text-xs rounded-xl shadow-md flex items-center justify-center gap-2 transition"
          >
            <Plus className="w-4 h-4" /> Catat Barang Masuk
          </button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-3">
          <div className="p-3 bg-teal-100 text-teal-700 rounded-xl">
            <FileText className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Transaksi Masuk</span>
            <span className="text-lg font-black text-slate-900">{filteredInbound.length} Nota/Faktur</span>
            <div className="text-[10px] text-slate-500 font-medium mt-0.5">
              <span className="text-teal-700 font-bold">{supplierCount} Supplier</span> &bull; <span className="text-amber-700 font-bold">{selfPurchaseCount} Beli Sendiri</span>
            </div>
          </div>
        </div>

        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-3">
          <div className="p-3 bg-emerald-100 text-emerald-700 rounded-xl">
            <ArrowDownLeft className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Unit Stok Diterima</span>
            <span className="text-lg font-black text-emerald-700">{totalInboundQty.toLocaleString('id-ID')} unit</span>
          </div>
        </div>

        <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs flex items-center gap-3">
          <div className="p-3 bg-slate-100 text-slate-700 rounded-xl">
            <DollarSign className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Pengeluaran Stok</span>
            <span className="text-lg font-black text-slate-900">Rp {totalInboundCost.toLocaleString('id-ID')}</span>
          </div>
        </div>
      </div>

      {/* Filter Tabs & Search Bar */}
      <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs space-y-3">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          {/* Filter Source Tabs */}
          <div className="flex items-center gap-1.5 p-1 bg-slate-100 rounded-xl border border-slate-200/80 shrink-0">
            <button
              onClick={() => handleFilterChange('all')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 ${
                sourceFilter === 'all'
                  ? 'bg-white text-slate-900 shadow-xs'
                  : 'text-slate-600 hover:text-slate-900'
              }`}
            >
              <Layers className="w-3.5 h-3.5 text-slate-500" />
              <span>Semua ({inboundRecords.length})</span>
            </button>

            <button
              onClick={() => handleFilterChange('Supplier')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 ${
                sourceFilter === 'Supplier'
                  ? 'bg-teal-700 text-white shadow-xs'
                  : 'text-slate-600 hover:text-slate-900'
              }`}
            >
              <Truck className="w-3.5 h-3.5" />
              <span>Supplier ({supplierCount})</span>
            </button>

            <button
              onClick={() => handleFilterChange('Beli Sendiri')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 ${
                sourceFilter === 'Beli Sendiri'
                  ? 'bg-amber-600 text-white shadow-xs'
                  : 'text-slate-600 hover:text-slate-900'
              }`}
            >
              <ShoppingBag className="w-3.5 h-3.5" />
              <span>Beli Sendiri ({selfPurchaseCount})</span>
            </button>
          </div>

          {/* Search Bar */}
          <div className="relative flex-1 max-w-md">
            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => handleSearchChange(e.target.value)}
              placeholder="Cari barang, varian, supplier, agen, atau no nota..."
              className="w-full pl-10 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-medium focus:outline-none focus:ring-2 focus:ring-teal-500 focus:bg-white"
            />
          </div>
        </div>
      </div>

      {/* Records Table */}
      <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
        {filteredInbound.length === 0 ? (
          <div className="p-12 text-center space-y-2">
            <Truck className="w-10 h-10 text-slate-300 mx-auto" />
            <p className="text-xs font-semibold text-slate-500">
              {searchQuery || sourceFilter !== 'all'
                ? 'Tidak ada data barang masuk yang sesuai dengan filter/pencarian.'
                : 'Belum ada riwayat barang masuk.'}
            </p>
          </div>
        ) : (
          <div>
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs">
                <thead className="bg-slate-50 text-slate-500 font-bold border-b border-slate-200">
                  <tr>
                    <th className="p-3.5 pl-6">Tanggal & No. Nota</th>
                    <th className="p-3.5">Barang & Varian</th>
                    <th className="p-3.5">Asal Pengadaan / Supplier</th>
                    <th className="p-3.5">Jumlah Masuk</th>
                    <th className="p-3.5">Harga Beli Unit</th>
                    <th className="p-3.5">Total Biaya</th>
                    <th className="p-3.5 pr-6 text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {paginatedInbound.map((r) => {
                    const isSelfPurchase = r.sourceType === 'Beli Sendiri';
                    return (
                      <tr key={r.id} className="hover:bg-slate-50/80 transition">
                        <td className="p-3.5 pl-6">
                          <div className="font-bold text-slate-900">{r.date}</div>
                          <div className="text-[10px] text-slate-500 font-mono">{r.invoiceNumber}</div>
                        </td>

                        <td className="p-3.5">
                          <div className="font-bold text-slate-900">{r.productName}</div>
                          <div className="text-slate-500 text-[11px]">Varian: {r.variantName}</div>
                        </td>

                        <td className="p-3.5">
                          <div className="flex flex-col gap-1 items-start">
                            {isSelfPurchase ? (
                              <span className="px-2 py-0.5 bg-amber-100 text-amber-900 border border-amber-200 rounded-md text-[10px] font-bold inline-flex items-center gap-1">
                                <ShoppingBag className="w-3 h-3 text-amber-700" /> Beli Sendiri
                              </span>
                            ) : (
                              <span className="px-2 py-0.5 bg-teal-50 text-teal-800 border border-teal-200 rounded-md text-[10px] font-bold inline-flex items-center gap-1">
                                <Truck className="w-3 h-3 text-teal-600" /> Supplier Resmi
                              </span>
                            )}
                            <span className="font-semibold text-slate-800 text-xs">
                              {r.supplierName}
                            </span>
                          </div>
                        </td>

                        <td className="p-3.5">
                          <span className="px-2.5 py-1 bg-teal-100 text-teal-800 rounded-full font-black">
                            +{r.quantity} {r.unit}
                          </span>
                        </td>

                        <td className="p-3.5 font-medium text-slate-700">
                          Rp {r.buyPrice.toLocaleString('id-ID')}
                        </td>

                        <td className="p-3.5 font-bold text-slate-900">
                          Rp {r.totalCost.toLocaleString('id-ID')}
                        </td>

                        <td className="p-3.5 pr-6 text-right">
                          <button
                            onClick={() => {
                              Swal.fire({
                                title: 'Hapus Catatan Barang Masuk?',
                                text: `Hapus pencatatan "${r.invoiceNumber}" (${r.productName} - ${r.variantName})?`,
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#e11d48',
                                cancelButtonColor: '#64748b',
                                confirmButtonText: 'Ya, Hapus!',
                                cancelButtonText: 'Batal'
                              }).then((res) => {
                                if (res.isConfirmed) {
                                  deleteInboundRecord(r.id);
                                  Swal.fire({
                                    icon: 'success',
                                    title: 'Berhasil Dihapus!',
                                    text: 'Catatan barang masuk berhasil dihapus.',
                                    timer: 1500,
                                    showConfirmButton: false
                                  });
                                }
                              });
                            }}
                            className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition"
                            title="Hapus Catatan"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <PaginationControl
              currentPage={inboundPage}
              totalPages={totalInboundPages}
              pageSize={inboundPageSize}
              totalItems={filteredInbound.length}
              onPageChange={setInboundPage}
              onPageSizeChange={setInboundPageSize}
            />
          </div>
        )}
      </div>

      {/* Inbound Modal */}
      <InboundModal
        isOpen={isInboundModalOpen}
        onClose={() => setIsInboundModalOpen(false)}
      />

    </div>
  );
};

