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 mockDisputes = [
  { id: 'dp_1', paymentIntent: 'pi_123', amount: 5000, currency: 'usd', reason: 'fraudulent', status: 'needs_response', evidenceDueBy: Date.now() + 86400000 * 5, created: Date.now() - 86400000 * 2 },
  { id: 'dp_2', paymentIntent: 'pi_456', amount: 12000, currency: 'usd', reason: 'product_not_received', status: 'under_review', evidenceDueBy: Date.now() - 86400000 * 1, created: Date.now() - 86400000 * 10 },
  { id: 'dp_3', paymentIntent: 'pi_789', amount: 7500, currency: 'eur', reason: 'duplicate', status: 'won', evidenceDueBy: Date.now() - 86400000 * 20, created: Date.now() - 86400000 * 25 },
  { id: 'dp_4', paymentIntent: 'pi_012', amount: 3000, currency: 'usd', reason: 'subscription_canceled', status: 'lost', evidenceDueBy: Date.now() - 86400000 * 15, created: Date.now() - 86400000 * 30 },
];

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 filteredDisputes = useMemo(() => {
    return mockDisputes.filter((dispute) => {
      const matchesSearch = dispute.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        dispute.paymentIntent.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || dispute.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const open = mockDisputes.filter((d) => d.status === 'needs_response').length;
    const underReview = mockDisputes.filter((d) => d.status === 'under_review').length;
    const won = mockDisputes.filter((d) => d.status === 'won').length;
    const lost = mockDisputes.filter((d) => d.status === 'lost').length;
    return { open, underReview, won, lost };
  }, []);

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

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

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

  const getDaysUntilDeadline = (deadline: number) => {
    const days = Math.ceil((deadline - Date.now()) / 86400000);
    return days;
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Dispute Tracker</h1>
        <p className="subtitle">Monitor disputes, evidence status, and deadlines</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Needs Response</div>
          <div className="stat-value stat-danger">{stats.open}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Under Review</div>
          <div className="stat-value stat-warning">{stats.underReview}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Won</div>
          <div className="stat-value stat-success">{stats.won}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Lost</div>
          <div className="stat-value">{stats.lost}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search disputes..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'needs_response', 'under_review', 'won', 'lost'].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">
        {filteredDisputes.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" strokeWidth="2" />
              <line x1="12" y1="9" x2="12" y2="13" strokeWidth="2" />
              <line x1="12" y1="17" x2="12.01" y2="17" strokeWidth="2" />
            </svg>
            <h3>No disputes found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Dispute ID</th>
                <th>Payment Intent</th>
                <th>Amount</th>
                <th>Reason</th>
                <th>Status</th>
                <th>Evidence Due</th>
                <th>Deadline</th>
              </tr>
            </thead>
            <tbody>
              {filteredDisputes.map((dispute) => {
                const daysUntil = getDaysUntilDeadline(dispute.evidenceDueBy);
                return (
                  <tr key={dispute.id}>
                    <td className="mono">{dispute.id}</td>
                    <td className="mono">{dispute.paymentIntent}</td>
                    <td className="amount">{formatAmount(dispute.amount, dispute.currency)}</td>
                    <td>{dispute.reason.replace('_', ' ')}</td>
                    <td>
                      <span className={`badge badge-${dispute.status}`}>
                        {dispute.status.replace('_', ' ')}
                      </span>
                    </td>
                    <td className="date">{formatDate(dispute.evidenceDueBy)}</td>
                    <td>
                      <span className={`deadline ${daysUntil < 0 ? 'overdue' : daysUntil <= 3 ? 'urgent' : ''}`}>
                        {daysUntil < 0 ? `${Math.abs(daysUntil)}d overdue` : `${daysUntil}d left`}
                      </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;
