import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { 
  TrendingUp, 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal, 
  Target, 
  DollarSign, 
  Users, 
  Calendar,
  ChevronRight,
  Clock,
  CheckCircle2,
  AlertCircle,
  Phone,
  Mail,
  TrendingDown,
  Trash2,
  Edit,
  ArrowRight,
  X,
  Download,
  Upload
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Project, Client } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

interface Deal {
  id: string;
  name: string;
  company: string;
  value: string;
  stage: 'Lead' | 'Qualified' | 'Proposal' | 'Negotiation' | 'Closed Won' | 'Closed Lost';
  probability: number;
  expectedClose: string;
  owner: string;
}


export function CRM() {
  const { projects, addProject, updateProject, deleteProject, clients, addClient } = useApp();
  const { hasPermission } = useAuth();
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const create = searchParams.get('create');
    if (create === 'true') {
      setIsDealModalOpen(true);
      const newParams = new URLSearchParams(searchParams);
      newParams.delete('create');
      setSearchParams(newParams, { replace: true });
    }
  }, [searchParams, setSearchParams]);
  const [view, setView] = useState<'list' | 'pipeline'>('list');
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [dealToDelete, setDealToDelete] = useState<{ id: string, name: string } | null>(null);
  const [isDealModalOpen, setIsDealModalOpen] = useState(false);
  const [editingDealId, setEditingDealId] = useState<string | null>(null);
  const [newDeal, setNewDeal] = useState<Partial<Project>>({
    name: '',
    client: '',
    status: 'Planning',
    deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    clientTotalAmount: 0,
    assignedTo: 'Unassigned'
  });
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterStage, setFilterStage] = useState('All');
  const [filterOwner, setFilterOwner] = useState('All');
  const menuRef = useRef<HTMLDivElement>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const filterRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setActiveMenu(null);
      }
      if (filterRef.current && !filterRef.current.contains(event.target as Node)) {
        setIsFilterOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleUpdateStage = async (projectId: string, stage: Deal['stage']) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    try {
      let status = 'Planning';
      switch (stage) {
        case 'Lead': status = 'Planning'; break;
        case 'Qualified': status = 'Pending'; break;
        case 'Proposal': status = 'In Progress'; break;
        case 'Negotiation': status = 'Active'; break;
        case 'Closed Won': status = 'Active'; break;
        case 'Closed Lost': status = 'Cancelled'; break;
      }

      const project = projects.find(p => p.id === projectId);
      
      if (stage === 'Closed Won' && project) {
        // Check if client exists
        const clientExists = clients.some(c => c.name === project.client);
        if (!clientExists) {
          const newClient: Client = {
            id: `CL-${Math.floor(Math.random() * 10000).toString().padStart(3, '0')}`,
            name: project.client,
            industry: 'Consulting', // Default
            contactPerson: project.personName || '',
            email: project.email || '',
            phone: project.contactNumber || '',
            status: 'Active',
            projects: 1,
            revenue: project.clientTotalAmount || 0
          };
          await addClient(newClient);
          toast.info(`New client "${project.client}" created`);
        }
      }

      await updateProject(projectId, { status });
      setActiveMenu(null);
      toast.success(`Deal moved to ${stage}`);
    } catch (error) {
      toast.error('Failed to update deal stage');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDeleteDeal = (projectId: string, name: string) => {
    setDealToDelete({ id: projectId, name });
    setIsDeleteModalOpen(true);
    setActiveMenu(null);
  };

  const confirmDelete = async () => {
    if (dealToDelete && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await deleteProject(dealToDelete.id);
        toast.error('Deal deleted');
        setIsDeleteModalOpen(false);
        setDealToDelete(null);
      } catch (error) {
        toast.error('Failed to delete deal');
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleSaveDeal = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;
    if (!newDeal.name || !newDeal.client) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSubmitting(true);
    try {
      if (editingDealId) {
        await updateProject(editingDealId, newDeal);
        toast.success('Deal updated successfully');
      } else {
        const id = `PRJ${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
        await addProject({
          ...newDeal,
          id,
          clientStatus: newDeal.status,
          team: 1,
          issueDate: new Date().toISOString().split('T')[0],
          issuedMonth: new Date().toISOString().substring(0, 7),
          engineerInvoiceStatus: 'Unpaid',
          clientInvoiceStatus: 'Unpaid'
        } as Project);
        toast.success('New deal added to pipeline');
      }
      setIsDealModalOpen(false);
      setEditingDealId(null);
      setNewDeal({
        name: '',
        client: '',
        status: 'Planning',
        deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        clientTotalAmount: 0,
        assignedTo: 'Unassigned'
      });
    } catch (error) {
      toast.error('Failed to save deal');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEditDeal = (deal: any) => {
    const project = projects.find(p => p.id === deal.id);
    if (project) {
      setEditingDealId(project.id);
      setNewDeal({ ...project });
      setIsDealModalOpen(true);
      setActiveMenu(null);
    }
  };

  const parseTotalTime = (timeStr?: string) => {
    if (!timeStr) return 0;
    const hoursMatch = timeStr.match(/(\d+)h/);
    const minsMatch = timeStr.match(/(\d+)m/);
    const hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
    const mins = minsMatch ? parseInt(minsMatch[1]) : 0;
    return hours + mins / 60;
  };

  const deals = useMemo(() => {
    return projects.map(p => {
      const hours = parseTotalTime(p.totalTime);
      const clientHourlyTotal = (p.clientHourlyRate || 0) * hours;
      const clientAmount = p.clientTotalAmount && p.clientTotalAmount > 0 ? p.clientTotalAmount : 
        (clientHourlyTotal + (p.clientTravelCost || 0) + (p.clientMaterialCost || 0) + (p.clientHalfDayRate || 0) + (p.clientFullDayRate || 0) + (p.clientMonthlyRate || 0));

      let stage: Deal['stage'] = 'Lead';
      let probability = 20;

      switch (p.status) {
        case 'Planning':
          stage = 'Lead';
          probability = 20;
          break;
        case 'Pending':
          stage = 'Qualified';
          probability = 40;
          break;
        case 'In Progress':
          stage = 'Proposal';
          probability = 60;
          break;
        case 'Work In Progress':
        case 'Active':
          stage = 'Negotiation';
          probability = 80;
          break;
        case 'Completed':
          stage = 'Closed Won';
          probability = 100;
          break;
        case 'Cancelled':
          stage = 'Closed Lost';
          probability = 0;
          break;
        default:
          stage = 'Lead';
          probability = 20;
      }

      return {
        id: p.id,
        name: p.name,
        company: p.client,
        value: `$${clientAmount.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`,
        numericValue: clientAmount,
        stage,
        probability,
        expectedClose: p.deadline,
        owner: p.assignedTo || 'Unassigned'
      };
    });
  }, [projects]);

  const handleExportCSV = () => {
    if (projects.length === 0) {
      toast.error('No deals to export');
      return;
    }

    const headers = ['ID', 'Name', 'Client', 'Status', 'Deadline', 'Value', 'Assigned To'];
    const csvRows = [
      headers.join(','),
      ...projects.map(p => [
        `"${p.id}"`,
        `"${p.name}"`,
        `"${p.client}"`,
        `"${p.status}"`,
        `"${p.deadline}"`,
        p.clientTotalAmount?.toFixed(2) || '0.00',
        `"${p.assignedTo || ''}"`
      ].join(','))
    ];

    const csvContent = csvRows.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `crm_deals_export_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success('CRM deals exported successfully');
  };

  const handleImportCSV = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || isSubmitting) return;

    setIsSubmitting(true);
    const reader = new FileReader();
    reader.onload = async (event) => {
      try {
        const text = event.target?.result as string;
        const rows = text.split('\n').filter(row => row.trim() !== '');
        if (rows.length < 2) {
          toast.error('Invalid CSV file format');
          return;
        }

        const newDeals: any[] = [];
        for (let i = 1; i < rows.length; i++) {
          const matches = rows[i].match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
          if (!matches || matches.length < 6) continue;

          const clean = (val: string) => val.replace(/^"|"$/g, '').trim();
          
          const deal = {
            id: clean(matches[0]),
            name: clean(matches[1]),
            client: clean(matches[2]),
            status: clean(matches[3]) as any,
            deadline: clean(matches[4]),
            clientTotalAmount: parseFloat(clean(matches[5])) || 0,
            assignedTo: clean(matches[6]) || 'Unassigned',
            issueDate: new Date().toISOString().split('T')[0],
            team: 1
          };
          newDeals.push(deal);
        }

        if (newDeals.length === 0) {
          toast.error('No valid data found in CSV');
          return;
        }

        const existingIds = new Set(projects.map(p => p.id));
        const uniqueNew = newDeals.filter(p => !existingIds.has(p.id));
        
        if (uniqueNew.length === 0) {
          toast.info('All records in CSV already exist');
        } else {
          for (const deal of uniqueNew) {
            await addProject(deal);
          }
          toast.success(`Successfully imported ${uniqueNew.length} new deals`);
        }
      } catch (error) {
        console.error('Import error:', error);
        toast.error('Failed to parse CSV file');
      } finally {
        setIsSubmitting(false);
        if (e.target) e.target.value = '';
      }
    };
    reader.readAsText(file);
  };

  const stats = useMemo(() => {
    let totalPipeline = 0;
    let weightedForecast = 0;
    let closedWonCount = 0;
    let activeLeadsCount = 0;

    deals.forEach(d => {
      if (d.stage !== 'Closed Won' && d.stage !== 'Closed Lost') {
        totalPipeline += d.numericValue;
        weightedForecast += (d.numericValue * d.probability) / 100;
      }
      
      if (d.stage === 'Closed Won') {
        closedWonCount++;
      }

      if (d.stage === 'Lead' || d.stage === 'Qualified') {
        activeLeadsCount++;
      }
    });

    const conversionRate = deals.length > 0 ? (closedWonCount / deals.length) * 100 : 0;

    return {
      totalPipeline,
      weightedForecast,
      conversionRate,
      activeLeadsCount
    };
  }, [deals]);

  const filteredDeals = deals.filter(d => {
    const matchesSearch = d.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      d.company.toLowerCase().includes(searchQuery.toLowerCase()) ||
      d.id.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesStage = filterStage === 'All' || d.stage === filterStage;
    const matchesOwner = filterOwner === 'All' || d.owner === filterOwner;
    
    return matchesSearch && matchesStage && matchesOwner;
  });

  const handleAddDeal = () => {
    setEditingDealId(null);
    setNewDeal({
      name: '',
      client: '',
      status: 'Planning',
      deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      clientTotalAmount: 0,
      assignedTo: 'Unassigned'
    });
    setIsDealModalOpen(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">CRM & Sales</h1>
          <p className="text-muted-foreground">Track leads, manage deals, and monitor your sales pipeline.</p>
        </div>
        <div className="flex items-center gap-2">
          {hasPermission('crm.create') && (
            <div className="relative">
              <input 
                type="file" 
                accept=".csv"
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                onChange={handleImportCSV}
              />
              <button className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors">
                <Upload size={18} />
                Import CSV
              </button>
            </div>
          )}
          {hasPermission('crm.export') && (
            <button 
              onClick={handleExportCSV}
              className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
            >
              <Download size={18} />
              Export CSV
            </button>
          )}
          <button 
            onClick={() => setView(view === 'list' ? 'pipeline' : 'list')}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            {view === 'list' ? 'Pipeline View' : 'List View'}
          </button>
          {hasPermission('crm.create') && (
            <button 
              onClick={handleAddDeal}
              className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
            >
              <Plus size={18} />
              Add Deal
            </button>
          )}
        </div>
      </div>

      {/* Sales Stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <SalesStatCard 
          title="Total Pipeline" 
          value={`$${stats.totalPipeline.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`} 
          icon={Target} 
          trend="+15% vs last month" 
          trendColor="text-green-500"
        />
        <SalesStatCard 
          title="Weighted Forecast" 
          value={`$${stats.weightedForecast.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`} 
          icon={DollarSign} 
          trend="Based on probability" 
        />
        <SalesStatCard 
          title="Conversion Rate" 
          value={`${stats.conversionRate.toFixed(1)}%`} 
          icon={TrendingUp} 
          trend="+2% from Q3" 
          trendColor="text-green-500"
        />
        <SalesStatCard 
          title="Active Leads" 
          value={stats.activeLeadsCount.toString()} 
          icon={Users} 
          trend="Open opportunities" 
          trendColor="text-blue-500"
        />
      </div>

      {/* Filters & Search */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
          <input
            type="text"
            placeholder="Search deals, companies, owners..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
          />
        </div>
        <div className="relative" ref={filterRef}>
          <button 
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={cn(
              "flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-accent",
              (filterStage !== 'All' || filterOwner !== 'All') && "border-primary text-primary"
            )}
          >
            <Filter size={18} />
            Filters
            {(filterStage !== 'All' || filterOwner !== 'All') && (
              <span className="flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground">
                {[filterStage, filterOwner].filter(f => f !== 'All').length}
              </span>
            )}
          </button>

          {isFilterOpen && (
            <div className="absolute right-0 mt-2 z-50 w-64 rounded-xl border border-border bg-card p-4 shadow-lg animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="flex items-center justify-between mb-4">
                <h4 className="font-bold text-sm">Filter Deals</h4>
                <button 
                  onClick={() => {
                    setFilterStage('All');
                    setFilterOwner('All');
                  }}
                  className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
                >
                  Reset
                </button>
              </div>
              
              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Stage</label>
                  <select 
                    value={filterStage}
                    onChange={(e) => setFilterStage(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Stages</option>
                    <option value="Lead">Lead</option>
                    <option value="Qualified">Qualified</option>
                    <option value="Proposal">Proposal</option>
                    <option value="Negotiation">Negotiation</option>
                    <option value="Closed Won">Closed Won</option>
                    <option value="Closed Lost">Closed Lost</option>
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Owner</label>
                  <select 
                    value={filterOwner}
                    onChange={(e) => setFilterOwner(e.target.value)}
                    className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="All">All Owners</option>
                    {Array.from(new Set(deals.map(d => d.owner))).map(owner => (
                      <option key={owner} value={owner}>{owner}</option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {view === 'list' ? (
        <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-muted/50 border-b border-border">
                <tr>
                  <th className="px-4 py-3 font-medium">Deal Name</th>
                  <th className="px-4 py-3 font-medium">Company</th>
                  <th className="px-4 py-3 font-medium">Value</th>
                  <th className="px-4 py-3 font-medium">Stage</th>
                  <th className="px-4 py-3 font-medium">Probability</th>
                  <th className="px-4 py-3 font-medium">Expected Close</th>
                  <th className="px-4 py-3 font-medium">Owner</th>
                  <th className="px-4 py-3 font-medium"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredDeals.map((deal) => (
                  <tr key={deal.id} className="hover:bg-accent/30 transition-colors group">
                    <td className="px-4 py-4">
                      <div>
                        <p className="font-medium group-hover:text-primary transition-colors">{deal.name}</p>
                        <p className="text-xs text-muted-foreground">{deal.id}</p>
                      </div>
                    </td>
                    <td className="px-4 py-4 text-muted-foreground">{deal.company}</td>
                    <td className="px-4 py-4 font-semibold">{deal.value}</td>
                    <td className="px-4 py-4">
                      <span className={cn(
                        "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",
                        deal.stage === 'Closed Won' ? "bg-green-500/10 text-green-500" :
                        deal.stage === 'Closed Lost' ? "bg-red-500/10 text-red-500" :
                        deal.stage === 'Negotiation' ? "bg-blue-500/10 text-blue-500" :
                        "bg-muted text-muted-foreground"
                      )}>
                        {deal.stage}
                      </span>
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-2">
                        <div className="h-1.5 w-16 rounded-full bg-muted overflow-hidden">
                          <div 
                            className="h-full bg-primary transition-all" 
                            style={{ width: `${deal.probability}%` }} 
                          />
                        </div>
                        <span className="text-xs font-medium">{deal.probability}%</span>
                      </div>
                    </td>
                    <td className="px-4 py-4 text-muted-foreground">{deal.expectedClose}</td>
                    <td className="px-4 py-4 text-muted-foreground">{deal.owner}</td>
                    <td className="px-4 py-4 text-right">
                      <div className="relative inline-block">
                        <button 
                          onClick={() => setActiveMenu(activeMenu === deal.id ? null : deal.id)}
                          className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                        >
                          <MoreHorizontal size={18} />
                        </button>
                        {activeMenu === deal.id && (
                          <div 
                            ref={menuRef}
                            className="absolute right-0 top-8 z-50 w-48 rounded-lg border border-border bg-card p-1 shadow-lg animate-in fade-in zoom-in duration-150"
                          >
                            {hasPermission('crm.edit') && (
                              <>
                                <button 
                                  onClick={() => handleEditDeal(deal)}
                                  className="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs hover:bg-accent transition-colors"
                                >
                                  <Edit size={14} className="text-muted-foreground" />
                                  Edit Deal
                                </button>
                                <div className="my-1 border-t border-border" />
                                <p className="px-3 py-1.5 text-[10px] font-bold uppercase text-muted-foreground tracking-wider">Move to Stage</p>
                                {(['Lead', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won', 'Closed Lost'] as Deal['stage'][]).map(s => (
                                  <button 
                                    key={s}
                                    disabled={isSubmitting}
                                    onClick={() => handleUpdateStage(deal.id, s)}
                                    className={cn(
                                      "flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs hover:bg-accent transition-colors disabled:opacity-50",
                                      deal.stage === s && "bg-primary/10 text-primary font-medium"
                                    )}
                                  >
                                    <ArrowRight size={14} className="text-muted-foreground" />
                                    {s}
                                  </button>
                                ))}
                                <div className="my-1 border-t border-border" />
                              </>
                            )}
                            {hasPermission('crm.delete') && (
                              <button 
                                disabled={isSubmitting}
                                onClick={() => handleDeleteDeal(deal.id, deal.name)}
                                className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-xs text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"
                              >
                                <Trash2 size={14} />
                                Delete Deal
                              </button>
                            )}
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <div className="grid gap-6 md:grid-cols-3 xl:grid-cols-4 overflow-x-auto pb-4">
          {['Lead', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won'].map((stage) => (
            <div key={stage} className="min-w-[280px] space-y-4">
              <div className="flex items-center justify-between px-2">
                <h3 className="font-semibold text-sm flex items-center gap-2">
                  {stage}
                  <span className="text-xs font-normal text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
                    {deals.filter(d => d.stage === stage).length}
                  </span>
                </h3>
              </div>
              <div className="space-y-3">
                {deals.filter(d => d.stage === stage).map((deal) => (
                  <div 
                    key={deal.id} 
                    className="rounded-xl border border-border bg-card p-4 shadow-sm hover:shadow-md transition-all cursor-pointer group"
                    onClick={() => toast.info(`Opening deal: ${deal.name}`)}
                  >
                    <div className="flex items-start justify-between mb-2">
                      <p className="font-medium text-sm group-hover:text-primary transition-colors">{deal.name}</p>
                      <div className="relative">
                        <button 
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveMenu(activeMenu === deal.id ? null : deal.id);
                          }}
                          className="rounded-md p-1 hover:bg-accent text-muted-foreground transition-colors"
                        >
                          <MoreHorizontal size={14} />
                        </button>
                        {activeMenu === deal.id && (
                          <div 
                            ref={menuRef}
                            className="absolute right-0 top-6 z-50 w-48 rounded-lg border border-border bg-card p-1 shadow-lg animate-in fade-in zoom-in duration-150"
                          >
                            <button 
                              onClick={(e) => {
                                e.stopPropagation();
                                handleEditDeal(deal);
                              }}
                              className="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs hover:bg-accent transition-colors"
                            >
                              <Edit size={14} className="text-muted-foreground" />
                              Edit Deal
                            </button>
                            <div className="my-1 border-t border-border" />
                            <p className="px-3 py-1.5 text-[10px] font-bold uppercase text-muted-foreground tracking-wider">Move to Stage</p>
                            {(['Lead', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won', 'Closed Lost'] as Deal['stage'][]).map(s => (
                              <button 
                                key={s}
                                disabled={isSubmitting}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleUpdateStage(deal.id, s);
                                }}
                                className={cn(
                                  "flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs hover:bg-accent transition-colors disabled:opacity-50",
                                  deal.stage === s && "bg-primary/10 text-primary font-medium"
                                )}
                              >
                                <ArrowRight size={14} className="text-muted-foreground" />
                                {s}
                              </button>
                            ))}
                            <div className="my-1 border-t border-border" />
                            <button 
                              disabled={isSubmitting}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDeleteDeal(deal.id, deal.name);
                              }}
                              className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-xs text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"
                            >
                              <Trash2 size={14} />
                              Delete Deal
                            </button>
                          </div>
                        )}
                      </div>
                    </div>
                    <p className="text-xs text-muted-foreground mb-3">{deal.company}</p>
                    <div className="flex items-center justify-between">
                      <p className="font-bold text-sm">{deal.value}</p>
                      <div className="flex items-center gap-1 text-[10px] text-muted-foreground">
                        <Clock size={10} />
                        <span>{deal.expectedClose}</span>
                      </div>
                    </div>
                    <div className="mt-3 pt-3 border-t border-border">
                      <p className="text-[10px] text-muted-foreground flex items-center gap-1">
                        <Users size={10} />
                        {deal.owner}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Deal Modal */}
      {isDealModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="bg-primary/5 border-b border-border p-6 flex items-center justify-between">
              <h2 className="text-xl font-bold">{editingDealId ? 'Edit Deal' : 'Add New Deal'}</h2>
              <button 
                onClick={() => {
                  setIsDealModalOpen(false);
                  setEditingDealId(null);
                }}
                className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSaveDeal} className="p-6 space-y-4">
              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Deal Name *</label>
                <input 
                  type="text" 
                  placeholder="e.g. Website Redesign"
                  value={newDeal.name || ''}
                  onChange={(e) => setNewDeal({...newDeal, name: e.target.value})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  required
                />
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Company *</label>
                <input 
                  type="text" 
                  placeholder="e.g. TechCorp"
                  value={newDeal.client || ''}
                  onChange={(e) => setNewDeal({...newDeal, client: e.target.value})}
                  className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Deal Value ($)</label>
                  <input 
                    type="number" 
                    placeholder="0"
                    value={newDeal.clientTotalAmount ?? 0}
                    onChange={(e) => setNewDeal({...newDeal, clientTotalAmount: parseFloat(e.target.value) || 0})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Stage</label>
                  <select 
                    value={newDeal.status || 'Planning'}
                    onChange={(e) => setNewDeal({...newDeal, status: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all appearance-none cursor-pointer"
                  >
                    <option value="Planning">Lead</option>
                    <option value="Pending">Qualified</option>
                    <option value="In Progress">Proposal</option>
                    <option value="Active">Negotiation</option>
                    <option value="Completed">Closed Won</option>
                    <option value="Cancelled">Closed Lost</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Expected Close</label>
                  <input 
                    type="date" 
                    value={newDeal.deadline || ''}
                    onChange={(e) => setNewDeal({...newDeal, deadline: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Owner</label>
                  <input 
                    type="text" 
                    placeholder="e.g. John Doe"
                    value={newDeal.assignedTo || ''}
                    onChange={(e) => setNewDeal({...newDeal, assignedTo: e.target.value})}
                    className="h-11 w-full rounded-xl border border-border bg-muted/20 px-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-background transition-all"
                  />
                </div>
              </div>

              <div className="pt-4 flex items-center gap-3">
                <button 
                  type="button"
                  disabled={isSubmitting}
                  onClick={() => {
                    setIsDealModalOpen(false);
                    setEditingDealId(null);
                  }}
                  className="flex-1 h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all disabled:opacity-50"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  disabled={isSubmitting}
                  className="flex-1 h-11 bg-primary text-sm font-bold text-primary-foreground rounded-xl hover:bg-primary/90 transition-all shadow-sm disabled:opacity-50"
                >
                  {isSubmitting ? 'Saving...' : (editingDealId ? 'Update Deal' : 'Create Deal')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div className="fixed inset-0 z-[110] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            <div className="p-6 space-y-4">
              <div className="flex items-center gap-3 text-destructive">
                <div className="p-2 rounded-full bg-destructive/10">
                  <AlertCircle size={24} />
                </div>
                <h2 className="text-xl font-bold">Delete Deal</h2>
              </div>
              <p className="text-sm text-muted-foreground">
                Are you sure you want to delete the deal <span className="font-bold text-foreground">"{dealToDelete?.name}"</span>? This action cannot be undone.
              </p>
              <div className="flex items-center gap-3 pt-2">
                <button 
                  onClick={() => {
                    setIsDeleteModalOpen(false);
                    setDealToDelete(null);
                  }}
                  className="flex-1 h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all"
                >
                  Cancel
                </button>
                <button 
                  onClick={confirmDelete}
                  disabled={isSubmitting}
                  className="flex-1 h-11 bg-destructive text-sm font-bold text-destructive-foreground rounded-xl hover:bg-destructive/90 transition-all shadow-sm disabled:opacity-50"
                >
                  {isSubmitting ? 'Deleting...' : 'Delete Deal'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SalesStatCard({ title, value, icon: Icon, trend, trendColor = "text-muted-foreground" }: { title: string, value: string, icon: any, trend: string, trendColor?: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <div className="p-2 rounded-lg bg-accent text-muted-foreground">
          <Icon size={18} />
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className={cn("text-xs mt-1", trendColor)}>{trend}</p>
      </div>
    </div>
  );
}
