import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPipelineData, updateDeal } from '@/store/slices/pipelineSlice';
import { DealCard } from './DealCard';
import { LoadingSpinner } from '@/components/common/LoadingSpinner';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';

interface Deal {
  id: string;
  title: string;
  value: number;
  stage: string;
  probability: number;
  customer: {
    name: string;
    company: string;
  };
}

const SalesPipeline: React.FC = () => {
  const dispatch = useDispatch();
  const { deals, loading, error } = useSelector((state) => state.pipeline);
  const [draggedDeal, setDraggedDeal] = useState<Deal | null>(null);

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

  const handleDragStart = (deal: Deal) => {
    setDraggedDeal(deal);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = (stage: string) => {
    if (draggedDeal) {
      dispatch(updateDeal({ ...draggedDeal, stage }));
      setDraggedDeal(null);
    }
  };

  if (loading) return <LoadingSpinner />;
  if (error) return <div role="alert" className="text-red-500">Error: {error}</div>;

  const stages = ['Prospecting', 'Qualification', 'Proposal', 'Negotiation', 'Closed'];

  return (
    <ErrorBoundary>
      <div className="p-4">
        <h1 className="text-2xl font-bold mb-6">Sales Pipeline</h1>
        <div className="grid grid-cols-5 gap-4">
          {stages.map((stage) => (
            <div
              key={stage}
              className="bg-gray-100 p-4 rounded-lg"
              onDragOver={handleDragOver}
              onDrop={() => handleDrop(stage)}
            >
              <h2 className="font-semibold mb-4">{stage}</h2>
              {deals
                .filter((deal) => deal.stage === stage)
                .map((deal) => (
                  <DealCard
                    key={deal.id}
                    deal={deal}
                    onDragStart={() => handleDragStart(deal)}
                  />
                ))}
            </div>
          ))}
        </div>
      </div>
    </ErrorBoundary>
  );
};

export default SalesPipeline;