import React, { useState, useMemo, useTransition, useEffect } from 'react';

interface Case {
  id: string;
  caseNumber: string;
  subject: string;
  status: 'New' | 'Working' | 'Escalated' | 'Closed';
  priority: 'Low' | 'Medium' | 'High' | 'Critical';
  accountName: string;
  contactName: string;
  slaViolation: boolean;
  createdDate: string;
}

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 }>>([]);
  const show = (message: string) => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockCases: Case[] = [
  { id: 'c001', caseNumber: '00001001', subject: 'Login Issue', status: 'New', priority: 'High', accountName: 'Acme Corp', contactName: 'Sarah Connor', slaViolation: false, createdDate: '2025-02-13' },
  { id: 'c002', caseNumber: '00001002', subject: 'Data Import Failed', status: 'Working', priority: 'Critical', accountName: 'Global Inc', contactName: 'Michael Scott', slaViolation: true, createdDate: '2025-02-12' },
  { id: 'c003', caseNumber: '00001003', subject: 'Feature Request', status: 'Working', priority: 'Low', accountName: 'TechStart', contactName: 'Jim Halpert', slaViolation: false, createdDate: '2025-02-11' },
  { id: 'c004', caseNumber: '00001004', subject: 'Integration Error', status: 'Escalated', priority: 'High', accountName: 'Premier LLC', contactName: 'Dwight Schrute', slaViolation: true, createdDate: '2025-02-10' },
  { id: 'c005', caseNumber: '00001005', subject: 'Password Reset', status: 'Closed', priority: 'Medium', accountName: 'Enterprise Solutions', contactName: 'Angela Martin', slaViolation: false, createdDate: '2025-02-09' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [priorityFilter, setPriorityFilter] = useState<string>('All');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredCases = useMemo(() => {
    return mockCases.filter(c => {
      const matchesSearch = c.subject.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           c.caseNumber.includes(debouncedSearch) ||
                           c.accountName.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesPriority = priorityFilter === 'All' || c.priority === priorityFilter;
      return matchesSearch && matchesPriority;
    });
  }, [debouncedSearch, priorityFilter]);

  const stats = useMemo(() => ({
    total: mockCases.filter(c => c.status !== 'Closed').length,
    critical: mockCases.filter(c => c.priority === 'Critical' && c.status !== 'Closed').length,
    slaViolations: mockCases.filter(c => c.slaViolation && c.status !== 'Closed').length,
    escalated: mockCases.filter(c => c.status === 'Escalated').length,
  }), []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  const handleViewCase = (caseItem: Case) => {
    show(`Viewing case ${caseItem.caseNumber}`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Case Manager</h1>
        <p>Support cases, priority, and SLA tracking</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Open Cases</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Critical</div>
          <div className="stat-value">{stats.critical}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">SLA Violations</div>
          <div className="stat-value">{stats.slaViolations}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Escalated</div>
          <div className="stat-value">{stats.escalated}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search cases by number, subject, or account..."
          value={searchQuery}
          onChange={handleSearch}
          className="search-input"
        />
        <select 
          value={priorityFilter} 
          onChange={(e) => setPriorityFilter(e.target.value)}
          className="filter-select"
        >
          <option value="All">All Priorities</option>
          <option value="Critical">Critical</option>
          <option value="High">High</option>
          <option value="Medium">Medium</option>
          <option value="Low">Low</option>
        </select>
      </div>

      {filteredCases.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🎫</div>
          <h3>No cases found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Case Number</th>
                <th>Subject</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Account</th>
                <th>Contact</th>
                <th>SLA</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredCases.map(caseItem => (
                <tr key={caseItem.id}>
                  <td><strong>{caseItem.caseNumber}</strong></td>
                  <td>{caseItem.subject}</td>
                  <td><span className={`status-badge status-${caseItem.status.toLowerCase()}`}>{caseItem.status}</span></td>
                  <td><span className={`priority-badge priority-${caseItem.priority.toLowerCase()}`}>{caseItem.priority}</span></td>
                  <td>{caseItem.accountName}</td>
                  <td>{caseItem.contactName}</td>
                  <td>{caseItem.slaViolation ? <span className="sla-violation">⚠️ Violation</span> : <span className="sla-ok">✓ OK</span>}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewCase(caseItem)}
                    >
                      View
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className="toast">{toast.message}</div>
        ))}
      </div>
    </div>
  );
};

export default App;
