'use client';

import React, { useState } from 'react';
import { Search, Eye, Printer, ChevronLeft, ChevronRight } from 'lucide-react';
import StatusBadge from '@/components/ui/StatusBadge';
import { toast } from 'sonner';

interface Transaction {
  id: string;
  ref: string;
  customer: string;
  cashier: string;
  branch: string;
  items: number;
  subtotal: number;
  vat: number;
  total: number;
  paymentMethod: 'M-Pesa' | 'Cash' | 'Card' | 'Split';
  status: 'completed' | 'voided' | 'processing' | 'held';
  time: string;
}

const transactions: Transaction[] = [
  { id: 'txn-20847', ref: 'S-20847', customer: 'Wanjiru Kamau', cashier: 'B. Otieno', branch: 'Westlands', items: 6, subtotal: 2982, vat: 477, total: 3459, paymentMethod: 'M-Pesa', status: 'completed', time: '09:14 AM' },
  { id: 'txn-20846', ref: 'S-20846', customer: 'Walk-in', cashier: 'A. Mwangi', branch: 'Westlands', items: 2, subtotal: 580, vat: 93, total: 673, paymentMethod: 'Cash', status: 'completed', time: '09:08 AM' },
  { id: 'txn-20845', ref: 'S-20845', customer: 'Kipchoge Ltd', cashier: 'B. Otieno', branch: 'Westlands', items: 14, subtotal: 8420, vat: 1347, total: 9767, paymentMethod: 'Card', status: 'completed', time: '09:01 AM' },
  { id: 'txn-20844', ref: 'S-20844', customer: 'Njoki Waweru', cashier: 'C. Njoroge', branch: 'CBD', items: 3, subtotal: 1240, vat: 198, total: 1438, paymentMethod: 'M-Pesa', status: 'completed', time: '08:55 AM' },
  { id: 'txn-20843', ref: 'S-20843', customer: 'Walk-in', cashier: 'A. Mwangi', branch: 'Westlands', items: 1, subtotal: 350, vat: 56, total: 406, paymentMethod: 'Cash', status: 'voided', time: '08:48 AM' },
  { id: 'txn-20842', ref: 'S-20842', customer: 'Fatuma Hassan', cashier: 'D. Kimani', branch: 'Parklands', items: 8, subtotal: 4680, vat: 749, total: 5429, paymentMethod: 'Split', status: 'completed', time: '08:42 AM' },
  { id: 'txn-20841', ref: 'S-20841', customer: 'Omondi & Sons', cashier: 'C. Njoroge', branch: 'CBD', items: 22, subtotal: 15400, vat: 2464, total: 17864, paymentMethod: 'Card', status: 'completed', time: '08:35 AM' },
  { id: 'txn-20840', ref: 'S-20840', customer: 'Walk-in', cashier: 'E. Achieng', branch: 'Parklands', items: 4, subtotal: 1820, vat: 291, total: 2111, paymentMethod: 'M-Pesa', status: 'processing', time: '08:29 AM' },
  { id: 'txn-20839', ref: 'S-20839', customer: 'Muthoni Gicheru', cashier: 'B. Otieno', branch: 'Westlands', items: 5, subtotal: 2100, vat: 336, total: 2436, paymentMethod: 'Cash', status: 'completed', time: '08:22 AM' },
  { id: 'txn-20838', ref: 'S-20838', customer: 'Walk-in', cashier: 'A. Mwangi', branch: 'Westlands', items: 1, subtotal: 200, vat: 32, total: 232, paymentMethod: 'Cash', status: 'held', time: '08:15 AM' },
];

const paymentBadge: Record<string, string> = {
  'M-Pesa': 'bg-success-bg text-success border border-green-200',
  'Cash': 'bg-muted text-muted-foreground border border-border',
  'Card': 'bg-info-bg text-info border border-blue-200',
  'Split': 'bg-warning-bg text-warning border border-yellow-200',
};

const statusVariant: Record<string, 'success' | 'danger' | 'info' | 'warning' | 'neutral'> = {
  completed: 'success',
  voided: 'danger',
  processing: 'info',
  held: 'warning',
};

