import React, { useState } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { Transaction, SalesReturn } from '../types';
import { ReceiptModal } from '../components/ReceiptModal';
import { ReturnModal } from '../components/ReturnModal';
import { PeriodFilterBar } from '../components/PeriodFilterBar';
import { PeakHoursChart } from '../components/PeakHoursChart';
import { PaginationControl } from '../components/PaginationControl';
import { isDateInPeriod, DateFilterState } from '../utils/dateFilters';
import { History, Search, Calendar, Trash2, Eye, TrendingUp, DollarSign, Send, ArrowUpRight, RotateCcw, ArrowRightLeft, FileText } from 'lucide-react';

export const TransactionsPage: React.FC = () => {
  const { db, deleteTransaction, deleteSalesReturn } = useStore();
  const [activeSubTab, setActiveSubTab] = useState<'sales' | 'returns'>('sales');
  const [searchQuery, setSearchQuery] = useState('');
  const [periodFilter, setPeriodFilter] = useState<DateFilterState>({
    period: 'all',
    startDate: '',
    endDate: ''
  });
  const [selectedTrx, setSelectedTrx] = useState<Transaction | null>(null);
  const [isReceiptOpen, setIsReceiptOpen] = useState(false);

  // Return Modal State
  const [isReturnModalOpen, setIsReturnModalOpen] = useState(false);
  const [returnTrxTarget, setReturnTrxTarget] = useState<Transaction | null>(null);

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

  const handleOpenReturnModal = (trx: Transaction | null = null) => {
    setReturnTrxTarget(trx);
    setIsReturnModalOpen(true);
  };

  const filteredTransactions = db.transactions.filter(t => {
    // Date filter
    if (!isDateInPeriod(t.date, periodFilter)) return false;

    // Search query filter
    const queryLower = searchQuery.toLowerCase().trim();
    if (!queryLower) return true;
    return (
      t.transactionCode.toLowerCase().includes(queryLower) ||
      t.customerName.toLowerCase().includes(queryLower) ||
      t.paymentMethod.toLowerCase().includes(queryLower) ||
      t.items.some(item => item.productName.toLowerCase().includes(queryLower) || item.variantName.toLowerCase().includes(queryLower))
    );
  });

  const returnsList = db.returns || [];
  const filteredReturns = returnsList.filter(r => {
    if (!isDateInPeriod(r.date, periodFilter)) return false;
    const q = searchQuery.toLowerCase().trim();
    if (!q) return true;
    return (
      r.returnCode.toLowerCase().includes(q) ||
      r.transactionCode.toLowerCase().includes(q) ||
      r.customerName.toLowerCase().includes(q) ||
      r.returnedItems.some(item => item.productName.toLowerCase().includes(q) || item.reason.toLowerCase().includes(q))
    );
  });

  const totalRevenue = filteredTransactions.reduce((acc, t) => acc + t.finalAmount, 0);
  const totalProfit = filteredTransactions.reduce((acc, t) => acc + t.totalProfit, 0);

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

  const handleFilterChange = (filter: DateFilterState) => {
    setPeriodFilter(filter);
    setCurrentPage(1);
  };

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

  const handleOpenReceipt = (trx: Transaction) => {
    setSelectedTrx(trx);
    setIsReceiptOpen(true);
  };

  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">
            <History className="w-6 h-6 text-emerald-600" />
            <h2 className="text-xl font-bold text-slate-900">Riwayat Penjualan & Retur Pelanggan</h2>
          </div>
          <p className="text-xs text-slate-500 mt-1">
            Laporan seluruh transaksi toko, pendapatan omzet, keuntungan margin, dan pengembalian / tukar barang pembeli.
          </p>
        </div>

        <button
          onClick={() => handleOpenReturnModal(null)}
          className="px-4 py-2.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl text-xs font-bold transition shadow-xs flex items-center justify-center gap-2"
        >
          <RotateCcw className="w-4 h-4" />
          <span>Proses Retur / Tukar Barang</span>
        </button>
      </div>

      {/* Sub-Tabs: Riwayat Penjualan vs Riwayat Retur */}
      <div className="flex items-center gap-2 border-b border-slate-200 pb-1">
        <button
          onClick={() => { setActiveSubTab('sales'); setCurrentPage(1); }}
          className={`px-4 py-2 text-xs font-extrabold rounded-xl transition flex items-center gap-2 ${
            activeSubTab === 'sales'
              ? 'bg-slate-900 text-white shadow-xs'
              : 'text-slate-600 hover:bg-slate-100'
          }`}
        >
          <FileText className="w-4 h-4" />
          <span>Riwayat Transaksi Penjualan ({filteredTransactions.length})</span>
        </button>

        <button
          onClick={() => { setActiveSubTab('returns'); setCurrentPage(1); }}
          className={`px-4 py-2 text-xs font-extrabold rounded-xl transition flex items-center gap-2 ${
            activeSubTab === 'returns'
              ? 'bg-rose-600 text-white shadow-xs'
              : 'text-slate-600 hover:bg-slate-100'
          }`}
        >
          <RotateCcw className="w-4 h-4" />
          <span>Riwayat Retur & Tukar Barang ({filteredReturns.length})</span>
        </button>
      </div>

      {/* Filter Periode */}
      <PeriodFilterBar
        filterState={periodFilter}
        onChange={handleFilterChange}
      />

      {/* Metrics Row */}
      <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-emerald-100 text-emerald-700 rounded-xl">
            <ArrowUpRight className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Transaksi Selesai</span>
            <span className="text-lg font-black text-slate-900">{filteredTransactions.length} Transaksi</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-teal-100 text-teal-700 rounded-xl">
            <TrendingUp className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Omzet Penjualan</span>
            <span className="text-lg font-black text-teal-700">Rp {totalRevenue.toLocaleString('id-ID')}</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-emerald-600 text-white rounded-xl">
            <DollarSign className="w-5 h-5" />
          </div>
          <div>
            <span className="text-xs text-slate-500 font-semibold block">Total Keuntungan Bersih</span>
            <span className="text-lg font-black text-emerald-800">Rp {totalProfit.toLocaleString('id-ID')}</span>
          </div>
        </div>
      </div>

      {/* PEAK TRANSACTION HOURS TSUNAMI WAVE CHART */}
      <PeakHoursChart
        transactions={filteredTransactions}
        title="Analisis Jam Ramai Transaksi Pembelian"
        subtitle="Grafik distribusi waktu jam berapa rata-rata orang berbelanja di toko"
      />

      {/* 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 berdasarkan kode TRX, nama pembeli, atau nama barang..."
            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-emerald-500 focus:bg-white"
          />
        </div>
      </div>

      {/* Transactions List Table / Returns List Table */}
      {activeSubTab === 'sales' ? (
        <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
        {filteredTransactions.length === 0 ? (
          <div className="p-12 text-center space-y-2">
            <History className="w-10 h-10 text-slate-300 mx-auto" />
            <p className="text-xs font-semibold text-slate-500">Belum ada riwayat transaksi penjualan.</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">No. TRX & Waktu</th>
                    <th className="p-3.5">Nama Pembeli</th>
                    <th className="p-3.5">Detail Barang Keluar</th>
                    <th className="p-3.5">Metode Bayar</th>
                    <th className="p-3.5">Total Belanja</th>
                    <th className="p-3.5">Keuntungan</th>
                    <th className="p-3.5 pr-6 text-right">Aksi & Struk</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {paginatedTransactions.map((trx) => (
                    <tr key={trx.id} className="hover:bg-slate-50/80 transition">
                      <td className="p-3.5 pl-6">
                        <div className="font-bold text-slate-900">{trx.transactionCode}</div>
                        <div className="text-[10px] text-slate-500">
                          {new Date(trx.date).toLocaleDateString('id-ID', {
                            day: 'numeric',
                            month: 'short',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}
                        </div>
                      </td>

                      <td className="p-3.5">
                        <div className="font-bold text-slate-800">{trx.customerName || 'Pelanggan Umum'}</div>
                        {trx.customerPhone && (
                          <div className="text-[10px] text-slate-500 font-mono">{trx.customerPhone}</div>
                        )}
                      </td>

                      <td className="p-3.5">
                        <div className="text-slate-800 font-semibold">
                          {trx.items.map(item => `${item.productName} (${item.variantName}) x${item.quantity}`).join(', ')}
                        </div>
                      </td>

                      <td className="p-3.5">
                        <span className="px-2 py-0.5 bg-emerald-100 text-emerald-800 rounded font-bold text-[10px]">
                          {trx.paymentMethod}
                        </span>
                      </td>

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

                      <td className="p-3.5 font-bold text-teal-600">
                        +Rp {trx.totalProfit.toLocaleString('id-ID')}
                      </td>

                      <td className="p-3.5 pr-6 text-right space-x-1">
                        <button
                          onClick={() => handleOpenReceipt(trx)}
                          className="px-2.5 py-1 bg-emerald-50 text-emerald-800 hover:bg-emerald-100 rounded-lg font-bold transition inline-flex items-center gap-1"
                        >
                          <Eye className="w-3.5 h-3.5" /> Struk
                        </button>

                        <button
                          onClick={() => handleOpenReturnModal(trx)}
                          className="px-2.5 py-1 bg-rose-50 text-rose-700 hover:bg-rose-100 rounded-lg font-bold transition inline-flex items-center gap-1"
                          title="Proses Retur untuk Transaksi ini"
                        >
                          <RotateCcw className="w-3.5 h-3.5" /> Retur
                        </button>

                        <button
                          onClick={() => {
                            Swal.fire({
                              title: 'Hapus Transaksi?',
                              text: `Hapus transaksi ${trx.transactionCode} dari riwayat?`,
                              icon: 'warning',
                              showCancelButton: true,
                              confirmButtonColor: '#e11d48',
                              cancelButtonColor: '#64748b',
                              confirmButtonText: 'Ya, Hapus!',
                              cancelButtonText: 'Batal'
                            }).then((res) => {
                              if (res.isConfirmed) {
                                deleteTransaction(trx.id);
                                Swal.fire({
                                  icon: 'success',
                                  title: 'Berhasil Dihapus!',
                                  text: `Transaksi ${trx.transactionCode} telah dihapus.`,
                                  timer: 1500,
                                  showConfirmButton: false
                                });
                              }
                            });
                          }}
                          className="p-1 text-slate-400 hover:text-rose-600 rounded-lg transition"
                          title="Hapus Transaksi"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <PaginationControl
              currentPage={currentPage}
              totalPages={totalPages}
              pageSize={pageSize}
              totalItems={filteredTransactions.length}
              onPageChange={setCurrentPage}
              onPageSizeChange={setPageSize}
            />
          </div>
        )}
      </div>
      ) : (
        /* TAB RIWAYAT RETUR BARANG */
        <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
          {filteredReturns.length === 0 ? (
            <div className="p-12 text-center space-y-2">
              <RotateCcw className="w-10 h-10 text-slate-300 mx-auto" />
              <p className="text-xs font-semibold text-slate-500">Belum ada catatan retur atau tukar barang pelanggan.</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">No. Retur & Waktu</th>
                      <th className="p-3.5">Ref. TRX & Pelanggan</th>
                      <th className="p-3.5">Barang Dikembalikan</th>
                      <th className="p-3.5">Tipe Retur</th>
                      <th className="p-3.5">Nilai Barang</th>
                      <th className="p-3.5">Penyelesaian / Selisih</th>
                      <th className="p-3.5 pr-6 text-right">Aksi</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {filteredReturns.map((ret) => (
                      <tr key={ret.id} className="hover:bg-slate-50/80 transition">
                        <td className="p-3.5 pl-6">
                          <div className="font-bold text-slate-900">{ret.returnCode}</div>
                          <div className="text-[10px] text-slate-500">
                            {new Date(ret.date).toLocaleDateString('id-ID', {
                              day: 'numeric',
                              month: 'short',
                              hour: '2-digit',
                              minute: '2-digit'
                            })}
                          </div>
                        </td>

                        <td className="p-3.5">
                          <div className="font-bold text-slate-800">{ret.transactionCode}</div>
                          <div className="text-[10px] text-slate-500">{ret.customerName}</div>
                        </td>

                        <td className="p-3.5 max-w-xs">
                          <div className="space-y-1">
                            {ret.returnedItems.map((item, idx) => (
                              <div key={idx} className="text-slate-800">
                                <span className="font-semibold">{item.productName} ({item.variantName})</span> x{item.quantity}
                                <span className="text-[10px] text-rose-600 font-bold block">Alasan: {item.reason} ({item.condition})</span>
                              </div>
                            ))}
                          </div>
                        </td>

                        <td className="p-3.5">
                          <span className={`px-2 py-0.5 rounded font-bold text-[10px] ${
                            ret.returnType === 'Refund Uang'
                              ? 'bg-rose-100 text-rose-800'
                              : 'bg-indigo-100 text-indigo-800'
                          }`}>
                            {ret.returnType}
                          </span>
                        </td>

                        <td className="p-3.5 font-black text-rose-700">
                          Rp {ret.totalReturnedValue.toLocaleString('id-ID')}
                        </td>

                        <td className="p-3.5">
                          {ret.returnType === 'Refund Uang' ? (
                            <span className="text-xs font-bold text-rose-700">Refun Cash: Rp {ret.totalReturnedValue.toLocaleString('id-ID')}</span>
                          ) : (
                            <div>
                              <div className="font-bold text-slate-800 text-[11px]">
                                Pengganti: {ret.replacementItems?.map(i => `${i.productName} x${i.quantity}`).join(', ')}
                              </div>
                              <div className="text-[10px] font-bold mt-0.5">
                                {ret.priceDifference && ret.priceDifference > 0 ? (
                                  <span className="text-amber-700">Pembeli Tambah: Rp {ret.priceDifference.toLocaleString('id-ID')}</span>
                                ) : ret.priceDifference && ret.priceDifference < 0 ? (
                                  <span className="text-emerald-700">Kembalian Selisih: Rp {Math.abs(ret.priceDifference).toLocaleString('id-ID')}</span>
                                ) : (
                                  <span className="text-slate-600">Tukar Pas (0)</span>
                                )}
                              </div>
                            </div>
                          )}
                        </td>

                        <td className="p-3.5 pr-6 text-right">
                          <button
                            onClick={() => {
                              Swal.fire({
                                title: 'Hapus Catatan Retur?',
                                text: `Hapus catatan retur ${ret.returnCode}?`,
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#e11d48',
                                cancelButtonColor: '#64748b',
                                confirmButtonText: 'Ya, Hapus!',
                                cancelButtonText: 'Batal'
                              }).then((res) => {
                                if (res.isConfirmed) {
                                  deleteSalesReturn(ret.id);
                                  Swal.fire({
                                    icon: 'success',
                                    title: 'Berhasil Dihapus!',
                                    text: `Catatan retur ${ret.returnCode} telah dihapus.`,
                                    timer: 1500,
                                    showConfirmButton: false
                                  });
                                }
                              });
                            }}
                            className="p-1 text-slate-400 hover:text-rose-600 rounded-lg transition"
                            title="Hapus Record Retur"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      <ReceiptModal
        transaction={selectedTrx}
        isOpen={isReceiptOpen}
        onClose={() => setIsReceiptOpen(false)}
      />

      <ReturnModal
        isOpen={isReturnModalOpen}
        onClose={() => setIsReturnModalOpen(false)}
        initialTransaction={returnTrxTarget}
      />

    </div>
  );
};
