"use client";

import * as React from "react";
import Link from "next/link";
import {
  Calendar,
  DollarSign,
  Loader2,
  MapPin,
  Pencil,
  Tag,
  Trash2,
  User,
  UserCheck,
  UserCircle,
  Users,
  Activity,
  Clock,
  Layout,
  MessageSquare,
  Plus,
  Sparkles,
  ClipboardList,
  Building2,
  TrendingUp,
  ExternalLink,
  ChevronRight,
  Upload,
  FileText,
  AlertCircle,
  ImagePlus,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { Loading } from "@/components/ui/loading";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";
import dynamic from "next/dynamic";
import { useQueryState, parseAsString } from "nuqs";

const PdfViewerDialog = dynamic(
  () => import("@/components/ui/pdf-viewer-dialog").then((mod) => mod.PdfViewerDialog),
  {
    ssr: false,
    loading: () => <Loading layout="panel" message="Loading viewer..." spinnerClassName="text-[#6C63FF]" />,
  }
);

import {
  useGetBusinessDealQuery,
  useGetBusinessDealPaymentStructureQuery,
  useUpdateBusinessDealPaymentStructureMutation,
  useDeleteBusinessDealMutation,
  useGetDealPipelineStagesQuery,
  useUpdateBusinessDealMutation,
  type BusinessDealRecord,
} from "@/api/rtk/business-deals-api";
import {
  useGetDealProposalsQuery,
  useUploadDealProposalMutation,
  useDeleteDealProposalMutation,
  useAddDealNoteMutation,
  useUpdateDealNoteMutation,
  useDeleteDealNoteMutation,
  useUploadDealNoteImageMutation,
} from "@/api/rtk/deals-api";
import { DeleteConfirmationAlert } from "@/components/ui/delete-confirmation-alert";
import {
  DealNoteComposer,
  getEditableTextFromNote,
  NoteContent,
} from "./deal-note-composer";
import { UserAvatar } from "@/components/ui/user-avatar";
import { DealPaymentManager } from "@/components/deals/deal-payment-manager";
import {
  toViewPaymentStructure,
  parsePositiveMoneyString,
  emptyPaymentStructureForLead,
  paymentStructureRawFromBusinessDeal,
} from "@/lib/to-view-payment-structure";
import { useGetProfileQuery } from "@/api/rtk/auth-api";
import { baseApi } from "@/api/rtk/base-api";
import { apiBaseUrl } from "@/api/client";
import { DealTasksWidget } from "@/components/tasks/deal-tasks-widget";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { openBusinessDealDialog } from "@/store/slices/business-deal-dialog-slice";
import { selectAutomationLastDealId, selectAutomationTriggerCount } from "@/store/slices/automation-slice";
import { format } from "date-fns";
import { useQueryClient } from "@tanstack/react-query";
import { invalidateBusinessBoardColumnsForStages } from "@/features/business-deals/invalidate-board-columns";
import { mergeBoardColumnStageIdsWithFirstColumn } from "@/components/deals/deals-pipeline-page/helpers";
import { useAuthToken } from "@/hooks/use-auth-token";
import { canViewDealUserActivity, hasPermission } from "@/lib/permissions";
import { useCreateActivityMutation } from "@/api/rtk/activities-api";
import { useGetAllUsersQuery } from "@/api/rtk/teams-api";
import { listAssignedUserNames } from "@/lib/deal-display";
import { DetailItemAssigneeChips } from "@/components/deals/deal-detail-assignee-chips";
import { stageLabel } from "./deal-utils";



function DetailItem({
  label,
  value,
  icon,
  className,
}: {
  label: string;
  value: React.ReactNode;
  icon?: React.ReactNode;
  className?: string;
}) {
  // Split by comma if it's a phone field
  const isPhone = label.toLowerCase().includes("phone");
  const parts = isPhone && value !== undefined && value !== null && String(value).trim() !== ""
    ? String(value).split(",").map(p => p.trim()).filter(Boolean)
    : null;

  return (
    <div
      className={cn(
        "min-w-0 p-4 rounded-2xl bg-gray-50/50 border border-gray-100/80 transition-all hover:bg-white hover:border-[#6C63FF]/20 group",
        className,
      )}
    >
      <div className="flex items-center gap-2 mb-1.5 min-w-0">
        {icon && (
          <span className="text-gray-400 group-hover:text-[#6C63FF] transition-colors shrink-0">
            {icon}
          </span>
        )}
        <span className="text-[10px] font-medium text-gray-400 uppercase tracking-widest font-['Lexend_Deca'] truncate">
          {label}
        </span>
      </div>
      {parts ? (
        <div className="flex flex-wrap gap-1.5 mt-0.5">
          {parts.map((p, i) => (
            <Badge 
              key={i} 
              variant="secondary" 
              className="bg-[#6C63FF]/5 text-[#6C63FF] border-[#6C63FF]/20 hover:bg-[#6C63FF]/10 transition-colors h-auto py-0.5 px-2 text-[13px] font-semibold rounded-md"
            >
              {p}
            </Badge>
          ))}
        </div>
      ) : (
        <p className="text-[15px] font-medium text-gray-800 font-['Lexend'] break-words [overflow-wrap:anywhere]">
          {value ?? "—"}
        </p>
      )}
    </div>
  );
}

function SectionHeading({
  icon,
  children,
}: {
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-[#6C63FF]/60">{icon}</span>
      <h3 className="text-[11px] font-semibold text-gray-400 uppercase tracking-widest">
        {children}
      </h3>
      <div className="flex-1 h-px bg-gray-100 ml-1" />
    </div>
  );
}

export interface BusinessDealDetailViewProps {
  businessDealId: string;
  onClose?: () => void;
  isFullPage?: boolean;
}

export function BusinessDealDetailView({
  businessDealId,
  onClose,
  isFullPage = false,
}: BusinessDealDetailViewProps) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const {
    data: deal,
    isLoading,
    isError,
    refetch: refetchBusinessDeal,
  } = useGetBusinessDealQuery(businessDealId, { skip: !businessDealId });








  const pipelineId = deal?.PipelineStage?.pipelineId;
  const { data: pipelineStages = [] } = useGetDealPipelineStagesQuery(
    { pipelineId: pipelineId! },
    { skip: !pipelineId },
  );

  const [deleteDeal, { isLoading: deleting }] = useDeleteBusinessDealMutation();
  const [updateDeal, { isLoading: updating }] = useUpdateBusinessDealMutation();
  const [deleteOpen, setDeleteOpen] = React.useState(false);
  const [createActivity] = useCreateActivityMutation();

  // Notes state & mutations
  const [editingNoteId, setEditingNoteId] = React.useState<string | null>(null);
  const [editingNoteText, setEditingNoteText] = React.useState("");
  const [deleteNoteId, setDeleteNoteId] = React.useState<string | null>(null);

  const [addDealNote] = useAddDealNoteMutation();
  const [updateDealNote] = useUpdateDealNoteMutation();
  const [deleteDealNote] = useDeleteDealNoteMutation();
  const [uploadNoteImage] = useUploadDealNoteImageMutation();

  const handleAddNote = async (text: string) => {
    const targetId = deal?.leadId || deal?.id;
    if (!targetId) return;
    try {
      await addDealNote({ dealId: targetId, text }).unwrap();
    } catch (err) {
      toast.error("Failed to add note");
    }
  };

  const handleUpdateNote = async (noteId: string, text: string) => {
    const targetId = deal?.leadId || deal?.id;
    if (!targetId) return;
    try {
      await updateDealNote({ dealId: targetId, noteId, text }).unwrap();
      setEditingNoteId(null);
      toast.success("Note updated");
    } catch (err) {
      toast.error("Failed to update note");
    }
  };

  const handleDeleteNote = async () => {
    const targetId = deal?.leadId || deal?.id;
    if (!targetId || !deleteNoteId) return;
    try {
      await deleteDealNote({ dealId: targetId, noteId: deleteNoteId }).unwrap();
      setDeleteNoteId(null);
      toast.success("Note deleted");
    } catch (err) {
      toast.error("Failed to delete note");
    }
  };

  const handleTaskHandedToAE = React.useCallback(async () => {
    console.log("[Auto-Stage] Callback triggered: Handed to AE detected.");

    if (!pipelineStages.length) {
      console.warn("[Auto-Stage] Aborting: pipelineStages list is empty.");
      return;
    }
    if (!deal) {
      console.warn("[Auto-Stage] Aborting: deal object is missing.");
      return;
    }

    console.log(`[Auto-Stage] Checking ${pipelineStages.length} stages for 'Proposal Queue'...`);

    let targetStageId: string | null = null;
    let isSubStage = false;

    // Search for "Proposal Queue" in stages and sub-stages
    for (const stage of pipelineStages) {
      const stageName = (stage.name || "").toLowerCase();
      console.log(`[Auto-Stage] Checking stage: "${stage.name}" (${stage.id})`);

      if (stageName.includes("proposal queue")) {
        targetStageId = stage.id;
        isSubStage = false;
        console.log(`[Auto-Stage] MATCH FOUND in main stage: "${stage.name}"`);
        break;
      }

      for (const sub of (stage.pipelineSubStages || [])) {
        const subName = (sub.name || "").toLowerCase();
        console.log(`[Auto-Stage]   - Checking sub-stage: "${sub.name}" (${sub.id})`);

        if (subName.includes("proposal queue")) {
          targetStageId = sub.id;
          isSubStage = true;
          console.log(`[Auto-Stage] MATCH FOUND in sub-stage: "${sub.name}"`);
          break;
        }
      }
      if (targetStageId) break;
    }

    if (!targetStageId) {
      const allNames = pipelineStages.flatMap(s => [s.name, ...(s.pipelineSubStages?.map(sub => sub.name) || [])]);
      console.error("[Auto-Stage] FAILED: 'Proposal Queue' not found in this pipeline. Available names:", allNames);
      return;
    }

    try {
      const payload = {
        id: deal.id,
        body: {
          ...(isSubStage
            ? { pipelineSubStageId: targetStageId }
            : { pipelineStageId: targetStageId, pipelineSubStageId: undefined }),
        },
      };

      console.log("[Auto-Stage] Calling updateDeal API with payload:", payload);
      await updateDeal(payload).unwrap();
      console.log("[Auto-Stage] API updateDeal SUCCESS.");

      // Invalidate board columns
      const pipelineId = deal.PipelineStage?.pipelineId;
      if (pipelineId) {
        const firstColumnStageId = pipelineStages[0]?.id;
        const targetStages = new Set<string>();
        targetStages.add(targetStageId);

        // Old stages
        if (deal.pipelineStageId) targetStages.add(deal.pipelineStageId);
        if (deal.pipelineSubStageId) targetStages.add(deal.pipelineSubStageId);

        const stageIdsForBoard = mergeBoardColumnStageIdsWithFirstColumn(
          Array.from(targetStages),
          firstColumnStageId ?? null,
        );

        invalidateBusinessBoardColumnsForStages(
          queryClient,
          pipelineId,
          stageIdsForBoard,
          { invalidateCounts: true },
        );
      }

      // Record activity
      console.log("[Auto-Stage] Recording activity log...");
      await createActivity({
        type: "Deal",
        subject: "Auto-transition to Proposal Queue",
        dealId: deal.id,
        description: "Deal stage automatically updated because a task was marked as 'Handed to AE'.",
      }).unwrap();
      console.log("[Auto-Stage] Activity log recorded successfully.");

      toast.success("Deal stage updated to Proposal Queue");
    } catch (err) {
      console.error("[Auto-Stage] API CALL FAILED:", err);
    }
  }, [pipelineStages, deal, updateDeal, createActivity]);

  const lastHandedToAEDealId = useAppSelector(selectAutomationLastDealId);
  const triggerCount = useAppSelector(selectAutomationTriggerCount);

  React.useEffect(() => {
    if (lastHandedToAEDealId && deal && lastHandedToAEDealId === deal.id) {
      console.log("[Auto-Stage] Detected Redux automation trigger for this deal.");
      handleTaskHandedToAE();
    }
  }, [triggerCount, lastHandedToAEDealId, deal?.id, handleTaskHandedToAE]);

  // Proposal State & Hooks
  const { data: proposals = [], isLoading: proposalsLoading } =
    useGetDealProposalsQuery(businessDealId, { skip: !businessDealId });
  const [uploadProposal, { isLoading: isUploadingProposal }] =
    useUploadDealProposalMutation();
  const [deleteProposal, { isLoading: isDeletingProposal }] =
    useDeleteDealProposalMutation();
  const [deleteProposalId, setDeleteProposalId] = React.useState<string | null>(
    null,
  );
  const [activeTab, setActiveTab] = useQueryState(
    "tab",
    parseAsString.withDefault("details").withOptions({ shallow: true }),
  );
  const [viewerOpen, setViewerOpen] = React.useState(false);
  const [viewerUrl, setViewerUrl] = React.useState<string | null>(null);
  const [viewerFileName, setViewerFileName] = React.useState("");

  const { token: accessToken } = useAuthToken();
  const { data: session } = useSession();
  const { data: profile } = useGetProfileQuery(undefined, {
    skip: !accessToken,
  });
  const { data: allUsers = [] } = useGetAllUsersQuery();
  const dealAssigneeNames = React.useMemo(
    () =>
      deal
        ? listAssignedUserNames(deal.aes, deal.aeIds, allUsers)
        : [],
    [deal, allUsers],
  );
  const permissionSource =
    (session as { backendUser?: unknown } | null)?.backendUser ?? profile;
  const canViewUserActivity = canViewDealUserActivity(permissionSource);
  const canViewHistory = hasPermission(
    permissionSource,
    ["READ", "UPDATE"],
    "LEAD_HISTORY",
  );
  const canUpdateDeal = hasPermission(
    permissionSource,
    "UPDATE",
    "DEAL",
  );
  const canDeleteDeal = hasPermission(
    permissionSource,
    "DELETE",
    "DEAL",
  );
  const userRole = profile?.role?.name?.toLowerCase() || "";
  const canDownload = ["admin", "ceo", "coo"].includes(userRole);

  const canViewPayment = hasPermission(
    permissionSource,
    ["READ", "CREATE", "UPDATE"],
    "PAYMENT_STRUCTURE",
  );
  const canManagePayment = hasPermission(
    permissionSource,
    ["CREATE", "UPDATE"],
    "PAYMENT_STRUCTURE",
  );

  const {
    data: businessDealPaymentBundle,
    isLoading: businessDealPaymentLoading,
    refetch: refetchBusinessDealPaymentStructure,
  } = useGetBusinessDealPaymentStructureQuery(businessDealId, {
    skip: !businessDealId || !canViewPayment,
  });
  const [updateBusinessDealPaymentStructure, { isLoading: isUpdatingPayment }] =
    useUpdateBusinessDealPaymentStructureMutation();

  const paymentStructureState = React.useMemo(() => {
    if (!deal) return { kind: "none" as const };
    if (businessDealPaymentLoading && !businessDealPaymentBundle) {
      return { kind: "loading" as const };
    }

    const dealPayment = toViewPaymentStructure(
      paymentStructureRawFromBusinessDeal(
        businessDealPaymentBundle?.paymentStructure
          ? {
              ...deal,
              paymentStructure:
                businessDealPaymentBundle.paymentStructure as BusinessDealRecord["paymentStructure"],
            }
          : deal,
      ),
      parsePositiveMoneyString(deal.dealValue) || null,
    );

    if (dealPayment) {
      const dv = parsePositiveMoneyString(deal.dealValue);
      if (dv != null) {
        dealPayment.projectVal = String(dv);
      }
      return {
        kind: "ok" as const,
        payment: dealPayment,
      };
    }

    return {
      kind: "ok" as const,
      payment: emptyPaymentStructureForLead(),
    };
  }, [deal, businessDealPaymentBundle, businessDealPaymentLoading]);

  const paymentStructureReadOnly = !canManagePayment || !businessDealId;

  const getDownloadUrl = (fileUrl: string) => {
    const base = apiBaseUrl.replace(/\/$/, "");
    const raw = (fileUrl || "").trim();
    if (!raw) return base;
    if (/^https?:\/\//i.test(raw)) return raw;
    return `${base}${raw.startsWith("/") ? raw : `/${raw}`}`;
  };

  const handleUploadProposal = async (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = e.target.files?.[0];
    if (!file || !businessDealId) return;
    try {
      await uploadProposal({ dealId: businessDealId, file }).unwrap();
      toast.success("Document uploaded successfully");
      e.target.value = "";
    } catch (err) {
      toast.error("Failed to upload document");
    }
  };

  const confirmDeleteProposal = async () => {
    if (!businessDealId || !deleteProposalId) return;
    try {
      await deleteProposal({
        dealId: businessDealId,
        documentId: deleteProposalId,
      }).unwrap();
      toast.success("Document removed");
      setDeleteProposalId(null);
    } catch (err) {
      toast.error("Failed to remove document");
      throw err;
    }
  };

  const handleBack = () => {
    onClose?.();
  };

  const fmtMoney = (v: string | null | undefined) => {
    if (v == null || v === "") return "—";
    const n = Number.parseFloat(v.replace(/,/g, ""));
    if (Number.isNaN(n)) return v;
    return new Intl.NumberFormat(undefined, {
      style: "currency",
      currency: "USD",
      maximumFractionDigits: 2,
    }).format(n);
  };

  const fmtDate = (iso: string | null | undefined) => {
    if (!iso) return "—";
    const d = new Date(iso);
    if (Number.isNaN(d.getTime())) return "—";
    return format(d, "MMM d, yyyy");
  };

  const onConfirmDelete = async () => {
    if (!deal) return;
    try {
      await deleteDeal(deal.id).unwrap();
      toast.success("Deal deleted");

      // Invalidate board
      const pipelineId = deal.PipelineStage?.pipelineId;
      if (pipelineId) {
        const firstColumnStageId = pipelineStages[0]?.id;
        const targetStages = new Set<string>();
        if (deal.pipelineStageId) targetStages.add(deal.pipelineStageId);
        if (deal.pipelineSubStageId) targetStages.add(deal.pipelineSubStageId);

        const stageIdsForBoard = mergeBoardColumnStageIdsWithFirstColumn(
          Array.from(targetStages),
          firstColumnStageId ?? null,
        );

        invalidateBusinessBoardColumnsForStages(
          queryClient,
          pipelineId,
          stageIdsForBoard,
          { invalidateCounts: true },
        );
      }

      handleBack();
    } catch (err) {
      toast.error("Could not delete deal");
      throw err;
    }
  };


  React.useEffect(() => {
    if (deal) {
      console.log("=================== DEAL ===================");
      console.log(canViewPayment && deal?.PipelineStage?.name?.includes("Closed Won"));
      console.log("=================== DEAL ===================");
    }
  }, [deal]);



  if (!businessDealId) {
    return (
      <div className="flex flex-1 items-center justify-center p-8 text-sm text-muted-foreground">
        Missing deal id
      </div>
    );
  }

  if (isLoading) {
    return (
      <Loading
        layout="panel"
        className="p-12"
        message="Loading deal…"
        spinnerClassName="text-[#6C63FF]"
      />
    );
  }

  if (isError || !deal) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center gap-4 p-8">
        <p className="text-center font-['Lexend'] text-sm text-gray-600">
          Could not load this deal. It may have been removed.
        </p>
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            void refetchBusinessDeal();
            if (canViewPayment && businessDealId) {
              void refetchBusinessDealPaymentStructure();
            }
          }}
        >
          Retry
        </Button>
      </div>
    );
  }

  const title =
    deal.title?.trim() ||
    deal.linkedLead?.customerName?.trim() ||
    deal.linkedCustomer?.fullName?.trim() ||
    deal.linkedCustomer?.companyName?.trim() ||
    "Business deal";

  const linkedName = deal.customerId
    ? deal.linkedCustomer?.fullName ||
    deal.linkedCustomer?.companyName ||
    deal.linkedCustomer?.customerName ||
    deal.linkedCustomer?.email
    : deal.leadId
      ? deal.linkedLead?.customerName || deal.linkedLead?.leadId
      : null;

  return (
    <div className={cn("flex min-h-0 flex-1 flex-col")}>
      {/* HEADER SECTION */}
      <div className="relative border-b border-gray-100 px-4 pb-8 pt-6 sm:px-8 sm:pb-10 sm:pt-8">
        <div className="relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
          <div className="flex items-start gap-4 min-w-0 sm:gap-6">
            <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-[#6C63FF]/20 bg-[#6C63FF]/10 shadow-inner sm:h-16 sm:w-16">
              <Building2 className="size-7 text-[#6C63FF] sm:size-8" />
            </div>
            <div className="min-w-0 flex-1">
              <div className="flex flex-wrap items-center gap-2 mb-1">

                {deal?.PipelineStage?.name ? (
                  <Badge
                    variant="outline"
                    className="rounded-lg font-['Lexend'] text-[10px] border-gray-200 text-gray-500"
                  >
                    {deal.PipelineStage.name}
                  </Badge>
                ) : null}
              </div>
              <h1 className="font-['Lexend'] text-xl font-semibold leading-tight tracking-tight text-gray-900 sm:text-[28px] break-words">
                {title}
              </h1>
              {deal.linkedLead?.leadId && (
                <p className="text-[11px] font-medium text-gray-400 font-['Lexend_Deca'] mt-0">
                  Lead ID: {deal.linkedLead.leadId}
                </p>
              )}
              {linkedName ? (
                <div className="mt-1.5 flex items-center gap-2 font-['Lexend_Deca'] text-sm text-gray-500">
                  <span>Linked:</span>
                  {deal.customerId ? (
                    <Link
                      href={`/customers/${deal.customerId}`}
                      className="flex items-center gap-1 font-medium text-[#6C63FF] hover:underline"
                    >
                      {linkedName}
                      <ExternalLink size={12} />
                    </Link>
                  ) : (
                    <span className="font-medium text-gray-700">
                      {linkedName}
                    </span>
                  )}
                </div>
              ) : null}
            </div>
          </div>

          <div className="flex flex-wrap items-stretch gap-4 lg:flex-nowrap lg:items-center lg:justify-end">
            <div className="flex shrink-0 flex-wrap gap-2">
              {canViewHistory ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="h-10 gap-1.5 rounded-xl border-gray-200 font-['Lexend_Deca'] font-bold text-[13px] hover:bg-gray-50"
                  onClick={() => router.push(`/sales-deals/${deal.id}/tracker`)}
                >
                  <Clock size={14} />
                  Deal activity
                </Button>
              ) : null}
              {canViewUserActivity ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="h-10 gap-1.5 rounded-xl border-emerald-100 font-['Lexend_Deca'] font-bold text-[13px] text-emerald-600 hover:bg-emerald-50"
                  onClick={() =>
                    router.push(`/sales-deals/${deal.id}/user-deal-timeline`)
                  }
                >
                  <Users size={14} />
                  User timeline
                </Button>
              ) : null}
              {canUpdateDeal ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="h-10 gap-1.5 rounded-xl border-gray-200 font-['Lexend_Deca'] font-bold text-[13px] hover:bg-gray-50"
                  onClick={() =>
                    dispatch(
                      openBusinessDealDialog({
                        mode: "edit",
                        businessDealId: deal.id,
                      }),
                    )
                  }
                >
                  <Pencil size={14} />
                  Edit
                </Button>
              ) : null}
              {canDeleteDeal ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="h-10 gap-1.5 rounded-xl border-red-100 text-red-500 font-['Lexend_Deca'] font-bold text-[13px] hover:bg-red-50"
                  onClick={() => setDeleteOpen(true)}
                >
                  <Trash2 size={14} />
                  Delete
                </Button>
              ) : null}
            </div>
          </div>
        </div>
      </div>

      {/* CONTENT AREA WITH TABS */}
      <div className="min-h-0 flex-1 overflow-y-auto px-4 py-6 sm:px-8">
        <Tabs
          value={activeTab}
          onValueChange={setActiveTab}
          className="w-full"
        >
          <TabsList className="mb-5 flex h-auto min-h-10 w-full flex-wrap gap-1 rounded-xl bg-gray-100/50 p-1">
            <TabsTrigger value="details" className="gap-2">
              <Layout size={14} />
              Details
            </TabsTrigger>
            <TabsTrigger value="notes" className="gap-2">
              <MessageSquare size={14} />
              Notes
            </TabsTrigger>
            <TabsTrigger value="tasks" className="gap-2">
              <FileText size={14} />
              Tasks
            </TabsTrigger>
            <TabsTrigger value="proposals" className="gap-2">
              <FileText size={14} />
              Proposals
            </TabsTrigger>
            {canViewPayment && deal?.PipelineStage?.name?.includes("Closed Won") ? (
              <TabsTrigger value="payment" className="gap-2">
                <DollarSign size={14} />
                Payment structure
              </TabsTrigger>
            ) : null}
          </TabsList>

          <TabsContent
            value="details"
            className="space-y-8 animate-in fade-in duration-500"
          >
            <section className="space-y-4">
              <SectionHeading icon={<Activity size={14} />}>
                Deal Overview
              </SectionHeading>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <DetailItem
                  label="Title"
                  value={deal.title?.trim() || "—"}
                  icon={<FileText className="size-3.5" />}
                />
                <DetailItem
                  label="Deal type"
                  value={deal.dealType?.trim() || "—"}
                  icon={<Tag className="size-3.5" />}
                />
                <DetailItem
                  label="Stage"
                  value={stageLabel(deal)}
                  icon={<Activity className="size-3.5" />}
                />
                <DetailItem
                  label="Deal value"
                  value={fmtMoney(deal.dealValue)}
                  icon={<DollarSign className="size-3.5" />}
                />
                <DetailItem
                  label="Expected close"
                  value={fmtDate(deal.expectedCloseDate ?? undefined)}
                  icon={<Calendar className="size-3.5" />}
                />
              </div>
            </section>

            <section className="space-y-4">
              <SectionHeading icon={<TrendingUp size={14} />}>
                Classification & Ownership
              </SectionHeading>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <DetailItem
                  label="Region"
                  value={deal.region?.trim() || "—"}
                  icon={<MapPin className="size-3.5" />}
                />
                <DetailItem
                  label="Brand"
                  value={deal.brand?.trim() || "—"}
                  icon={<Tag className="size-3.5" />}
                />
                <DetailItem
                  label="Owner"
                  value={deal.owner?.name?.trim() || deal.owner?.email || "—"}
                  icon={<User className="size-3.5" />}
                />
                <DetailItemAssigneeChips
                  label="Deal assignee"
                  names={dealAssigneeNames}
                  icon={<UserCheck size={14} />}
                />
                <DetailItem
                  label="Created At"
                  value={fmtDate(deal.createdAt)}
                  icon={<Clock size={14} />}
                />
              </div>
            </section>

            {deal.linkedLead?.leadDetails && (
              <section className="space-y-4">
                <SectionHeading icon={<FileText size={14} />}>
                  Description
                </SectionHeading>
                <div className="rounded-2xl border border-gray-100 bg-white/40 backdrop-blur-md p-6 shadow-sm">
                  <p className="font-['Lexend'] text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">
                    {deal.linkedLead.leadDetails}
                  </p>
                </div>
              </section>
            )}
          </TabsContent>

          <TabsContent
            value="notes"
            className="animate-in fade-in duration-500 flex flex-col h-[calc(100vh-240px)]"
          >
            <div className="flex-1 overflow-y-auto pr-2 custom-scrollbar space-y-6 py-6">
              {deal.dealNotes?.length ? (
                deal.dealNotes.map((note) => (
                  <div
                    key={note.id}
                    className="flex gap-4 group animate-in fade-in slide-in-from-bottom-2"
                  >
                    <UserAvatar
                      avatar={note.author?.profile?.avatar}
                      name={note.author?.name}
                      size="md"
                    />
                    <div className="flex-1">
                      <div className="bg-gray-50 rounded-2xl p-4 border border-gray-100 group-hover:bg-white transition-colors shadow-sm hover:shadow-md">
                        <div className="flex justify-between mb-2">
                          <span className="text-sm font-semibold text-gray-900">
                            {note.author?.name}
                          </span>
                          <span className="text-[10px] text-gray-400 font-medium">
                            {new Date(note.createdAt).toLocaleString()}
                          </span>
                        </div>
                        {editingNoteId === note.id ? (
                          <div className="space-y-3">
                            <Textarea
                              className="min-h-[100px] text-sm bg-white border-[#6C63FF]/20 focus:border-[#6C63FF] focus:ring-[#6C63FF]/10 transition-all"
                              value={editingNoteText}
                              onChange={(e) => setEditingNoteText(e.target.value)}
                              autoFocus
                            />
                            <div className="flex gap-2">
                              <Button
                                size="sm"
                                className="bg-[#6C63FF] hover:bg-[#5B54E0]"
                                onClick={() => handleUpdateNote(note.id, editingNoteText)}
                              >
                                Save Changes
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => setEditingNoteId(null)}
                              >
                                Cancel
                              </Button>
                            </div>
                          </div>
                        ) : (
                          <NoteContent text={note.text} apiBaseUrl={apiBaseUrl} />
                        )}
                      </div>
                      {!editingNoteId && (
                        <div className="flex gap-4 mt-2 ml-2 opacity-0 group-hover:opacity-100 transition-all duration-200">
                          <button
                            onClick={() => {
                              setEditingNoteId(note.id);
                              setEditingNoteText(getEditableTextFromNote(note.text));
                            }}
                            className="text-[11px] font-bold text-gray-400 hover:text-[#6C63FF] uppercase tracking-wider"
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => setDeleteNoteId(note.id)}
                            className="text-[11px] font-bold text-gray-400 hover:text-red-500 uppercase tracking-wider"
                          >
                            Delete
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                ))
              ) : (
                <div className="flex flex-col items-center justify-center py-24 opacity-40">
                  <div className="size-16 rounded-3xl bg-gray-100 flex items-center justify-center mb-4">
                    <MessageSquare size={32} className="text-gray-400" />
                  </div>
                  <p className="font-['Lexend'] text-sm font-semibold text-gray-600">No notes yet</p>
                  <p className="text-xs text-gray-400 mt-1">Add a note below to start the conversation</p>
                </div>
              )}
            </div>

            <div className="mt-auto  border-t border-gray-100 bg-white/80 backdrop-blur-sm sticky bottom-0">
              <DealNoteComposer
                dealId={deal.leadId || deal.id}
                apiBaseUrl={apiBaseUrl}
                onSend={handleAddNote}
                uploadImage={async (did, file) =>
                  uploadNoteImage({ dealId: did, file }).unwrap()
                }
              />
            </div>

            <DeleteConfirmationAlert
              open={!!deleteNoteId}
              onOpenChange={(open) => !open && setDeleteNoteId(null)}
              onConfirm={handleDeleteNote}
              title="Delete Note"
              description="Are you sure you want to delete this note? This action cannot be undone."
            />
          </TabsContent>

          <TabsContent
            value="tasks"
            className="animate-in fade-in duration-500"
          >
            <section className="space-y-4">
              <SectionHeading icon={<FileText size={14} />}>
                Tasks & Follow-ups
              </SectionHeading>
              <div className="rounded-2xl border border-gray-100 bg-white/40 backdrop-blur-md p-2 shadow-sm">
                <DealTasksWidget
                  dealId={deal.leadId || deal.id}
                  taskModuleType="DEAL"
                />
              </div>
            </section>
          </TabsContent>

          <TabsContent
            value="proposals"
            className="animate-in fade-in duration-500"
          >
            <section className="space-y-6">
              <div className="flex items-center justify-between">
                <SectionHeading icon={<FileText size={14} />}>
                  Proposal Documents
                </SectionHeading>
                <label className="inline-flex cursor-pointer items-center gap-2 rounded-xl bg-[#6C63FF]/10 px-6 py-2.5 text-sm font-semibold text-[#6C63FF] transition-colors hover:bg-[#6C63FF]/20">
                  <Upload size={16} />
                  {isUploadingProposal ? "Uploading..." : "Upload Document"}
                  <input
                    type="file"
                    className="hidden"
                    accept=".pdf,.docx"
                    disabled={isUploadingProposal}
                    onChange={handleUploadProposal}
                  />
                </label>
              </div>

              <div className="mt-4 space-y-3">
                {proposals.length ? (
                  proposals.map((doc) => (
                    <div
                      key={doc.id}
                      className="flex items-center justify-between rounded-xl border border-gray-100 bg-white/40 p-4 backdrop-blur-md transition-all hover:bg-white/60"
                    >
                      <div className="flex gap-4">
                        <div className="flex size-12 items-center justify-center rounded-xl bg-[#6C63FF]/10 text-[#6C63FF]">
                          <FileText size={22} />
                        </div>
                        <div>
                          <p className="font-['Lexend'] text-[15px] font-semibold text-gray-900">
                            {doc.fileName}
                          </p>
                          <p className="font-['Lexend_Deca'] text-[11px] text-gray-400">
                            {new Date(doc.createdAt).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={() => {
                            setViewerUrl(getDownloadUrl(doc.fileUrl));
                            setViewerFileName(doc.fileName);
                            setViewerOpen(true);
                          }}
                          className="flex size-10 items-center justify-center rounded-xl border border-gray-100 bg-white shadow-sm transition-all hover:bg-gray-50 text-[#6C63FF]"
                        >
                          <FileText size={16} />
                        </button>
                        <button
                          type="button"
                          onClick={() => setDeleteProposalId(doc.id)}
                          className="flex size-10 items-center justify-center rounded-xl bg-red-50 text-red-600 transition-all hover:bg-red-100"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-gray-200 py-20 text-gray-400">
                    <FileText className="mb-3 size-12 opacity-20" />
                    <p className="font-['Lexend'] text-sm font-medium">
                      No documents uploaded yet
                    </p>
                    <p className="text-xs opacity-60">
                      Upload PDF or DOCX proposals for this deal
                    </p>
                  </div>
                )}
              </div>
            </section>
          </TabsContent>

          {(canViewPayment && deal?.PipelineStage?.name?.includes("Closed Won")) ? (
            <TabsContent
              value="payment"
              className="mt-0 animate-in fade-in duration-500 outline-none"
            >
              <section className="space-y-6">
                <SectionHeading icon={<DollarSign size={14} />}>
                  Payment management
                </SectionHeading>

                {paymentStructureState.kind === "loading" ? (
                  <Loading
                    layout="section"
                    message="Loading payment data..."
                    spinnerClassName="text-[#6C63FF]"
                  />
                ) : paymentStructureState.kind === "ok" ? (
                  <DealPaymentManager
                    showAddCustomPaymentForm={false}
                    title={"Payment structure"}
                    description={"Manage payment terms, milestones, and status for this deal."}
                    payment={paymentStructureState.payment}
                    readOnly={paymentStructureReadOnly}
                    isSaving={isUpdatingPayment}
                    upfrontStatusReadOnly={!canManagePayment}
                    autoPersistUpfrontStatus={Boolean(
                      businessDealId && canManagePayment,
                    )}
                    onUpdate={async (payment) => {
                      if (!canManagePayment) {
                        throw new Error("FORBIDDEN");
                      }
                      if (
                        paymentStructureState.kind !== "ok" ||
                        !businessDealId
                      ) {
                        throw new Error("NO_PAYMENT_SAVE_TARGET");
                      }
                      await updateBusinessDealPaymentStructure({
                        id: businessDealId,
                        body: payment,
                      }).unwrap();
                      await refetchBusinessDealPaymentStructure();
                      toast.success("Payment structure updated");
                    }}
                  />
                ) : (
                  <div className="flex flex-col items-center justify-center py-12 text-center rounded-2xl border border-dashed border-gray-200">
                    <p className="text-gray-500">No payment data available for this deal.</p>
                  </div>
                )}
              </section>
            </TabsContent>
          ) : null}
        </Tabs>
      </div>

      <DeleteConfirmationAlert
        open={!!deleteProposalId}
        onOpenChange={(o) => !o && setDeleteProposalId(null)}
        onConfirm={confirmDeleteProposal}
        title="Remove Document"
        description="Are you sure you want to remove this proposal document?"
        isLoading={isDeletingProposal}
      />

      <PdfViewerDialog
        open={viewerOpen}
        onOpenChange={setViewerOpen}
        url={viewerUrl}
        fileName={viewerFileName}
        canDownload={canDownload}
        token={accessToken}
      />

      <DeleteConfirmationAlert
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete this deal?"
        description="This removes the sales deal from the pipeline. Linked lead or customer records are not deleted."
        confirmText="Delete deal"
        isLoading={deleting}
        onConfirm={onConfirmDelete}
      />
    </div>
  );
}