export default function RecentTransactionsTable() {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 8;

  const filtered = transactions.filter(
    (t) =>
      t.ref.toLowerCase().includes(search.toLowerCase()) ||
      t.customer.toLowerCase().includes(search.toLowerCase()) ||
      t.cashier.toLowerCase().includes(search.toLowerCase())
  );

  const paged = filtered.slice((page - 1) * pageSize, page * pageSize);
  const totalPages = Math.ceil(filtered.length / pageSize);

  return (
    <div className="card-elevated rounded-xl overflow-hidden">
      <div className="flex items-center justify-between px-5 py-4 border-b border-border">
        <div>
          <h3 className="text-base font-600 text-foreground">Recent Transactions</h3>
          <p className="text-xs text-muted-foreground mt-0.5">{filtered.length} transactions today</p>
        </div>
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-2.5 h-8 w-44">
            <Search size={13} className="text-muted-foreground flex-shrink-0" />
            <input
              type="text"
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              placeholder="Search transactions…"
              className="bg-transparent text-xs text-foreground placeholder:text-muted-foreground outline-none w-full"
            />
          </div>
        </div>
      </div>

      <div className="overflow-x-auto scrollbar-thin">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/30">
              {['Ref #', 'Customer', 'Cashier', 'Branch', 'Items', 'Total (KES)', 'Payment', 'Time', 'Status', ''].map((col) => (
                <th
                  key={`col-${col || 'actions'}`}
                  className="px-4 py-2.5 text-left text-xs font-600 uppercase tracking-wide text-muted-foreground whitespace-nowrap"
                >
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {paged.map((txn) => (
              <tr
                key={txn.id}
                className="border-b border-border hover:bg-muted/40 transition-colors group"
              >
                <td className="px-4 py-3">
                  <span className="font-mono text-xs font-600 text-primary">{txn.ref}</span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs text-foreground font-500 truncate max-w-28 block">{txn.customer}</span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs text-muted-foreground">{txn.cashier}</span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs text-muted-foreground">{txn.branch}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className="text-xs font-tabular text-foreground">{txn.items}</span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs font-tabular font-600 text-foreground">
                    {txn.total.toLocaleString()}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className={`text-xs px-2 py-0.5 rounded-full font-600 ${paymentBadge[txn.paymentMethod]}`}>
                    {txn.paymentMethod}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-xs text-muted-foreground font-mono">{txn.time}</span>
                </td>
                <td className="px-4 py-3">
                  <StatusBadge variant={statusVariant[txn.status]} label={txn.status.charAt(0).toUpperCase() + txn.status.slice(1)} dot />
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => toast.success(`Viewing receipt ${txn.ref}`)}
                      className="p-1.5 rounded hover:bg-primary/10 text-muted-foreground hover:text-primary transition-colors"
                      title="View receipt"
                    >
                      <Eye size={13} />
                    </button>
                    <button
                      onClick={() => toast.success(`Printing receipt ${txn.ref}`)}
                      className="p-1.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
                      title="Print receipt"
                    >
                      <Printer size={13} />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between px-5 py-3 border-t border-border bg-muted/20">
        <p className="text-xs text-muted-foreground">
          Showing {Math.min((page - 1) * pageSize + 1, filtered.length)}–{Math.min(page * pageSize, filtered.length)} of {filtered.length}
        </p>
        <div className="flex items-center gap-1">
          <button
            onClick={() => setPage(Math.max(1, page - 1))}
            disabled={page === 1}
            className="p-1.5 rounded hover:bg-muted disabled:opacity-40 transition-colors"
          >
            <ChevronLeft size={14} className="text-muted-foreground" />
          </button>
          {Array.from({ length: totalPages }).map((_, i) => (
            <button
              key={`page-${i + 1}`}
              onClick={() => setPage(i + 1)}
              className={`w-7 h-7 rounded text-xs font-600 transition-colors ${
                page === i + 1
                  ? 'bg-primary text-white' :'text-muted-foreground hover:bg-muted'
              }`}
            >
              {i + 1}
            </button>
          ))}
          <button
            onClick={() => setPage(Math.min(totalPages, page + 1))}
            disabled={page === totalPages}
            className="p-1.5 rounded hover:bg-muted disabled:opacity-40 transition-colors"
          >
            <ChevronRight size={14} className="text-muted-foreground" />
          </button>
        </div>
      </div>
    </div>
  );
}