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

interface Workflow {
  id: string;
  name: string;
  type: 'contact' | 'deal' | 'ticket';
  status: 'active' | 'inactive' | 'draft';
  enrolled: number;
  actions: number;
  lastRun: string;
}

const mockWorkflows: Workflow[] = [
  { id: '1', name: 'Lead Nurture Sequence', type: 'contact', status: 'active', enrolled: 1250, actions: 8, lastRun: '2024-02-13 10:00' },
  { id: '2', name: 'Deal Stage Notifications', type: 'deal', status: 'active', enrolled: 340, actions: 5, lastRun: '2024-02-13 09:30' },
  { id: '3', name: 'Support Ticket Assignment', type: 'ticket', status: 'active', enrolled: 892, actions: 3, lastRun: '2024-02-13 11:15' },
  { id: '4', name: 'Onboarding Email Series', type: 'contact', status: 'active', enrolled: 560, actions: 12, lastRun: '2024-02-13 08:00' },
  { id: '5', name: 'Abandoned Cart Recovery', type: 'deal', status: 'draft', enrolled: 0, actions: 6, lastRun: '-' },
];

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 [selectedWorkflow, setSelectedWorkflow] = useState<Workflow | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredWorkflows = useMemo(() => {
    if (!debouncedSearch) return mockWorkflows;
    const term = debouncedSearch.toLowerCase();
    return mockWorkflows.filter(w => w.name.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockWorkflows.length,
    active: mockWorkflows.filter(w => w.status === 'active').length,
    totalEnrolled: mockWorkflows.reduce((sum, w) => sum + w.enrolled, 0),
    totalActions: mockWorkflows.reduce((sum, w) => sum + w.actions, 0),
  }), []);

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

  const handleSelectWorkflow = (workflow: Workflow) => {
    setSelectedWorkflow(workflow);
    addToast(`Viewing ${workflow.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Workflow Manager</h1>
        <p>Automation workflows, status, enrollment counts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Workflows</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Enrolled</div>
          <div className="stat-value">{stats.totalEnrolled}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Actions</div>
          <div className="stat-value">{stats.totalActions}</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search workflows..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredWorkflows.length === 0 ? (
        <div className="empty-state">
          <h3>No workflows found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Status</th>
                <th>Enrolled</th>
                <th>Actions</th>
                <th>Last Run</th>
              </tr>
            </thead>
            <tbody>
              {filteredWorkflows.map(workflow => (
                <tr
                  key={workflow.id}
                  onClick={() => handleSelectWorkflow(workflow)}
                  className={selectedWorkflow?.id === workflow.id ? 'selected' : ''}
                >
                  <td>{workflow.name}</td>
                  <td>{workflow.type}</td>
                  <td>
                    <span className={`status-badge status-${workflow.status}`}>
                      {workflow.status}
                    </span>
                  </td>
                  <td>{workflow.enrolled.toLocaleString()}</td>
                  <td>{workflow.actions}</td>
                  <td>{workflow.lastRun}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedWorkflow && (
        <div className="detail-panel">
          <h3>Workflow Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedWorkflow.name}</div>
            <div><strong>Type:</strong> {selectedWorkflow.type}</div>
            <div><strong>Status:</strong> {selectedWorkflow.status}</div>
            <div><strong>Enrolled:</strong> {selectedWorkflow.enrolled.toLocaleString()}</div>
            <div><strong>Actions:</strong> {selectedWorkflow.actions}</div>
            <div><strong>Last Run:</strong> {selectedWorkflow.lastRun}</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;
