import React, { useState } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { OutboundModal } from '../components/OutboundModal';
import { PaginationControl } from '../components/PaginationControl';
import { ArrowUpRight, Plus, Search, Trash2, AlertTriangle, PackageX } from 'lucide-react';

export const OutboundPage: React.FC = () => {
  const { db, deleteOutboundRecord, setOutboundModalOpen } = useStore();
  const [searchQuery, setSearchQuery] = useState('');

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const outboundRecords = db.outboundRecords || [];

  const filteredOutbound = outboundRecords.filter(r => {
    const queryLower = searchQuery.toLowerCase().trim();
    if (!queryLower) return true;
    return (
      r.productName.toLowerCase().includes(queryLower) ||
      r.variantName.toLowerCase().includes(queryLower) ||
      r.reason.toLowerCase().includes(queryLower) ||
      (r.notes && r.notes.toLowerCase().includes(queryLower))
    );
  });

  const totalOutboundLossCost = filteredOutbound.reduce((acc, r) => acc + r.totalLossCost, 0);
  const totalOutboundQty = filteredOutbound.reduce((acc, r) => acc + r.quantity, 0);

  const totalPages = Math.ceil(filteredOutbound.length / pageSize);
  const paginatedOutbound = filteredOutbound.slice((currentPage - 1) * pageSize, currentPage * pageSize);

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

  return (
    <div className="space-y-6">
      
      {/* Header Banner */}
      <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">
            <ArrowUpRight className="w-6 h-6 text-amber-600" />
            <h2 className="text-xl font-bold text-slate-900">Pencatatan Barang Keluar & Kedaluwarsa</h2>
          </div>
          <p className="text-xs text-slate-500 mt-1">
            Kelola data kerugian stok, produk expired, barang rusak, serta penyesuaian opnam fisik.
          </p>
        </div>

        <button
          onClick={() => setOutboundModalOpen(true)}
          className="px-5 py-2.5 bg-amber-600 hover:bg-amber-700 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 Expired/Rusak
        </button>
      </div>

      {/* Summary Metrics */}
      <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-amber-100 text-amber-800 rounded-xl">
            <PackageX className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Catatan Keluar</span>
            <span className="text-lg font-black text-slate-900">{filteredOutbound.length} Kejadian</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-rose-100 text-rose-700 rounded-xl">
            <ArrowUpRight className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Unit Out / Expired</span>
            <span className="text-lg font-black text-rose-700">{totalOutboundQty.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">
            <AlertTriangle className="w-5 h-5 text-amber-600" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Estimasi Kerugian (Modal)</span>
            <span className="text-lg font-black text-slate-900">Rp {totalOutboundLossCost.toLocaleString('id-ID')}</span>
          </div>
        </div>
      </div>

      {/* Search Bar */}
      <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs">
        <div className="relative">
          <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 nama barang, varian, alasan (Kedaluwarsa/Rusak), atau catatan..."
            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-amber-500 focus:bg-white"
          />
        </div>
      </div>

      {/* Outbound Records Table */}
      <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
        {filteredOutbound.length === 0 ? (
          <div className="p-12 text-center space-y-2">
            <PackageX className="w-10 h-10 text-slate-300 mx-auto" />
            <p className="text-xs font-semibold text-slate-500">Belum ada riwayat barang keluar / expired.</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</th>
                    <th className="p-3.5">Barang & Varian</th>
                    <th className="p-3.5">Alasan Keluar</th>
                    <th className="p-3.5">Jumlah Out</th>
                    <th className="p-3.5">Harga Modal</th>
                    <th className="p-3.5">Total Kerugian</th>
                    <th className="p-3.5">Keterangan</th>
                    <th className="p-3.5 pr-6 text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {paginatedOutbound.map((r) => (
                    <tr key={r.id} className="hover:bg-slate-50/80 transition">
                      <td className="p-3.5 pl-6 font-bold text-slate-900">{r.date}</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">
                        <span className={`px-2.5 py-0.5 rounded-full text-[11px] font-bold ${
                          r.reason.includes('Expired')
                            ? 'bg-rose-100 text-rose-800'
                            : r.reason.includes('Rusak')
                            ? 'bg-amber-100 text-amber-900'
                            : 'bg-slate-100 text-slate-800'
                        }`}>
                          {r.reason}
                        </span>
                      </td>

                      <td className="p-3.5">
                        <span className="px-2.5 py-1 bg-rose-50 text-rose-800 rounded-full font-black border border-rose-200">
                          -{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-extrabold text-rose-700">
                        Rp {r.totalLossCost.toLocaleString('id-ID')}
                      </td>

                      <td className="p-3.5 text-slate-500 max-w-xs truncate">
                        {r.notes || '-'}
                      </td>

                      <td className="p-3.5 pr-6 text-right">
                        <button
                          onClick={() => {
                            Swal.fire({
                              title: 'Hapus Catatan Barang Keluar?',
                              text: `Hapus pencatatan barang keluar ${r.productName} - ${r.variantName}?`,
                              icon: 'warning',
                              showCancelButton: true,
                              confirmButtonColor: '#e11d48',
                              cancelButtonColor: '#64748b',
                              confirmButtonText: 'Ya, Hapus!',
                              cancelButtonText: 'Batal'
                            }).then((res) => {
                              if (res.isConfirmed) {
                                deleteOutboundRecord(r.id);
                                Swal.fire({
                                  icon: 'success',
                                  title: 'Berhasil Dihapus!',
                                  text: 'Catatan barang keluar 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={currentPage}
              totalPages={totalPages}
              pageSize={pageSize}
              totalItems={filteredOutbound.length}
              onPageChange={setCurrentPage}
              onPageSizeChange={setPageSize}
            />
          </div>
        )}
      </div>

    </div>
  );
};
