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 mockRefunds = [
  { id: 'ref_1', paymentIntent: 'pi_123', amount: 5000, status: 'succeeded', reason: 'requested_by_customer', created: Date.now() - 86400000 * 2 },
  { id: 'ref_2', paymentIntent: 'pi_456', amount: 12000, status: 'pending', reason: 'duplicate', created: Date.now() - 3600000 },
  { id: 'ref_3', paymentIntent: 'pi_789', amount: 7500, status: 'succeeded', reason: 'fraudulent', created: Date.now() - 86400000 * 5 },
  { id: 'ref_4', paymentIntent: 'pi_012', amount: 3000, status: 'failed', reason: 'requested_by_customer', created: Date.now() - 86400000 * 1 },
  { id: 'ref_5', paymentIntent: 'pi_345', amount: 15000, status: 'succeeded', reason: 'product_not_received', created: Date.now() - 86400000 * 10 },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredRefunds = useMemo(() => {
    return mockRefunds.filter((refund) => {
      const matchesSearch = refund.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        refund.paymentIntent.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || refund.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const totalRefunded = mockRefunds.filter((r) => r.status === 'succeeded').reduce((sum, r) => sum + r.amount, 0);
    const succeeded = mockRefunds.filter((r) => r.status === 'succeeded').length;
    const pending = mockRefunds.filter((r) => r.status === 'pending').length;
    const failed = mockRefunds.filter((r) => r.status === 'failed').length;
    return { totalRefunded, succeeded, pending, failed };
  }, []);

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

  const handleCreateRefund = () => {
    setShowCreateModal(true);
    show('Refund creation workflow started', '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">
        <div>
          <h1>Refund Manager</h1>
          <p className="subtitle">Process refunds and track refund history</p>
        </div>
        <button className="btn-primary" onClick={handleCreateRefund}>Create Refund</button>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Refunded</div>
          <div className="stat-value">{formatAmount(stats.totalRefunded)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Successful</div>
          <div className="stat-value stat-success">{stats.succeeded}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Pending</div>
          <div className="stat-value stat-warning">{stats.pending}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Failed</div>
          <div className="stat-value stat-danger">{stats.failed}</div>
        </div>
      </div>

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

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

      <div className="data-grid">
        {filteredRefunds.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M19 12H5M12 19l-7-7 7-7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <h3>No refunds found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Refund ID</th>
                <th>Payment Intent</th>
                <th>Amount</th>
                <th>Reason</th>
                <th>Status</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredRefunds.map((refund) => (
                <tr key={refund.id}>
                  <td className="mono">{refund.id}</td>
                  <td className="mono">{refund.paymentIntent}</td>
                  <td className="amount">{formatAmount(refund.amount)}</td>
                  <td>{refund.reason.replace(/_/g, ' ')}</td>
                  <td>
                    <span className={`badge badge-${refund.status}`}>{refund.status}</span>
                  </td>
                  <td className="date">{formatDate(refund.created)}</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;
