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

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

const useToast = () => {
  const [toasts, setToasts] = useState<Array<{ id: number; message: string; type: string }>>([]);
  const show = (message: string, type = 'info') => {
    const id = Date.now();
    setToasts((prev) => [...prev, { id, message, type }]);
    setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockInvoices = [
  { id: 'in_1', customer: 'Acme Corp', amount: 9900, status: 'paid', dueDate: Date.now() - 86400000 * 5, paidAt: Date.now() - 86400000 * 3 },
  { id: 'in_2', customer: 'TechStart', amount: 29900, status: 'open', dueDate: Date.now() + 86400000 * 7, paidAt: null },
  { id: 'in_3', customer: 'Global Ventures', amount: 2900, status: 'paid', dueDate: Date.now() - 86400000 * 15, paidAt: Date.now() - 86400000 * 12 },
  { id: 'in_4', customer: 'Startup Labs', amount: 15000, status: 'void', dueDate: Date.now() - 86400000 * 20, paidAt: null },
  { id: 'in_5', customer: 'Innovation Hub', amount: 9900, status: 'uncollectible', dueDate: Date.now() - 86400000 * 60, paidAt: null },
  { id: 'in_6', customer: 'Digital Agency', amount: 5500, status: 'open', dueDate: Date.now() + 86400000 * 14, paidAt: null },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredInvoices = useMemo(() => {
    return mockInvoices.filter((invoice) => {
      const matchesSearch =
        invoice.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        invoice.customer.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || invoice.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const totalPaid = mockInvoices.filter((i) => i.status === 'paid').reduce((sum, i) => sum + i.amount, 0);
    const totalOpen = mockInvoices.filter((i) => i.status === 'open').reduce((sum, i) => sum + i.amount, 0);
    const paid = mockInvoices.filter((i) => i.status === 'paid').length;
    const open = mockInvoices.filter((i) => i.status === 'open').length;
    return { totalPaid, totalOpen, paid, open };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setStatusFilter(status);
      show(`Filtered by: ${status}`, 'info');
    });
  };

  const handleAction = (invoice: typeof mockInvoices[0], action: string) => {
    show(`${action} invoice ${invoice.id}`, 'info');
  };

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount / 100);
  };

  const formatDate = (timestamp: number | null) => {
    if (!timestamp) return 'N/A';
    return new Date(timestamp).toLocaleDateString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Invoice Center</h1>
        <p className="subtitle">Manage invoices, payments, and billing</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Paid</div>
          <div className="stat-value stat-success">{formatAmount(stats.totalPaid)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Open</div>
          <div className="stat-value stat-warning">{formatAmount(stats.totalOpen)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Paid Invoices</div>
          <div className="stat-value">{stats.paid}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Open Invoices</div>
          <div className="stat-value">{stats.open}</div>
        </div>
      </div>

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

      {isPending && <div className="loading-indicator">Filtering...</div>}

      <div className="data-grid">
        {filteredInvoices.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" strokeWidth="2" />
              <polyline points="14 2 14 8 20 8" strokeWidth="2" />
              <line x1="16" y1="13" x2="8" y2="13" strokeWidth="2" />
              <line x1="16" y1="17" x2="8" y2="17" strokeWidth="2" />
            </svg>
            <h3>No invoices found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Invoice ID</th>
                <th>Customer</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Due Date</th>
                <th>Paid At</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredInvoices.map((invoice) => (
                <tr key={invoice.id}>
                  <td className="mono">{invoice.id}</td>
                  <td>{invoice.customer}</td>
                  <td className="amount">{formatAmount(invoice.amount)}</td>
                  <td>
                    <span className={`badge badge-${invoice.status}`}>{invoice.status}</span>
                  </td>
                  <td className="date">{formatDate(invoice.dueDate)}</td>
                  <td className="date">{formatDate(invoice.paidAt)}</td>
                  <td>
                    <div className="action-buttons">
                      {invoice.status === 'open' && (
                        <>
                          <button className="btn-action btn-sm" onClick={() => handleAction(invoice, 'Send')}>
                            Send
                          </button>
                          <button className="btn-action btn-sm" onClick={() => handleAction(invoice, 'Pay')}>
                            Pay
                          </button>
                        </>
                      )}
                      {invoice.status === 'paid' && (
                        <button className="btn-action btn-sm" onClick={() => handleAction(invoice, 'Download')}>
                          Download
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div className="toast-container">
        {toasts.map((toast) => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;
