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 mockRadarRules = [
  { id: 'rule_1', name: 'Block high-risk cards', action: 'block', riskLevel: 'high', enabled: true, triggeredCount: 45 },
  { id: 'rule_2', name: 'Review suspicious activity', action: 'review', riskLevel: 'elevated', enabled: true, triggeredCount: 128 },
  { id: 'rule_3', name: 'Allow low-risk transactions', action: 'allow', riskLevel: 'normal', enabled: true, triggeredCount: 2450 },
  { id: 'rule_4', name: 'Block international cards', action: 'block', riskLevel: 'high', enabled: false, triggeredCount: 23 },
];

const mockBlockedPayments = [
  { id: 'ch_1', amount: 15000, riskScore: 95, riskLevel: 'highest', reason: 'high_risk_card', customer: 'unknown', created: Date.now() - 3600000 },
  { id: 'ch_2', amount: 8500, riskScore: 88, riskLevel: 'elevated', reason: 'suspicious_activity', customer: 'new_customer@example.com', created: Date.now() - 7200000 },
  { id: 'ch_3', amount: 12000, riskScore: 92, riskLevel: 'highest', reason: 'multiple_failed_attempts', customer: 'test@fraud.com', created: Date.now() - 10800000 },
  { id: 'ch_4', amount: 25000, riskScore: 98, riskLevel: 'highest', reason: 'stolen_card', customer: 'unknown', created: Date.now() - 14400000 },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredRules = useMemo(() => {
    return mockRadarRules.filter((rule) =>
      rule.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      rule.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const filteredBlocked = useMemo(() => {
    return mockBlockedPayments.filter((payment) =>
      payment.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      payment.reason.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalRules = mockRadarRules.length;
    const activeRules = mockRadarRules.filter((r) => r.enabled).length;
    const blockedPayments = mockBlockedPayments.length;
    const totalBlocked = mockBlockedPayments.reduce((sum, p) => sum + p.amount, 0);
    return { totalRules, activeRules, blockedPayments, totalBlocked };
  }, []);

  const handleViewChange = (newView: 'rules' | 'blocked') => {
    startTransition(() => {
      setView(newView);
      show(`Switched to ${newView} view`, '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).toLocaleString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Fraud Detection</h1>
        <p className="subtitle">Radar rules, risk scores, and blocked payments</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Active Rules</div>
          <div className="stat-value stat-success">{stats.activeRules}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Rules</div>
          <div className="stat-value">{stats.totalRules}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Blocked Payments</div>
          <div className="stat-value stat-danger">{stats.blockedPayments}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Blocked Amount</div>
          <div className="stat-value">{formatAmount(stats.totalBlocked)}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder={`Search ${view}...`}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          <button
            className={`filter-btn ${view === 'rules' ? 'active' : ''}`}
            onClick={() => handleViewChange('rules')}
          >
            Radar Rules
          </button>
          <button
            className={`filter-btn ${view === 'blocked' ? 'active' : ''}`}
            onClick={() => handleViewChange('blocked')}
          >
            Blocked Payments
          </button>
        </div>
      </div>

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

      <div className="data-grid">
        {view === 'rules' ? (
          filteredRules.length === 0 ? (
            <div className="empty-state">
              <h3>No Radar rules found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Rule ID</th>
                  <th>Name</th>
                  <th>Action</th>
                  <th>Risk Level</th>
                  <th>Triggered Count</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredRules.map((rule) => (
                  <tr key={rule.id}>
                    <td className="mono">{rule.id}</td>
                    <td><strong>{rule.name}</strong></td>
                    <td>
                      <span className={`badge badge-${rule.action}`}>{rule.action}</span>
                    </td>
                    <td>
                      <span className={`badge badge-${rule.riskLevel}`}>
                        {rule.riskLevel}
                      </span>
                    </td>
                    <td>{rule.triggeredCount}</td>
                    <td>
                      <span className={`badge ${rule.enabled ? 'badge-active' : 'badge-inactive'}`}>
                        {rule.enabled ? 'Enabled' : 'Disabled'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredBlocked.length === 0 ? (
            <div className="empty-state">
              <h3>No blocked payments found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Charge ID</th>
                  <th>Amount</th>
                  <th>Risk Score</th>
                  <th>Risk Level</th>
                  <th>Reason</th>
                  <th>Customer</th>
                  <th>Created</th>
                </tr>
              </thead>
              <tbody>
                {filteredBlocked.map((payment) => (
                  <tr key={payment.id}>
                    <td className="mono">{payment.id}</td>
                    <td className="amount">{formatAmount(payment.amount)}</td>
                    <td>
                      <span className={`risk-score ${payment.riskScore >= 90 ? 'risk-highest' : 'risk-elevated'}`}>
                        {payment.riskScore}
                      </span>
                    </td>
                    <td>
                      <span className={`badge badge-${payment.riskLevel}`}>
                        {payment.riskLevel}
                      </span>
                    </td>
                    <td>{payment.reason.replace(/_/g, ' ')}</td>
                    <td>{payment.customer}</td>
                    <td className="date">{formatDate(payment.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;
