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 mockTaxItems = [
  { id: 'TAX001', name: 'State Sales Tax', type: 'Sales Tax', rate: 6.25, agency: 'State Revenue Dept', status: 'active' },
  { id: 'TAX002', name: 'Local Sales Tax', type: 'Sales Tax', rate: 1.75, agency: 'City Tax Office', status: 'active' },
  { id: 'TAX003', name: 'Federal Payroll Tax', type: 'Payroll Tax', rate: 15.3, agency: 'IRS', status: 'active' },
  { id: 'TAX004', name: 'State Unemployment Tax', type: 'Payroll Tax', rate: 3.4, agency: 'State Unemployment', status: 'active' },
  { id: 'TAX005', name: 'Previous Year Sales Tax', type: 'Sales Tax', rate: 6.0, agency: 'State Revenue Dept', status: 'inactive' },
];

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

  const filteredTaxItems = useMemo(() => {
    return mockTaxItems.filter((item) => {
      const matchesSearch = item.name.toLowerCase().includes(debouncedSearch.toLowerCase()) || item.agency.toLowerCase().includes(debouncedSearch.toLowerCase()) || item.id.includes(debouncedSearch);
      const matchesFilter = filterType === 'all' || item.type === filterType;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterType]);

  const stats = useMemo(() => {
    const total = mockTaxItems.filter(t => t.status === 'active').length;
    const salesTax = mockTaxItems.filter(t => t.type === 'Sales Tax' && t.status === 'active').length;
    const payrollTax = mockTaxItems.filter(t => t.type === 'Payroll Tax' && t.status === 'active').length;
    const avgRate = mockTaxItems.filter(t => t.status === 'active').reduce((s, t) => s + t.rate, 0) / total;
    return { total, salesTax, payrollTax, avgRate };
  }, []);

  const handleFilterChange = (type: string) => {
    startTransition(() => {
      setFilterType(type);
      showToast(`Filter: ${type === 'all' ? 'All Tax Items' : type}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Tax Center</h1>
        <p>Tax codes, rates, and agencies</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Active Tax Items</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Sales Tax Items</div>
          <div className="stat-value">{stats.salesTax}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Payroll Tax Items</div>
          <div className="stat-value">{stats.payrollTax}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Average Rate</div>
          <div className="stat-value">{stats.avgRate.toFixed(2)}%</div>
        </div>
      </div>

      <div className="controls">
        <input type="text" className="search-input" placeholder="Search by name, agency, or ID..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
        <div className="filter-buttons">
          {['all', 'Sales Tax', 'Payroll Tax'].map((type) => (
            <button key={type} className={`filter-btn ${filterType === type ? 'active' : ''}`} onClick={() => handleFilterChange(type)}>
              {type === 'all' ? 'All' : type}
            </button>
          ))}
        </div>
      </div>

      {filteredTaxItems.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📋</div>
          <h3>No tax items found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Type</th>
                <th>Rate (%)</th>
                <th>Agency</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredTaxItems.map((item) => (
                <tr key={item.id}>
                  <td style={{ fontFamily: 'monospace', color: 'var(--accent-primary)', fontWeight: 600 }}>{item.id}</td>
                  <td style={{ fontWeight: 500 }}>{item.name}</td>
                  <td>{item.type}</td>
                  <td className="amount">{item.rate.toFixed(2)}%</td>
                  <td>{item.agency}</td>
                  <td>
                    <span style={{ display: 'inline-block', padding: '0.375rem 0.75rem', borderRadius: '9999px', fontSize: '0.75rem', fontWeight: 600, background: item.status === 'active' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(148, 163, 184, 0.1)', color: item.status === 'active' ? 'var(--success)' : 'var(--text-muted)' }}>
                      {item.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
