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

interface Task {
  id: string;
  subject: string;
  status: 'Not Started' | 'In Progress' | 'Completed' | 'Deferred';
  priority: 'Low' | 'Normal' | 'High';
  dueDate: string;
  assignedTo: string;
  relatedTo: string;
  overdue: boolean;
}

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 mockTasks: Task[] = [
  { id: 't001', subject: 'Follow up with Acme Corp', status: 'Not Started', priority: 'High', dueDate: '2025-02-14', assignedTo: 'Jane Smith', relatedTo: 'Acme Corporation', overdue: false },
  { id: 't002', subject: 'Prepare proposal for Global Inc', status: 'In Progress', priority: 'High', dueDate: '2025-02-15', assignedTo: 'John Doe', relatedTo: 'Global Industries', overdue: false },
  { id: 't003', subject: 'Schedule demo call', status: 'Not Started', priority: 'Normal', dueDate: '2025-02-12', assignedTo: 'Alice Johnson', relatedTo: 'Tech Innovations', overdue: true },
  { id: 't004', subject: 'Send contract', status: 'Completed', priority: 'High', dueDate: '2025-02-10', assignedTo: 'Bob Wilson', relatedTo: 'Premier Services', overdue: false },
  { id: 't005', subject: 'Review quarterly goals', status: 'In Progress', priority: 'Normal', dueDate: '2025-02-20', assignedTo: 'Jane Smith', relatedTo: 'Internal', overdue: false },
  { id: 't006', subject: 'Update CRM data', status: 'Deferred', priority: 'Low', dueDate: '2025-02-11', assignedTo: 'Alice Johnson', relatedTo: 'Internal', overdue: true },
];

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

  const filteredTasks = useMemo(() => {
    return mockTasks.filter(task => {
      const matchesSearch = task.subject.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           task.relatedTo.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'All' || task.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockTasks.filter(t => t.status !== 'Completed').length,
    overdue: mockTasks.filter(t => t.overdue && t.status !== 'Completed').length,
    highPriority: mockTasks.filter(t => t.priority === 'High' && t.status !== 'Completed').length,
    completed: mockTasks.filter(t => t.status === 'Completed').length,
  }), []);

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

  const handleCompleteTask = (task: Task) => {
    show(`Marked "${task.subject}" as complete`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Task Center</h1>
        <p>Tasks, overdue alerts, and assignments</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Open Tasks</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Overdue</div>
          <div className="stat-value">{stats.overdue}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">High Priority</div>
          <div className="stat-value">{stats.highPriority}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Completed</div>
          <div className="stat-value">{stats.completed}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search tasks by subject or related to..."
          value={searchQuery}
          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="Not Started">Not Started</option>
          <option value="In Progress">In Progress</option>
          <option value="Completed">Completed</option>
          <option value="Deferred">Deferred</option>
        </select>
      </div>

      {filteredTasks.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">✅</div>
          <h3>No tasks found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Subject</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Due Date</th>
                <th>Assigned To</th>
                <th>Related To</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredTasks.map(task => (
                <tr key={task.id} className={task.overdue ? 'overdue-row' : ''}>
                  <td>
                    <strong>{task.subject}</strong>
                    {task.overdue && <span className="overdue-badge">⚠️ Overdue</span>}
                  </td>
                  <td><span className={`status-badge status-${task.status.toLowerCase().replace(/\s/g, '-')}`}>{task.status}</span></td>
                  <td><span className={`priority-badge priority-${task.priority.toLowerCase()}`}>{task.priority}</span></td>
                  <td>{task.dueDate}</td>
                  <td>{task.assignedTo}</td>
                  <td>{task.relatedTo}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleCompleteTask(task)}
                      disabled={task.status === 'Completed'}
                    >
                      {task.status === 'Completed' ? 'Done' : 'Complete'}
                    </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;
