import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  ArrowLeft,
  Handshake,
  Users,
  Building2,
  Mail,
  Phone,
  Globe,
  Calendar,
  Clock,
  CheckCircle2,
  Circle,
  Plus,
  MoreHorizontal,
  Trash2,
  Pencil,
  FileText,
  Loader2,
  MessageSquare,
  CalendarPlus,
  ChevronDown,
  ChevronRight,
  StickyNote,
  ClipboardList,
  Presentation,
} from "lucide-react";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { PHASE_CONFIG, PHASE_OPTIONS } from "@/lib/phase-config";
import { cn } from "@/lib/utils";

// ============================================================================
// Types
// ============================================================================

interface Note {
  id?: number;
  name?: string;
  createdAt?: string;
}

interface Activity {
  id?: number;
  name?: string;
  type?: string;
  plannedAt?: string;
  doneAt?: string;
  createdAt?: string;
  notes?: Note[];
}

interface Company {
  id?: number;
  name?: string;
  website?: string;
  notes?: string;
}

interface Contact {
  id?: number;
  firstName?: string;
  lastName?: string;
  mail?: string;
  phone1?: string;
  phone2?: string;
  notes?: string;
  company?: Company[];
}

interface Deal {
  id?: number;
  name?: string;
  phase?: string;
  notes?: string;
  lostReason?: string;
  mainContact?: Contact[];
  activities?: Activity[];
  createdAt?: string;
  updatedAt?: string;
}

// ============================================================================
// Helper Functions
// ============================================================================

function formatContactName(contact: Contact): string {
  const parts = [contact.firstName, contact.lastName].filter(Boolean);
  return parts.join(" ") || "Unknown";
}

function formatDate(dateStr?: string): string {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

function formatDateTime(dateStr?: string): string {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
  });
}

function formatRelativeDate(dateStr?: string): string {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  const now = new Date();
  const diffTime = date.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 0) return "Today";
  if (diffDays === 1) return "Tomorrow";
  if (diffDays === -1) return "Yesterday";
  if (diffDays > 0 && diffDays <= 7) return `In ${diffDays} days`;
  if (diffDays < 0 && diffDays >= -7) return `${Math.abs(diffDays)} days ago`;
  return formatDate(dateStr);
}

function isOverdue(plannedAt?: string, doneAt?: string): boolean {
  if (!plannedAt || doneAt) return false;
  return new Date(plannedAt) < new Date();
}

// ============================================================================
// Activity Card Component
// ============================================================================

interface ActivityCardProps {
  activity: Activity;
  onComplete: (id: number) => void;
  onUncomplete: (id: number) => void;
  onEdit: (activity: Activity) => void;
  onDelete: (id: number) => void;
  onAddNote: (activityId: number) => void;
  isCompleting?: boolean;
  expanded: boolean;
  onToggleExpand: () => void;
}

