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

interface Form {
  id: string;
  name: string;
  type: 'contact' | 'lead' | 'survey';
  submissions: number;
  conversionRate: number;
  createdDate: string;
  status: 'active' | 'draft' | 'archived';
}

const mockForms: Form[] = [
  { id: '1', name: 'Contact Us Form', type: 'contact', submissions: 456, conversionRate: 34, createdDate: '2024-01-10', status: 'active' },
  { id: '2', name: 'Lead Capture', type: 'lead', submissions: 892, conversionRate: 42, createdDate: '2024-01-15', status: 'active' },
  { id: '3', name: 'Customer Feedback', type: 'survey', submissions: 234, conversionRate: 67, createdDate: '2024-02-01', status: 'active' },
  { id: '4', name: 'Newsletter Signup', type: 'contact', submissions: 1250, conversionRate: 78, createdDate: '2024-01-20', status: 'active' },
  { id: '5', name: 'Product Demo Request', type: 'lead', submissions: 145, conversionRate: 56, createdDate: '2024-02-05', status: 'draft' },
];

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

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredForms = useMemo(() => {
    if (!debouncedSearch) return mockForms;
    const term = debouncedSearch.toLowerCase();
    return mockForms.filter(f => f.name.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockForms.length,
    totalSubmissions: mockForms.reduce((sum, f) => sum + f.submissions, 0),
    active: mockForms.filter(f => f.status === 'active').length,
    avgConversion: (mockForms.reduce((sum, f) => sum + f.conversionRate, 0) / mockForms.length).toFixed(0),
  }), []);

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

  const handleSelectForm = (form: Form) => {
    setSelectedForm(form);
    addToast(`Viewing ${form.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Form Builder</h1>
        <p>Forms overview, submission counts, recent entries</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Forms</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Submissions</div>
          <div className="stat-value">{stats.totalSubmissions}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Forms</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Conversion</div>
          <div className="stat-value">{stats.avgConversion}%</div>
        </div>
      </div>

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

      {filteredForms.length === 0 ? (
        <div className="empty-state">
          <h3>No forms 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>Submissions</th>
                <th>Conversion Rate</th>
                <th>Status</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredForms.map(form => (
                <tr
                  key={form.id}
                  onClick={() => handleSelectForm(form)}
                  className={selectedForm?.id === form.id ? 'selected' : ''}
                >
                  <td>{form.name}</td>
                  <td>{form.type}</td>
                  <td>{form.submissions}</td>
                  <td>{form.conversionRate}%</td>
                  <td>
                    <span className={`status-badge status-${form.status}`}>
                      {form.status}
                    </span>
                  </td>
                  <td>{form.createdDate}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedForm && (
        <div className="detail-panel">
          <h3>Form Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedForm.name}</div>
            <div><strong>Type:</strong> {selectedForm.type}</div>
            <div><strong>Submissions:</strong> {selectedForm.submissions}</div>
            <div><strong>Conversion Rate:</strong> {selectedForm.conversionRate}%</div>
            <div><strong>Status:</strong> {selectedForm.status}</div>
            <div><strong>Created:</strong> {selectedForm.createdDate}</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;
