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

interface Ticket {
  id: string;
  subject: string;
  contact: string;
  status: 'new' | 'open' | 'pending' | 'resolved' | 'closed';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  created: string;
  updated: string;
}

const mockTickets: Ticket[] = [
  { id: '1', subject: 'Login issues', contact: 'John Doe', status: 'open', priority: 'high', created: '2024-02-10', updated: '2024-02-12' },
  { id: '2', subject: 'Feature request', contact: 'Jane Smith', status: 'new', priority: 'medium', created: '2024-02-13', updated: '2024-02-13' },
  { id: '3', subject: 'Billing question', contact: 'Bob Wilson', status: 'pending', priority: 'low', created: '2024-02-11', updated: '2024-02-12' },
  { id: '4', subject: 'Critical bug', contact: 'Alice Johnson', status: 'open', priority: 'urgent', created: '2024-02-12', updated: '2024-02-13' },
  { id: '5', subject: 'Account access', contact: 'Charlie Brown', status: 'resolved', priority: 'medium', created: '2024-02-09', updated: '2024-02-11' },
];

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;
};

interface Toast {
  id: number;
  message: string;
  type: 'success' | 'error' | 'info';
}

const useToast = () => {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const addToast = useCallback((message: string, type: Toast['type'] = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);
  return { toasts, addToast };
};

const App = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [priorityFilter, setPriorityFilter] = useState<string>('all');
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredTickets = useMemo(() => {
    let filtered = mockTickets;
    
    if (debouncedSearch) {
      const term = debouncedSearch.toLowerCase();
      filtered = filtered.filter(t =>
        t.subject.toLowerCase().includes(term) ||
        t.contact.toLowerCase().includes(term)
      );
    }
    
    if (statusFilter !== 'all') {
      filtered = filtered.filter(t => t.status === statusFilter);
    }
    
    if (priorityFilter !== 'all') {
      filtered = filtered.filter(t => t.priority === priorityFilter);
    }
    
    return filtered;
  }, [debouncedSearch, statusFilter, priorityFilter]);

  const stats = useMemo(() => ({
    total: mockTickets.length,
    new: mockTickets.filter(t => t.status === 'new').length,
    open: mockTickets.filter(t => t.status === 'open').length,
    urgent: mockTickets.filter(t => t.priority === 'urgent').length,
  }), []);

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

  const handleSelectTicket = (ticket: Ticket) => {
    setSelectedTicket(ticket);
    addToast(`Viewing ticket: ${ticket.subject}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Ticket Center</h1>
        <p>Manage support tickets and customer issues</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Tickets</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">New</div>
          <div className="stat-value">{stats.new}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Open</div>
          <div className="stat-value">{stats.open}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Urgent</div>
          <div className="stat-value">{stats.urgent}</div>
        </div>
      </div>

      <div className="filter-bar">
        <input
          type="text"
          placeholder="Search tickets..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="filter-select"
        >
          <option value="all">All Status</option>
          <option value="new">New</option>
          <option value="open">Open</option>
          <option value="pending">Pending</option>
          <option value="resolved">Resolved</option>
          <option value="closed">Closed</option>
        </select>
        <select
          value={priorityFilter}
          onChange={(e) => setPriorityFilter(e.target.value)}
          className="filter-select"
        >
          <option value="all">All Priority</option>
          <option value="low">Low</option>
          <option value="medium">Medium</option>
          <option value="high">High</option>
          <option value="urgent">Urgent</option>
        </select>
        {isPending && <span className="search-loading">Filtering...</span>}
      </div>

      {filteredTickets.length === 0 ? (
        <div className="empty-state">
          <h3>No tickets found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Subject</th>
                <th>Contact</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Created</th>
                <th>Updated</th>
              </tr>
            </thead>
            <tbody>
              {filteredTickets.map(ticket => (
                <tr
                  key={ticket.id}
                  onClick={() => handleSelectTicket(ticket)}
                  className={selectedTicket?.id === ticket.id ? 'selected' : ''}
                >
                  <td>{ticket.subject}</td>
                  <td>{ticket.contact}</td>
                  <td>
                    <span className={`status-badge status-${ticket.status}`}>
                      {ticket.status}
                    </span>
                  </td>
                  <td>
                    <span className={`priority-badge priority-${ticket.priority}`}>
                      {ticket.priority}
                    </span>
                  </td>
                  <td>{ticket.created}</td>
                  <td>{ticket.updated}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedTicket && (
        <div className="detail-panel">
          <h3>Ticket Details</h3>
          <div className="detail-grid">
            <div><strong>Subject:</strong> {selectedTicket.subject}</div>
            <div><strong>Contact:</strong> {selectedTicket.contact}</div>
            <div><strong>Status:</strong> {selectedTicket.status}</div>
            <div><strong>Priority:</strong> {selectedTicket.priority}</div>
            <div><strong>Created:</strong> {selectedTicket.created}</div>
            <div><strong>Last Updated:</strong> {selectedTicket.updated}</div>
          </div>
        </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;
