const { useState, useEffect } = React;
const { formatCleanAmount } = window;

function QrisBssView() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [downloading, setDownloading] = useState(false);
  const [error, setError] = useState(null);
  
  const [tags, setTags] = useState([]);
  const [inputSearch, setInputSearch] = useState('');

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(25);
  const [totalPages, setTotalPages] = useState(1);
  const [totalRecords, setTotalRecords] = useState(0);

  const fetchData = async () => {
    setLoading(true); setError(null);
    try {
      let queryParams = new URLSearchParams();
      queryParams.append('page', page);
      queryParams.append('limit', limit);
      tags.forEach(t => queryParams.append('tags', t));

      const response = await fetch(`/api/qris-bss?${queryParams.toString()}`);
      const contentType = response.headers.get("content-type");
      if (!contentType || !contentType.includes("application/json")) throw new Error("Gagal mengambil data dari server / Response bukan JSON.");
      
      const result = await response.json();
      if (response.ok && result.success) {
        setData(result.data || []);
        if (result.pagination) {
          setTotalPages(result.pagination.totalPages);
          setTotalRecords(result.pagination.totalRecords);
        }
      } else { throw new Error(result.message || 'Gagal memuat data QRIS BSS'); }
    } catch (err) { setError(err.message); } finally { setLoading(false); }
  };

  useEffect(() => { fetchData(); }, [page, limit, tags]);

  const processBulkInput = (rawText) => {
    if (!rawText) return;
    const items = rawText.split(/[\s,\n\r\t]+/).map(item => item.trim()).filter(item => item !== '');
    if (items.length > 0) {
      setTags([...new Set([...tags, ...items])]);
      setPage(1);
    }
  };

  const handleTagKeyDown = (e) => {
    if (e.key === 'Enter') { e.preventDefault(); processBulkInput(inputSearch); setInputSearch(''); }
  };

  const handlePaste = (e) => {
    e.preventDefault(); const pastedText = e.clipboardData.getData('text');
    processBulkInput(pastedText); setInputSearch('');
  };

  const removeTag = (tagToRemove) => { setTags(tags.filter(t => t !== tagToRemove)); setPage(1); };
  const clearAllTags = () => { setTags([]); setPage(1); };

  const downloadExcel = async () => {
    setDownloading(true);
    try {
      let queryParams = new URLSearchParams();
      queryParams.append('export', 'true');
      tags.forEach(t => queryParams.append('tags', t));

      const response = await fetch(`/api/qris-bss?${queryParams.toString()}`);
      const result = await response.json();

      if (!response.ok || !result.success) throw new Error(result.message || "Gagal mengambil data export.");

      const exportData = result.data || [];
      if (exportData.length === 0) { alert("Tidak ada data untuk diunduh!"); return; }

      const headers = [
        "NO", "DATE TRAN", "TIME TRAN", "NO REFERENCE", "NO FT", "ISSUER NAME", 
        "MERCHANT NAME", "LOCATION MERCHANT", "MERCHANT PAN", "NASIONAL MID", 
        "MERCHANT AGGREGATOR ID", "STATUS TRANSACTION", "RESPONSE CODE", 
        "KETERANGAN RESPONSE CODE", "AMOUNT", "AMOUNT TIPS", "MDR", "MDR AMOUNT", 
        "CATEGORY MERCHANT", "CODE MERCHANT", "CUSTOMER NAME", "CUSTOMER PAN", 
        "REFUND DATE", "NO FT REFUND", "TERMINAL ID", "% SHARING", "BATCH REFERENCE", "INVOICE NUMBER"
      ];
      
      const wsData = [headers];
      exportData.forEach((d, i) => {
        wsData.push([
          i + 1, d.date_tran || '', d.time_tran || '', d.no_reference || '', d.no_ft || '',
          d.issuer_name || '', d.merchant_name || '', d.location_merchant || '',
          d.merchant_pan || '', d.nasional_mid || '', d.merchant_aggregator_id || '',
          d.status_transaction || '', d.response_code || '', d.keterangan_response_code || '',
          Number(d.amount) || 0, Number(d.amount_tips) || 0, Number(d.mdr) || 0, Number(d.mdr_amount) || 0,
          d.category_merchant || '', d.code_merchant || '', d.customer_name || '', d.customer_pan || '',
          d.refund_date || '', d.no_ft_refund || '', d.terminal_id || '', Number(d.sharing_percent) || 0,
          d.batch_reference || '', d.invoice_number || ''
        ]);
      });

      const today = new Date().toISOString().split('T')[0];
      const ws = window.XLSX.utils.aoa_to_sheet(wsData);
      const wb = window.XLSX.utils.book_new();
      window.XLSX.utils.book_append_sheet(wb, ws, "Settlement QRIS BSS");
      window.XLSX.writeFile(wb, `Settlement_QRIS_BSS_Bulk_Filtered_${today}.xlsx`);

    } catch (err) { alert(err.message); } finally { setDownloading(false); }
  };

  return (
    <div className="w-full space-y-6 pb-12">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-cardbg/80 backdrop-blur-md p-6 rounded-2xl border border-slate-700/60 shadow-lg">
        <div>
          <div className="flex items-center space-x-3">
            <span className="p-2 bg-emerald-500/10 text-emerald-400 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" /></svg>
            </span>
            <h1 className="text-xl md:text-2xl font-extrabold text-white tracking-tight">QRIS BSS</h1>
          </div>
          <p className="text-xs md:text-sm text-slate-400 mt-1 pl-11">Pencarian Bulk & Monitoring Data Settlement QRIS BSS (Total {totalRecords.toLocaleString('id-ID')} Transaksi Ditemukan)</p>
        </div>
        <div className="flex items-center space-x-2">
          <button onClick={downloadExcel} disabled={downloading || totalRecords === 0} className="bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white px-4 py-2.5 rounded-xl font-medium text-xs flex items-center space-x-2 transition shadow-lg active:scale-95">
            <svg className={`w-4 h-4 ${downloading ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
            <span>{downloading ? 'Mengeksport...' : `Download Full XLSX (${totalRecords.toLocaleString('id-ID')})`}</span>
          </button>
          <button onClick={fetchData} className="bg-slate-800 hover:bg-slate-700 text-slate-200 px-4 py-2.5 rounded-xl border border-slate-600/80 text-xs font-medium flex items-center space-x-2 transition shadow-sm active:scale-95">
            <svg className={`h-4 w-4 text-blue-400 ${loading ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
            <span>Refresh</span>
          </button>
        </div>
      </div>

      <div className="p-4 bg-[#0b1329] border border-slate-800 rounded-2xl shadow-lg space-y-3">
        <div className="flex items-center justify-between text-xs text-slate-400 font-semibold px-1">
          <span>Pencarian Bulk (Paste daftar nomor/kata kunci terpisah spasi/baris baru):</span>
          {tags.length > 0 && (
            <button onClick={clearAllTags} className="text-rose-400 hover:text-rose-300 transition">Hapus Semua Tag ({tags.length})</button>
          )}
        </div>
        <div className="flex flex-wrap items-center bg-[#0f172a] border border-slate-700/80 rounded-xl px-3 py-2 shadow-inner focus-within:border-emerald-500 transition-all duration-200 min-h-[46px]">
          <svg className="w-4 h-4 text-slate-500 mr-2.5 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
          {tags.map((tag, i) => (
            <span key={i} className="flex items-center bg-emerald-900/60 border border-emerald-500/50 text-emerald-200 text-xs px-2.5 py-1 rounded-full mr-2 mb-1 mt-1 font-medium shadow-sm">
              {tag} <button onClick={() => removeTag(tag)} className="ml-1.5 text-emerald-400 hover:text-rose-400 font-bold">&times;</button>
            </span>
          ))}
          <input type="text" placeholder={tags.length === 0 ? "Ketik atau Paste deretan kata kunci/nomor lalu Enter..." : "Tambah nomor/kata kunci lain..."} value={inputSearch} onChange={(e) => setInputSearch(e.target.value)} onKeyDown={handleTagKeyDown} onPaste={handlePaste} className="bg-transparent text-sm text-white focus:outline-none flex-1 min-w-[220px] py-1" />
        </div>
      </div>

      {loading ? (
        <div className="flex flex-col items-center justify-center p-16 bg-cardbg rounded-2xl border border-slate-700/60 text-slate-400">
          <svg className="animate-spin h-8 w-8 text-emerald-400 mb-3" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
          <p className="text-sm font-medium">Memuat data Settlement QRIS BSS dari server...</p>
        </div>
      ) : error ? (
        <div className="p-8 bg-red-950/40 border border-red-800/60 text-red-400 rounded-2xl text-center"><p className="font-bold text-base mb-1">Gagal Memuat Data</p><p className="text-sm text-red-300">{error}</p></div>
      ) : data.length === 0 ? (
        <div className="p-16 bg-cardbg rounded-2xl border border-slate-700/60 text-center text-slate-400"><p className="text-base font-bold text-slate-300 mb-1">Data Tidak Ditemukan</p><p className="text-xs text-slate-500">Tidak ada transaksi QRIS BSS yang sesuai dengan kata kunci pencarian di seluruh database.</p></div>
      ) : (
        <div className="bg-cardbg rounded-2xl border border-slate-700/60 overflow-hidden shadow-2xl flex flex-col">
          <div className="overflow-x-auto max-h-[550px]">
            <table className="w-full text-left text-xs text-slate-300 whitespace-nowrap">
              <thead className="bg-slate-900 text-slate-400 uppercase tracking-wider text-[11px] font-bold border-b border-slate-700/80 sticky top-0 z-10">
                <tr>
                  <th className="py-3.5 px-4 border-r border-slate-800 text-center">NO</th>
                  <th className="py-3.5 px-4 border-r border-slate-800">TANGGAL & WAKTU</th>
                  <th className="py-3.5 px-4 border-r border-slate-800">NO REFERENCE / FT</th>
                  <th className="py-3.5 px-4 border-r border-slate-800">ISSUER & MERCHANT</th>
                  <th className="py-3.5 px-4 border-r border-slate-800">CUSTOMER</th>
                  <th className="py-3.5 px-4 border-r border-slate-800 text-right">AMOUNT</th>
                  <th className="py-3.5 px-4 border-r border-slate-800 text-right">MDR AMOUNT</th>
                  <th className="py-3.5 px-4 border-r border-slate-800 text-center">STATUS</th>
                  <th className="py-3.5 px-4">INVOICE & TERMINAL</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800/60 font-mono">
                {data.map((d, idx) => (
                  <tr key={d.sys_id || idx} className="hover:bg-slate-800/40 transition">
                    <td className="py-3 px-4 text-center text-slate-500 font-bold">{(page - 1) * limit + idx + 1}</td>
                    <td className="py-3 px-4 border-r border-slate-800">
                      <div className="font-bold text-white">{d.date_tran || '-'}</div>
                      <div className="text-[10px] text-slate-400">{d.time_tran || '-'}</div>
                    </td>
                    <td className="py-3 px-4 border-r border-slate-800">
                      <div className="text-emerald-400 font-bold">{d.no_reference || '-'}</div>
                      <div className="text-[10px] text-slate-400">FT: {d.no_ft || '-'}</div>
                    </td>
                    <td className="py-3 px-4 border-r border-slate-800">
                      <div className="font-bold text-slate-200">{d.merchant_name || '-'}</div>
                      <div className="text-[10px] text-slate-400">Issuer: <span className="text-slate-300">{d.issuer_name || '-'}</span></div>
                    </td>
                    <td className="py-3 px-4 border-r border-slate-800">
                      <div className="font-semibold text-slate-300">{d.customer_name || '-'}</div>
                      <div className="text-[10px] text-slate-400">{d.customer_pan || '-'}</div>
                    </td>
                    <td className="py-3 px-4 border-r border-slate-800 text-right font-bold text-emerald-400">Rp {formatCleanAmount(d.amount)}</td>
                    <td className="py-3 px-4 border-r border-slate-800 text-right text-slate-300">Rp {formatCleanAmount(d.mdr_amount)}</td>
                    <td className="py-3 px-4 border-r border-slate-800 text-center">
                      <span className={`px-2.5 py-1 rounded-full text-[10px] font-bold ${String(d.status_transaction || '').toUpperCase() === 'SUCCESS' || String(d.status_transaction || '').toUpperCase() === 'SETTLED' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-amber-500/10 text-amber-400 border border-amber-500/30'}`}>{d.status_transaction || '-'}</span>
                    </td>
                    <td className="py-3 px-4">
                      <div className="text-slate-300">{d.invoice_number || '-'}</div>
                      <div className="text-[10px] text-slate-500">Term ID: {d.terminal_id || '-'}</div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="p-4 bg-slate-900 border-t border-slate-800 flex flex-col sm:flex-row items-center justify-between gap-4 text-xs">
            <div className="flex items-center space-x-3 text-slate-400">
              <span>Menampilkan {((page - 1) * limit) + 1} - {Math.min(page * limit, totalRecords)} dari <strong>{totalRecords.toLocaleString('id-ID')}</strong> data</span>
              <div className="flex items-center space-x-1.5 ml-4 border-l border-slate-800 pl-4">
                <span>Tampilkan:</span>
                <select value={limit} onChange={(e) => { setLimit(parseInt(e.target.value)); setPage(1); }} className="bg-slate-800 border border-slate-700 text-white rounded px-2 py-1 focus:outline-none">
                  <option value={10}>10</option>
                  <option value={25}>25</option>
                  <option value={50}>50</option>
                  <option value={100}>100</option>
                </select>
              </div>
            </div>

            <div className="flex items-center space-x-2">
              <button onClick={() => setPage(1)} disabled={page === 1} className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed rounded text-slate-300 font-bold">&laquo;</button>
              <button onClick={() => setPage(p => Math.max(p - 1, 1))} disabled={page === 1} className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed rounded text-slate-300 font-medium">Prev</button>
              <span className="px-3 py-1.5 bg-emerald-600/20 text-emerald-400 border border-emerald-500/30 font-bold rounded">Halaman {page} / {totalPages}</span>
              <button onClick={() => setPage(p => Math.min(p + 1, totalPages))} disabled={page >= totalPages} className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed rounded text-slate-300 font-medium">Next</button>
              <button onClick={() => setPage(totalPages)} disabled={page >= totalPages} className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-30 disabled:cursor-not-allowed rounded text-slate-300 font-bold">&raquo;</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.QrisBssView = QrisBssView;