import React, { useState, useMemo, useTransition } from 'react';

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  React.useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
};

const useToast = () => {
  const [toast, setToast] = useState<string | null>(null);

  const showToast = (message: string) => {
    setToast(message);
    setTimeout(() => setToast(null), 3000);
  };

  return { toast, showToast };
};

const mockBills = [
  { id: 'B001', vendor: 'Office Supplies Co', amount: 2450.00, dueDate: '2024-02-15', billDate: '2024-01-15', status: 'unpaid' },
  { id: 'B002', vendor: 'Tech Hardware Inc', amount: 12000.00, dueDate: '2024-02-01', billDate: '2024-01-01', status: 'paid' },
  { id: 'B003', vendor: 'Marketing Agency', amount: 5500.00, dueDate: '2024-01-20', billDate: '2023-12-20', status: 'overdue' },
  { id: 'B004', vendor: 'Cloud Services LLC', amount: 899.00, dueDate: '2024-02-10', billDate: '2024-01-10', status: 'unpaid' },
  { id: 'B005', vendor: 'Legal Services Group', amount: 7500.00, dueDate: '2024-02-05', billDate: '2024-01-05', status: 'paid' },
  { id: 'B006', vendor: 'Utilities Provider', amount: 450.00, dueDate: '2024-01-25', billDate: '2024-01-01', status: 'overdue' },
];

type Bill = typeof mockBills[0];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredBills = useMemo(() => {
    return mockBills.filter((bill) => {
      const matchesSearch =
        bill.vendor.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        bill.id.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesFilter = filterStatus === 'all' || bill.status === filterStatus;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterStatus]);

  const stats = useMemo(() => {
    const total = mockBills.reduce((sum, b) => sum + b.amount, 0);
    const paid = mockBills.filter(b => b.status === 'paid').reduce((sum, b) => sum + b.amount, 0);
    const unpaid = mockBills.filter(b => b.status === 'unpaid').reduce((sum, b) => sum + b.amount, 0);
    const overdue = mockBills.filter(b => b.status === 'overdue').reduce((sum, b) => sum + b.amount, 0);
    return { total, paid, unpaid, overdue };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setFilterStatus(status);
      showToast(`Filter: ${status === 'all' ? 'All Bills' : status.charAt(0).toUpperCase() + status.slice(1)}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Bill Manager</h1>
        <p>Track bills, due dates, and payment status</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Bills</div>
          <div className="stat-value">${stats.total.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Paid</div>
          <div className="stat-value">${stats.paid.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Unpaid</div>
          <div className="stat-value">${stats.unpaid.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
        <div className="stat-card stat-danger">
          <div className="stat-label">Overdue</div>
          <div className="stat-value">${stats.overdue.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search by vendor or bill #..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'paid', 'unpaid', 'overdue'].map((status) => (
            <button
              key={status}
              className={`filter-btn ${filterStatus === status ? 'active' : ''}`}
              onClick={() => handleFilterChange(status)}
            >
              {status.charAt(0).toUpperCase() + status.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {filteredBills.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🧾</div>
          <h3>No bills found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Bill #</th>
                <th>Vendor</th>
                <th>Bill Date</th>
                <th>Due Date</th>
                <th>Amount</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredBills.map((bill) => (
                <tr key={bill.id}>
                  <td className="bill-id">{bill.id}</td>
                  <td className="vendor-name">{bill.vendor}</td>
                  <td>{bill.billDate}</td>
                  <td>{bill.dueDate}</td>
                  <td className="amount">${bill.amount.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                  <td>
                    <span className={`status-badge status-${bill.status}`}>
                      {bill.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {toast && <div className="toast">{toast}</div>}
    </div>
  );
};

export default App;