function ActivityCard({
  activity,
  onComplete,
  onUncomplete,
  onEdit,
  onDelete,
  onAddNote,
  isCompleting,
  expanded,
  onToggleExpand,
}: ActivityCardProps) {
  const isComplete = !!activity.doneAt;
  const overdue = isOverdue(activity.plannedAt, activity.doneAt);
  const hasNotes = activity.notes && activity.notes.length > 0;
  const TypeIcon = getActivityTypeIcon(activity.type);
  const typeColor = activity.type ? typeColors[activity.type] : "";

  return (
    <div
      className={cn(
        "group border rounded-lg transition-all",
        isComplete
          ? "bg-muted/30 border-muted"
          : overdue
          ? "bg-red-50/50 border-red-200 dark:bg-red-950/20 dark:border-red-800"
          : "bg-background hover:border-primary/30"
      )}
    >
      <div className="p-4">
        <div className="flex items-start gap-3">
          {/* Completion Toggle */}
          <button
            onClick={() =>
              activity.id &&
              (isComplete ? onUncomplete(activity.id) : onComplete(activity.id))
            }
            disabled={isCompleting}
            className={cn(
              "mt-0.5 flex-shrink-0 transition-colors",
              isComplete
                ? "text-green-500 hover:text-green-600"
                : overdue
                ? "text-red-400 hover:text-red-500"
                : "text-muted-foreground hover:text-primary"
            )}
          >
            {isCompleting ? (
              <Loader2 className="h-5 w-5 animate-spin" />
            ) : isComplete ? (
              <CheckCircle2 className="h-5 w-5" />
            ) : (
              <Circle className="h-5 w-5" />
            )}
          </button>

          {/* Activity Content */}
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2">
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <p
                    className={cn(
                      "font-medium",
                      isComplete && "line-through text-muted-foreground"
                    )}
                  >
                    {activity.name || "Untitled Activity"}
                  </p>
                  {activity.type && (
                    <span
                      className={cn(
                        "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border",
                        typeColor
                      )}
                    >
                      <TypeIcon className="h-3 w-3" />
                      {activity.type}
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-3 mt-1">
                  {activity.plannedAt && (
                    <span
                      className={cn(
                        "text-sm flex items-center gap-1",
                        isComplete
                          ? "text-muted-foreground"
                          : overdue
                          ? "text-red-500 font-medium"
                          : "text-muted-foreground"
                      )}
                    >
                      <Calendar className="h-3.5 w-3.5" />
                      {formatRelativeDate(activity.plannedAt)}
                    </span>
                  )}
                  {isComplete && activity.doneAt && (
                    <span className="text-sm text-green-600 flex items-center gap-1">
                      <CheckCircle2 className="h-3.5 w-3.5" />
                      Completed {formatRelativeDate(activity.doneAt)}
                    </span>
                  )}
                </div>
              </div>

              {/* Actions */}
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0"
                  onClick={() => activity.id && onAddNote(activity.id)}
                >
                  <StickyNote className="h-4 w-4" />
                </Button>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => onEdit(activity)}>
                      <Pencil className="h-4 w-4 mr-2" />
                      Edit
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-destructive"
                      onClick={() => activity.id && onDelete(activity.id)}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Delete
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>

            {/* Notes Section */}
            {hasNotes && (
              <div className="mt-3">
                <button
                  onClick={onToggleExpand}
                  className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
                >
                  {expanded ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronRight className="h-4 w-4" />
                  )}
                  <MessageSquare className="h-3.5 w-3.5" />
                  {activity.notes?.length} note{activity.notes?.length !== 1 && "s"}
                </button>
                {expanded && (
                  <div className="mt-2 space-y-2 pl-5 border-l-2 border-muted">
                    {activity.notes?.map((note) => (
                      <div
                        key={note.id}
                        className="p-2 bg-muted/50 rounded text-sm"
                      >
                        <p>{note.name}</p>
                        <p className="text-xs text-muted-foreground mt-1">
                          {formatDateTime(note.createdAt)}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// Contact Info Card Component
// ============================================================================

interface ContactInfoCardProps {
  contact: Contact;
  onViewContact?: () => void;
}

function ContactInfoCard({ contact, onViewContact }: ContactInfoCardProps) {
  const company = contact.company?.[0];

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="p-2 rounded-lg bg-blue-500/10">
              <Users className="h-4 w-4 text-blue-500" />
            </div>
            <CardTitle className="text-base">Contact</CardTitle>
          </div>
          {onViewContact && (
            <Button variant="ghost" size="sm" onClick={onViewContact}>
              View
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <div>
          <p className="font-semibold text-lg">{formatContactName(contact)}</p>
          {company && (
            <p className="text-sm text-muted-foreground flex items-center gap-1.5 mt-0.5">
              <Building2 className="h-3.5 w-3.5" />
              {company.name}
            </p>
          )}
        </div>

        <div className="space-y-2">
          {contact.mail && (
            <a
              href={`mailto:${contact.mail}`}
              className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <Mail className="h-4 w-4" />
              {contact.mail}
            </a>
          )}
          {contact.phone1 && (
            <a
              href={`tel:${contact.phone1}`}
              className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <Phone className="h-4 w-4" />
              {contact.phone1}
            </a>
          )}
          {contact.phone2 && (
            <a
              href={`tel:${contact.phone2}`}
              className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <Phone className="h-4 w-4" />
              {contact.phone2}
            </a>
          )}
        </div>

        {contact.notes && (
          <div className="pt-2 border-t">
            <p className="text-xs text-muted-foreground mb-1">Notes</p>
            <p className="text-sm">{contact.notes}</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// ============================================================================
// Company Info Card Component
// ============================================================================

interface CompanyInfoCardProps {
  company: Company;
  onViewCompany?: () => void;
}

function CompanyInfoCard({ company, onViewCompany }: CompanyInfoCardProps) {
  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="p-2 rounded-lg bg-purple-500/10">
              <Building2 className="h-4 w-4 text-purple-500" />
            </div>
            <CardTitle className="text-base">Company</CardTitle>
          </div>
          {onViewCompany && (
            <Button variant="ghost" size="sm" onClick={onViewCompany}>
              View
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        <p className="font-semibold text-lg">{company.name}</p>

        {company.website && (
          <a
            href={
              company.website.startsWith("http")
                ? company.website
                : `https://${company.website}`
            }
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
          >
            <Globe className="h-4 w-4" />
            {company.website}
          </a>
        )}

        {company.notes && (
          <div className="pt-2 border-t">
            <p className="text-xs text-muted-foreground mb-1">Notes</p>
            <p className="text-sm">{company.notes}</p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// ============================================================================
// Activity Dialog Component
// ============================================================================

interface ActivityDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  activity?: Activity | null;
  dealId: number;
  onSuccess: () => void;
}

// Activity types with icons
const activityTypes = [
  { value: "Call", label: "Call", icon: Phone },
  { value: "Meeting", label: "Meeting", icon: Users },
  { value: "Task", label: "Task", icon: ClipboardList },
  { value: "Demo", label: "Demo", icon: Presentation },
] as const;

type ActivityType = (typeof activityTypes)[number]["value"];

// Activity type colors for badges
const typeColors: Record<string, string> = {
  Call: "bg-blue-500/10 text-blue-600 border-blue-500/20",
  Meeting: "bg-purple-500/10 text-purple-600 border-purple-500/20",
  Task: "bg-amber-500/10 text-amber-600 border-amber-500/20",
  Demo: "bg-emerald-500/10 text-emerald-600 border-emerald-500/20",
};

// Get icon for activity type
function getActivityTypeIcon(type?: string) {
  const found = activityTypes.find(t => t.value === type);
  return found?.icon || ClipboardList;
}

function ActivityDialog({
  open,
  onOpenChange,
  activity,
  dealId,
  onSuccess,
}: ActivityDialogProps) {
  const isCreateMode = !activity;
  const [name, setName] = useState("");
  const [type, setType] = useState<ActivityType | "">("");
  const [plannedAt, setPlannedAt] = useState("");
  const [isInitialized, setIsInitialized] = useState(false);

  // Initialize/reset form when dialog opens or activity changes
  if (open && !isInitialized) {
    if (activity) {
      setName(activity.name || "");
      setType((activity.type as ActivityType) || "");
      setPlannedAt(activity.plannedAt ? activity.plannedAt.split("T")[0] : "");
    } else {
      setName("");
      setType("");
      setPlannedAt("");
    }
    setIsInitialized(true);
  }

  // Reset initialization flag when dialog closes
  if (!open && isInitialized) {
    setIsInitialized(false);
  }

  const handleOpenChange = (newOpen: boolean) => {
    onOpenChange(newOpen);
  };

  const createMutation = trpc.activities.create.useMutation({
    onSuccess: () => {
      onSuccess();
      onOpenChange(false);
    },
  });

  const updateMutation = trpc.activities.update.useMutation({
    onSuccess: () => {
      onSuccess();
      onOpenChange(false);
    },
  });

  const handleSave = () => {
    if (isCreateMode) {
      if (name.trim() && type) {
        createMutation.mutate({
          name,
          type: type as ActivityType,
          deal: [dealId],
          plannedAt: plannedAt || undefined,
        });
      }
    } else if (activity?.id) {
      updateMutation.mutate({
        id: activity.id,
        name,
        type: type as ActivityType || undefined,
        plannedAt: plannedAt || undefined,
      });
    }
  };

  const isPending = createMutation.isPending || updateMutation.isPending;
  const canSave = isCreateMode ? name.trim() && type : name.trim();

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {isCreateMode ? "New Activity" : "Edit Activity"}
          </DialogTitle>
          <DialogDescription>
            {isCreateMode
              ? "Create a new activity for this deal"
              : "Update the activity details"}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="activity-name">Activity Name *</Label>
            <Input
              id="activity-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g., Follow-up call, Send proposal..."
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="activity-type">Type *</Label>
            <Select
              value={type}
              onValueChange={(val) => setType(val as ActivityType)}
            >
              <SelectTrigger id="activity-type">
                <SelectValue placeholder="Select activity type..." />
              </SelectTrigger>
              <SelectContent>
                {activityTypes.map((t) => {
                  const Icon = t.icon;
                  return (
                    <SelectItem key={t.value} value={t.value}>
                      <span className="flex items-center gap-2">
                        <Icon className="h-4 w-4" />
                        {t.label}
                      </span>
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="planned-at">Planned Date</Label>
            <Input
              id="planned-at"
              type="date"
              value={plannedAt}
              onChange={(e) => setPlannedAt(e.target.value)}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={isPending || !canSave}>
            {isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
            {isCreateMode ? "Create" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ============================================================================
// Note Dialog Component
// ============================================================================

interface NoteDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  activityId: number | null;
  onSuccess: () => void;
}

function NoteDialog({ open, onOpenChange, activityId, onSuccess }: NoteDialogProps) {
  const [content, setContent] = useState("");

  const createMutation = trpc.notes.create.useMutation({
    onSuccess: () => {
      setContent("");
      onSuccess();
      onOpenChange(false);
    },
  });

  const handleSave = () => {
    if (activityId && content.trim()) {
      createMutation.mutate({
        name: content,
        activities1: [activityId],
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Add Note</DialogTitle>
          <DialogDescription>
            Add a note to this activity
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          <Textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="Write your note here..."
            className="min-h-[120px]"
          />
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleSave}
            disabled={createMutation.isPending || !content.trim()}
          >
            {createMutation.isPending && (
              <Loader2 className="h-4 w-4 animate-spin mr-2" />
            )}
            Add Note
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ============================================================================
// Phase Badge Component
// ============================================================================

function PhaseBadgeDisplay({ phase }: { phase: string }) {
  const config = PHASE_CONFIG[phase];
  if (!config) return <Badge variant="outline">{phase}</Badge>;

  const Icon = config.icon;

  return (
    <div
      className={cn(
        "inline-flex items-center gap-2 px-3 py-1.5 rounded-full",
        config.bgColor
      )}
    >
      <Icon className={cn("h-4 w-4", config.color)} />
      <span className={cn("font-medium", config.color)}>{config.label}</span>
    </div>
  );
}

// ============================================================================
// Main Page Component
// ============================================================================

export default function DealDetailsPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dealId = id ? parseInt(id, 10) : null;

  // Activity management state
  const [activityDialogOpen, setActivityDialogOpen] = useState(false);
  const [editingActivity, setEditingActivity] = useState<Activity | null>(null);
  const [noteDialogOpen, setNoteDialogOpen] = useState(false);
  const [noteActivityId, setNoteActivityId] = useState<number | null>(null);
  const [expandedActivities, setExpandedActivities] = useState<Set<number>>(
    new Set()
  );
  const [completingActivityId, setCompletingActivityId] = useState<number | null>(
    null
  );

  // Edit deal state
  const [isEditingPhase, setIsEditingPhase] = useState(false);

  // Data fetching
  const {
    data: dealData,
    isLoading,
    refetch,
  } = trpc.deals.getDetails.useQuery(
    { id: dealId! },
    { enabled: !!dealId }
  );

  const deal = dealData as Deal | null | undefined;

  // Mutations
  const completeMutation = trpc.activities.complete.useMutation({
    onSuccess: () => {
      setCompletingActivityId(null);
      refetch();
    },
  });

  const uncompleteMutation = trpc.activities.uncomplete.useMutation({
    onSuccess: () => {
      setCompletingActivityId(null);
      refetch();
    },
  });

  const deleteActivityMutation = trpc.activities.delete.useMutation({
    onSuccess: () => refetch(),
  });

  const updateDealMutation = trpc.deals.update.useMutation({
    onSuccess: () => {
      setIsEditingPhase(false);
      refetch();
    },
  });

  // Handlers
  const handleComplete = (activityId: number) => {
    setCompletingActivityId(activityId);
    completeMutation.mutate({ id: activityId });
  };

  const handleUncomplete = (activityId: number) => {
    setCompletingActivityId(activityId);
    uncompleteMutation.mutate({ id: activityId });
  };

  const handleDeleteActivity = (activityId: number) => {
    if (confirm("Are you sure you want to delete this activity?")) {
      deleteActivityMutation.mutate({ id: activityId });
    }
  };

  const handleEditActivity = (activity: Activity) => {
    setEditingActivity(activity);
    setActivityDialogOpen(true);
  };

  const handleAddNote = (activityId: number) => {
    setNoteActivityId(activityId);
    setNoteDialogOpen(true);
  };

  const toggleActivityExpand = (activityId: number) => {
    setExpandedActivities((prev) => {
      const next = new Set(prev);
      if (next.has(activityId)) {
        next.delete(activityId);
      } else {
        next.add(activityId);
      }
      return next;
    });
  };

  const handlePhaseChange = (newPhase: string) => {
    if (dealId) {
      updateDealMutation.mutate({
        id: dealId,
        phase: newPhase as "New" | "Demo scheduled" | "Contract signed" | "Lost",
      });
    }
  };

  // Separate activities into pending and completed
  const pendingActivities =
    deal?.activities?.filter((a) => !a.doneAt) || [];
  const completedActivities =
    deal?.activities?.filter((a) => a.doneAt) || [];

  // Get contact and company
  const contact = deal?.mainContact?.[0];
  const company = contact?.company?.[0];

  if (!dealId) {
    return (
      <div className="container mx-auto p-6 max-w-7xl">
        <p className="text-muted-foreground">Invalid deal ID</p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="container mx-auto p-6 max-w-7xl">
        <div className="flex items-center justify-center py-20">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      </div>
    );
  }

  if (!deal) {
    return (
      <div className="container mx-auto p-6 max-w-7xl">
        <p className="text-muted-foreground">Deal not found</p>
        <Button variant="link" onClick={() => navigate("/deals")} className="mt-2">
          Back to Deals
        </Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-7xl space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        {/* Left side - Back button and title */}
        <div className="flex items-start gap-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => navigate("/deals")}
            className="mt-1"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-xl bg-gradient-to-br from-primary/20 to-primary/5 border border-primary/20">
              <Handshake className="h-6 w-6 text-primary" />
            </div>
            <h1 className="text-2xl font-bold">{deal.name}</h1>
          </div>
        </div>

        {/* Right side - Phase and metadata */}
        <div className="flex items-center gap-4">
          {isEditingPhase ? (
            <Select
              value={deal.phase || "New"}
              onValueChange={(value) => {
                handlePhaseChange(value);
              }}
            >
              <SelectTrigger className="w-[200px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {PHASE_OPTIONS.map((option) => {
                  const config = PHASE_CONFIG[option];
                  const Icon = config.icon;
                  return (
                    <SelectItem key={option} value={option}>
                      <div className="flex items-center gap-2">
                        <Icon className={cn("h-4 w-4", config.color)} />
                        <span>{config.label}</span>
                      </div>
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
          ) : (
            <button
              onClick={() => setIsEditingPhase(true)}
              className="hover:opacity-80 transition-opacity"
            >
              <PhaseBadgeDisplay phase={deal.phase || "New"} />
            </button>
          )}
          <span className="text-sm text-muted-foreground">
            Created {formatDate(deal.createdAt)}
          </span>
        </div>
      </div>

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Activities */}
        <div className="lg:col-span-2 space-y-6">
          {/* Activities Section */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <CalendarPlus className="h-5 w-5 text-primary" />
                  <CardTitle className="text-lg">Activities</CardTitle>
                  <Badge variant="secondary" className="ml-2">
                    {pendingActivities.length} pending
                  </Badge>
                </div>
                <Button
                  onClick={() => {
                    setEditingActivity(null);
                    setActivityDialogOpen(true);
                  }}
                  size="sm"
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Add Activity
                </Button>
              </div>
              <CardDescription>
                Manage tasks and follow-ups for this deal
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Tabs defaultValue="pending" className="w-full">
                <TabsList className="mb-4">
                  <TabsTrigger value="pending" className="gap-2">
                    <Clock className="h-4 w-4" />
                    Pending ({pendingActivities.length})
                  </TabsTrigger>
                  <TabsTrigger value="completed" className="gap-2">
                    <CheckCircle2 className="h-4 w-4" />
                    Completed ({completedActivities.length})
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="pending" className="space-y-3">
                  {pendingActivities.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground">
                      <Calendar className="h-12 w-12 mx-auto mb-3 opacity-20" />
                      <p>No pending activities</p>
                      <Button
                        variant="link"
                        onClick={() => {
                          setEditingActivity(null);
                          setActivityDialogOpen(true);
                        }}
                        className="mt-2"
                      >
                        Create your first activity
                      </Button>
                    </div>
                  ) : (
                    pendingActivities.map((activity) => (
                      <ActivityCard
                        key={activity.id}
                        activity={activity}
                        onComplete={handleComplete}
                        onUncomplete={handleUncomplete}
                        onEdit={handleEditActivity}
                        onDelete={handleDeleteActivity}
                        onAddNote={handleAddNote}
                        isCompleting={completingActivityId === activity.id}
                        expanded={expandedActivities.has(activity.id || 0)}
                        onToggleExpand={() =>
                          activity.id && toggleActivityExpand(activity.id)
                        }
                      />
                    ))
                  )}
                </TabsContent>

                <TabsContent value="completed" className="space-y-3">
                  {completedActivities.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground">
                      <CheckCircle2 className="h-12 w-12 mx-auto mb-3 opacity-20" />
                      <p>No completed activities yet</p>
                    </div>
                  ) : (
                    completedActivities.map((activity) => (
                      <ActivityCard
                        key={activity.id}
                        activity={activity}
                        onComplete={handleComplete}
                        onUncomplete={handleUncomplete}
                        onEdit={handleEditActivity}
                        onDelete={handleDeleteActivity}
                        onAddNote={handleAddNote}
                        isCompleting={completingActivityId === activity.id}
                        expanded={expandedActivities.has(activity.id || 0)}
                        onToggleExpand={() =>
                          activity.id && toggleActivityExpand(activity.id)
                        }
                      />
                    ))
                  )}
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>

          {/* Deal Notes */}
          {deal.notes && (
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <FileText className="h-5 w-5 text-primary" />
                  <CardTitle className="text-lg">Deal Notes</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm whitespace-pre-wrap">{deal.notes}</p>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Right Column - Contact & Company Info */}
        <div className="space-y-6">
          {contact ? (
            <ContactInfoCard contact={contact} />
          ) : (
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <div className="p-2 rounded-lg bg-blue-500/10">
                    <Users className="h-4 w-4 text-blue-500" />
                  </div>
                  <CardTitle className="text-base">Contact</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  No contact assigned to this deal
                </p>
              </CardContent>
            </Card>
          )}

          {company ? (
            <CompanyInfoCard company={company} />
          ) : contact ? (
            <Card>
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <div className="p-2 rounded-lg bg-purple-500/10">
                    <Building2 className="h-4 w-4 text-purple-500" />
                  </div>
                  <CardTitle className="text-base">Company</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  No company linked to this contact
                </p>
              </CardContent>
            </Card>
          ) : null}

          {/* Quick Stats */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">Summary</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Total Activities</span>
                <span className="font-medium">
                  {(deal.activities?.length || 0)}
                </span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Pending</span>
                <span className="font-medium text-amber-600">
                  {pendingActivities.length}
                </span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Completed</span>
                <span className="font-medium text-green-600">
                  {completedActivities.length}
                </span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Overdue</span>
                <span className="font-medium text-red-600">
                  {pendingActivities.filter((a) => isOverdue(a.plannedAt, a.doneAt)).length}
                </span>
              </div>
              <div className="pt-3 border-t">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Last Updated</span>
                  <span>{formatDate(deal.updatedAt)}</span>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Activity Dialog */}
      <ActivityDialog
        open={activityDialogOpen}
        onOpenChange={setActivityDialogOpen}
        activity={editingActivity}
        dealId={dealId}
        onSuccess={refetch}
      />

      {/* Note Dialog */}
      <NoteDialog
        open={noteDialogOpen}
        onOpenChange={setNoteDialogOpen}
        activityId={noteActivityId}
        onSuccess={refetch}
      />
    </div>
  );
}
