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 mockVendors = [
  { id: 'V001', name: 'Office Supplies Co', email: 'sales@officesupplies.com', phone: '555-1001', status1099: 'Yes', balance: 2450.00 },
  { id: 'V002', name: 'Tech Hardware Inc', email: 'billing@techhw.com', phone: '555-1002', status1099: 'No', balance: 0 },
  { id: 'V003', name: 'Marketing Agency', email: 'accounts@marketing.co', phone: '555-1003', status1099: 'Yes', balance: 5500.00 },
  { id: 'V004', name: 'Cloud Services LLC', email: 'support@cloudservices.com', phone: '555-1004', status1099: 'No', balance: 899.00 },
  { id: 'V005', name: 'Legal Services Group', email: 'billing@legalservices.com', phone: '555-1005', status1099: 'Yes', balance: 0 },
  { id: 'V006', name: 'Utilities Provider', email: 'customerservice@utilities.com', phone: '555-1006', status1099: 'No', balance: 450.00 },
];

type Vendor = typeof mockVendors[0];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredVendors = useMemo(() => {
    return mockVendors.filter((vendor) => {
      const matchesSearch =
        vendor.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        vendor.email.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        vendor.id.includes(debouncedSearch);
      const matchesFilter = filter1099 === 'all' || 
        (filter1099 === 'yes' && vendor.status1099 === 'Yes') ||
        (filter1099 === 'no' && vendor.status1099 === 'No');
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filter1099]);

  const stats = useMemo(() => {
    const total = mockVendors.length;
    const with1099 = mockVendors.filter(v => v.status1099 === 'Yes').length;
    const without1099 = mockVendors.filter(v => v.status1099 === 'No').length;
    const totalBalance = mockVendors.reduce((sum, v) => sum + v.balance, 0);
    return { total, with1099, without1099, totalBalance };
  }, []);

  const handleFilterChange = (filter: string) => {
    startTransition(() => {
      setFilter1099(filter);
      showToast(`Filter: ${filter === 'all' ? 'All Vendors' : filter === 'yes' ? '1099 Vendors' : 'Non-1099 Vendors'}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Vendor Directory</h1>
        <p>Vendor list with 1099 status and contact information</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Vendors</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">1099 Vendors</div>
          <div className="stat-value">{stats.with1099}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Non-1099</div>
          <div className="stat-value">{stats.without1099}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Balance</div>
          <div className="stat-value">${stats.totalBalance.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

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

      {filteredVendors.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🏢</div>
          <h3>No vendors found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Vendor ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>1099 Status</th>
                <th>Balance</th>
              </tr>
            </thead>
            <tbody>
              {filteredVendors.map((vendor) => (
                <tr key={vendor.id}>
                  <td className="vendor-id">{vendor.id}</td>
                  <td className="vendor-name">{vendor.name}</td>
                  <td>{vendor.email}</td>
                  <td>{vendor.phone}</td>
                  <td>
                    <span className={`status-badge status-${vendor.status1099.toLowerCase()}`}>
                      {vendor.status1099}
                    </span>
                  </td>
                  <td className="amount">${vendor.balance.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
