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 mockTaxRates = [
  { id: 'txr_1', displayName: 'Sales Tax (CA)', jurisdiction: 'California', percentage: 7.25, inclusive: false, active: true },
  { id: 'txr_2', displayName: 'VAT (UK)', jurisdiction: 'United Kingdom', percentage: 20.0, inclusive: true, active: true },
  { id: 'txr_3', displayName: 'GST (Canada)', jurisdiction: 'Canada', percentage: 5.0, inclusive: false, active: true },
  { id: 'txr_4', displayName: 'Sales Tax (NY)', jurisdiction: 'New York', percentage: 8.875, inclusive: false, active: false },
];

const mockTaxIds = [
  { id: 'taxid_1', customer: 'Acme Corp', type: 'us_ein', value: '12-3456789', verification: 'verified' },
  { id: 'taxid_2', customer: 'TechStart', type: 'eu_vat', value: 'GB123456789', verification: 'verified' },
  { id: 'taxid_3', customer: 'Global Ventures', type: 'ca_bn', value: '123456789', verification: 'pending' },
  { id: 'taxid_4', customer: 'Startup Labs', type: 'au_abn', value: '12345678901', verification: 'unverified' },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [view, setView] = useState<'rates' | 'ids'>('rates');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredRates = useMemo(() => {
    return mockTaxRates.filter((rate) =>
      rate.displayName.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      rate.jurisdiction.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const filteredTaxIds = useMemo(() => {
    return mockTaxIds.filter((taxId) =>
      taxId.customer.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      taxId.value.includes(debouncedSearch)
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalRates = mockTaxRates.length;
    const activeRates = mockTaxRates.filter((r) => r.active).length;
    const totalTaxIds = mockTaxIds.length;
    const verifiedIds = mockTaxIds.filter((t) => t.verification === 'verified').length;
    return { totalRates, activeRates, totalTaxIds, verifiedIds };
  }, []);

  const handleViewChange = (newView: 'rates' | 'ids') => {
    startTransition(() => {
      setView(newView);
      show(`Switched to tax ${newView} view`, 'info');
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Tax Manager</h1>
        <p className="subtitle">Manage tax rates and customer tax IDs</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Tax Rates</div>
          <div className="stat-value">{stats.totalRates}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Rates</div>
          <div className="stat-value stat-success">{stats.activeRates}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Tax IDs</div>
          <div className="stat-value">{stats.totalTaxIds}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Verified IDs</div>
          <div className="stat-value stat-success">{stats.verifiedIds}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder={`Search tax ${view}...`}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          <button
            className={`filter-btn ${view === 'rates' ? 'active' : ''}`}
            onClick={() => handleViewChange('rates')}
          >
            Tax Rates
          </button>
          <button
            className={`filter-btn ${view === 'ids' ? 'active' : ''}`}
            onClick={() => handleViewChange('ids')}
          >
            Tax IDs
          </button>
        </div>
      </div>

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

      <div className="data-grid">
        {view === 'rates' ? (
          filteredRates.length === 0 ? (
            <div className="empty-state">
              <h3>No tax rates found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Rate ID</th>
                  <th>Display Name</th>
                  <th>Jurisdiction</th>
                  <th>Percentage</th>
                  <th>Type</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredRates.map((rate) => (
                  <tr key={rate.id}>
                    <td className="mono">{rate.id}</td>
                    <td><strong>{rate.displayName}</strong></td>
                    <td>{rate.jurisdiction}</td>
                    <td>{rate.percentage}%</td>
                    <td>
                      <span className="badge badge-active">
                        {rate.inclusive ? 'Inclusive' : 'Exclusive'}
                      </span>
                    </td>
                    <td>
                      <span className={`badge ${rate.active ? 'badge-active' : 'badge-inactive'}`}>
                        {rate.active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredTaxIds.length === 0 ? (
            <div className="empty-state">
              <h3>No tax IDs found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Tax ID</th>
                  <th>Customer</th>
                  <th>Type</th>
                  <th>Value</th>
                  <th>Verification</th>
                </tr>
              </thead>
              <tbody>
                {filteredTaxIds.map((taxId) => (
                  <tr key={taxId.id}>
                    <td className="mono">{taxId.id}</td>
                    <td>{taxId.customer}</td>
                    <td>
                      <span className="badge badge-active">{taxId.type.toUpperCase()}</span>
                    </td>
                    <td className="mono">{taxId.value}</td>
                    <td>
                      <span className={`badge badge-${taxId.verification}`}>
                        {taxId.verification}
                      </span>
                    </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;
