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

interface Campaign {
  id: string;
  name: string;
  type: 'Email' | 'Webinar' | 'Trade Show' | 'Social Media';
  status: 'Planned' | 'In Progress' | 'Completed';
  budgetedCost: number;
  actualCost: number;
  expectedRevenue: number;
  members: number;
  responses: number;
}

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 mockCampaigns: Campaign[] = [
  { id: 'cam001', name: 'Q1 Email Blast', type: 'Email', status: 'Completed', budgetedCost: 5000, actualCost: 4800, expectedRevenue: 50000, members: 1500, responses: 180 },
  { id: 'cam002', name: 'Product Launch Webinar', type: 'Webinar', status: 'In Progress', budgetedCost: 8000, actualCost: 7500, expectedRevenue: 120000, members: 450, responses: 320 },
  { id: 'cam003', name: 'Industry Conference 2025', type: 'Trade Show', status: 'Planned', budgetedCost: 25000, actualCost: 0, expectedRevenue: 300000, members: 0, responses: 0 },
  { id: 'cam004', name: 'LinkedIn Campaign', type: 'Social Media', status: 'In Progress', budgetedCost: 3000, actualCost: 2200, expectedRevenue: 35000, members: 2400, responses: 95 },
  { id: 'cam005', name: 'Partner Summit', type: 'Trade Show', status: 'Completed', budgetedCost: 15000, actualCost: 14200, expectedRevenue: 200000, members: 85, responses: 72 },
];

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 filteredCampaigns = useMemo(() => {
    return mockCampaigns.filter(campaign => {
      const matchesSearch = campaign.name.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'All' || campaign.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const active = mockCampaigns.filter(c => c.status !== 'Completed');
    return {
      total: mockCampaigns.length,
      active: active.length,
      totalMembers: mockCampaigns.reduce((sum, c) => sum + c.members, 0),
      avgROI: Math.round((mockCampaigns.reduce((sum, c) => sum + ((c.expectedRevenue - c.actualCost) / (c.actualCost || 1)), 0) / mockCampaigns.length) * 100),
    };
  }, []);

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

  const handleViewCampaign = (campaign: Campaign) => {
    show(`Viewing ${campaign.name}`);
  };

  const calculateROI = (campaign: Campaign) => {
    if (campaign.actualCost === 0) return 0;
    return Math.round(((campaign.expectedRevenue - campaign.actualCost) / campaign.actualCost) * 100);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Campaign Dashboard</h1>
        <p>Campaign ROI, members, and responses</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Campaigns</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 Members</div>
          <div className="stat-value">{stats.totalMembers.toLocaleString()}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg ROI</div>
          <div className="stat-value">{stats.avgROI}%</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search campaigns by name..."
          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="Planned">Planned</option>
          <option value="In Progress">In Progress</option>
          <option value="Completed">Completed</option>
        </select>
      </div>

      {filteredCampaigns.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📢</div>
          <h3>No campaigns found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Campaign Name</th>
                <th>Type</th>
                <th>Status</th>
                <th>Budget</th>
                <th>Actual Cost</th>
                <th>Expected Revenue</th>
                <th>Members</th>
                <th>Responses</th>
                <th>ROI</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredCampaigns.map(campaign => (
                <tr key={campaign.id}>
                  <td><strong>{campaign.name}</strong></td>
                  <td><span className={`type-badge type-${campaign.type.toLowerCase().replace(/\s/g, '-')}`}>{campaign.type}</span></td>
                  <td><span className={`status-badge status-${campaign.status.toLowerCase().replace(/\s/g, '-')}`}>{campaign.status}</span></td>
                  <td>${(campaign.budgetedCost / 1000).toFixed(1)}K</td>
                  <td>${(campaign.actualCost / 1000).toFixed(1)}K</td>
                  <td>${(campaign.expectedRevenue / 1000).toFixed(0)}K</td>
                  <td>{campaign.members}</td>
                  <td>{campaign.responses}</td>
                  <td><span className={calculateROI(campaign) > 100 ? 'roi-positive' : 'roi-neutral'}>{calculateROI(campaign)}%</span></td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewCampaign(campaign)}
                    >
                      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;
