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 mockSubscriptions = [
  { id: 'sub_1', customer: 'Acme Corp', plan: 'Pro Plan', amount: 9900, interval: 'month', status: 'active', currentPeriodEnd: Date.now() + 86400000 * 15 },
  { id: 'sub_2', customer: 'TechStart', plan: 'Enterprise', amount: 29900, interval: 'year', status: 'active', currentPeriodEnd: Date.now() + 86400000 * 200 },
  { id: 'sub_3', customer: 'Global Ventures', plan: 'Starter', amount: 2900, interval: 'month', status: 'trialing', currentPeriodEnd: Date.now() + 86400000 * 7 },
  { id: 'sub_4', customer: 'Startup Labs', plan: 'Pro Plan', amount: 9900, interval: 'month', status: 'past_due', currentPeriodEnd: Date.now() - 86400000 * 2 },
  { id: 'sub_5', customer: 'Innovation Hub', plan: 'Pro Plan', amount: 9900, interval: 'month', status: 'active', currentPeriodEnd: Date.now() + 86400000 * 20 },
  { id: 'sub_6', customer: 'Digital Agency', plan: 'Enterprise', amount: 29900, interval: 'month', status: 'canceled', currentPeriodEnd: Date.now() + 86400000 * 5 },
];

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 filteredSubscriptions = useMemo(() => {
    return mockSubscriptions.filter((sub) => {
      const matchesSearch =
        sub.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        sub.customer.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        sub.plan.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || sub.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const mrr = mockSubscriptions
      .filter((s) => s.status === 'active')
      .reduce((sum, s) => {
        const monthlyAmount = s.interval === 'year' ? s.amount / 12 : s.amount;
        return sum + monthlyAmount;
      }, 0);
    const active = mockSubscriptions.filter((s) => s.status === 'active').length;
    const trialing = mockSubscriptions.filter((s) => s.status === 'trialing').length;
    const pastDue = mockSubscriptions.filter((s) => s.status === 'past_due').length;
    return { mrr, active, trialing, pastDue };
  }, []);

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

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

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleDateString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Subscription Hub</h1>
        <p className="subtitle">Monitor subscriptions, MRR, and recurring revenue</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Monthly Recurring Revenue</div>
          <div className="stat-value">{formatAmount(stats.mrr)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Subscriptions</div>
          <div className="stat-value stat-success">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Trialing</div>
          <div className="stat-value stat-warning">{stats.trialing}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Past Due</div>
          <div className="stat-value stat-danger">{stats.pastDue}</div>
        </div>
      </div>

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

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

      <div className="data-grid">
        {filteredSubscriptions.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <rect x="3" y="8" width="18" height="4" rx="1" strokeWidth="2" />
              <path d="M12 8v13" strokeWidth="2" />
              <path d="M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7" strokeWidth="2" />
            </svg>
            <h3>No subscriptions found</h3>
            <p>Try adjusting your filters</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Subscription ID</th>
                <th>Customer</th>
                <th>Plan</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Next Billing</th>
              </tr>
            </thead>
            <tbody>
              {filteredSubscriptions.map((sub) => (
                <tr key={sub.id}>
                  <td className="mono">{sub.id}</td>
                  <td>{sub.customer}</td>
                  <td>{sub.plan}</td>
                  <td className="amount">{formatAmount(sub.amount)}/{sub.interval}</td>
                  <td>
                    <span className={`badge badge-${sub.status}`}>{sub.status.replace('_', ' ')}</span>
                  </td>
                  <td className="date">{formatDate(sub.currentPeriodEnd)}</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;
