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 mockCoupons = [
  { id: 'coup_1', name: 'SUMMER2024', type: 'percent_off', value: 20, duration: 'once', timesRedeemed: 145, valid: true },
  { id: 'coup_2', name: 'WELCOME50', type: 'amount_off', value: 5000, duration: 'forever', timesRedeemed: 89, valid: true },
  { id: 'coup_3', name: 'ANNUAL25', type: 'percent_off', value: 25, duration: 'repeating', timesRedeemed: 67, valid: true },
  { id: 'coup_4', name: 'EXPIRED10', type: 'percent_off', value: 10, duration: 'once', timesRedeemed: 234, valid: false },
];

const mockPromoCodes = [
  { id: 'promo_1', code: 'SAVE20NOW', coupon: 'SUMMER2024', active: true, timesRedeemed: 45, maxRedemptions: 100 },
  { id: 'promo_2', code: 'FIRSTORDER', coupon: 'WELCOME50', active: true, timesRedeemed: 89, maxRedemptions: null },
  { id: 'promo_3', code: 'VIP25', coupon: 'ANNUAL25', active: false, timesRedeemed: 12, maxRedemptions: 50 },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredCoupons = useMemo(() => {
    return mockCoupons.filter((coupon) =>
      coupon.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      coupon.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const filteredPromoCodes = useMemo(() => {
    return mockPromoCodes.filter((promo) =>
      promo.code.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      promo.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalCoupons = mockCoupons.length;
    const validCoupons = mockCoupons.filter((c) => c.valid).length;
    const totalPromoCodes = mockPromoCodes.length;
    const activePromoCodes = mockPromoCodes.filter((p) => p.active).length;
    const totalRedemptions = mockCoupons.reduce((sum, c) => sum + c.timesRedeemed, 0);
    return { totalCoupons, validCoupons, totalPromoCodes, activePromoCodes, totalRedemptions };
  }, []);

  const handleViewChange = (newView: 'coupons' | 'promo_codes') => {
    startTransition(() => {
      setView(newView);
      show(`Switched to ${newView.replace('_', ' ')} view`, 'info');
    });
  };

  const formatDiscount = (type: string, value: number) => {
    if (type === 'percent_off') {
      return `${value}% off`;
    }
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value / 100);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Coupon Manager</h1>
        <p className="subtitle">Manage coupons, promotion codes, and usage tracking</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Coupons</div>
          <div className="stat-value">{stats.totalCoupons}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Valid Coupons</div>
          <div className="stat-value stat-success">{stats.validCoupons}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Promo Codes</div>
          <div className="stat-value stat-warning">{stats.activePromoCodes}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Redemptions</div>
          <div className="stat-value">{stats.totalRedemptions}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder={`Search ${view.replace('_', ' ')}...`}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          <button
            className={`filter-btn ${view === 'coupons' ? 'active' : ''}`}
            onClick={() => handleViewChange('coupons')}
          >
            Coupons
          </button>
          <button
            className={`filter-btn ${view === 'promo_codes' ? 'active' : ''}`}
            onClick={() => handleViewChange('promo_codes')}
          >
            Promo Codes
          </button>
        </div>
      </div>

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

      <div className="data-grid">
        {view === 'coupons' ? (
          filteredCoupons.length === 0 ? (
            <div className="empty-state">
              <h3>No coupons found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Coupon ID</th>
                  <th>Name</th>
                  <th>Discount</th>
                  <th>Duration</th>
                  <th>Times Redeemed</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredCoupons.map((coupon) => (
                  <tr key={coupon.id}>
                    <td className="mono">{coupon.id}</td>
                    <td><strong>{coupon.name}</strong></td>
                    <td>{formatDiscount(coupon.type, coupon.value)}</td>
                    <td>{coupon.duration.replace('_', ' ')}</td>
                    <td>{coupon.timesRedeemed}</td>
                    <td>
                      <span className={`badge ${coupon.valid ? 'badge-active' : 'badge-inactive'}`}>
                        {coupon.valid ? 'Valid' : 'Expired'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredPromoCodes.length === 0 ? (
            <div className="empty-state">
              <h3>No promo codes found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Promo Code ID</th>
                  <th>Code</th>
                  <th>Coupon</th>
                  <th>Redemptions</th>
                  <th>Max Redemptions</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredPromoCodes.map((promo) => (
                  <tr key={promo.id}>
                    <td className="mono">{promo.id}</td>
                    <td><strong>{promo.code}</strong></td>
                    <td>{promo.coupon}</td>
                    <td>{promo.timesRedeemed}</td>
                    <td>{promo.maxRedemptions || 'Unlimited'}</td>
                    <td>
                      <span className={`badge ${promo.active ? 'badge-active' : 'badge-inactive'}`}>
                        {promo.active ? 'Active' : 'Inactive'}
                      </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;
