import React, { useEffect, useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchSalesData } from '@/store/salesSlice';
import { SalesMetrics } from './SalesMetrics';
import { PipelineOverview } from './PipelineOverview';
import { LeadsList } from './LeadsList';

interface DashboardProps {
  agentId: string;
}

export const SalesAgentDashboard: React.FC<DashboardProps> = ({ agentId }) => {
  const dispatch = useDispatch();
  const { data, loading, error } = useSelector((state) => state.sales);

  useEffect(() => {
    dispatch(fetchSalesData(agentId));
  }, [dispatch, agentId]);

  const metrics = useMemo(() => {
    return data ? {
      totalLeads: data.leads.length,
      conversion: (data.closedDeals / data.totalDeals) * 100,
      revenue: data.totalRevenue
    } : null;
  }, [data]);

  if (loading) return <div role="alert" aria-busy="true" className="flex justify-center p-8">Loading dashboard...</div>;
  if (error) return <div role="alert" className="text-red-600 p-4">{error}</div>;

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-6">Sales Dashboard</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        <SalesMetrics metrics={metrics} />
        <PipelineOverview data={data?.pipeline} />
        <LeadsList leads={data?.leads} />
      </div>
    </div>
  );
};
