"use client"

import * as React from "react"
import { Deal, Stage, DealDetailViewProps } from "./types"
import { buildPipelineTimelineStages } from "./deal-utils"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { cn } from "@/lib/utils"
import {
    Building2, Phone, Mail, MapPin, Users, UserPlus,
    ArrowRight, UserCheck, Loader2,
    MessageSquare, Bell, Users2,
    Layout, X, XCircle, Clock,
    ClipboardList, Pencil,
    Briefcase, TrendingUp, Tag, Timer,
} from "lucide-react"
import { Textarea } from "@/components/ui/textarea"
import { ReactSelect } from "@/components/ui/react-select"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Loading } from "@/components/ui/loading"
import { Badge } from "@/components/ui/badge"
import { useRouter, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { useAuthToken } from "@/hooks/use-auth-token"
import { apiBaseUrl } from "@/api/client"
import {
    useGetDealQuery,
    useUpdateDealMutation,
    useMoveDealMutation,
    useCloseLostMutation,
    useGetConvertedDealIdsQuery,
} from "@/api/rtk/deals-api"
import { useGetClosedLeadTagsQuery } from "@/api/rtk/deal-meta-api"
import { markLocalDealBoardMove } from "@/lib/deal-board-socket-coalesce"
import { useQueryClient } from "@tanstack/react-query"
import { invalidateLeadsBoardColumnsTouchingStages } from "@/features/leads/api/invalidate-leads-board-columns"
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api"
import { DealBantSidebar } from "./deal-bant-sidebar"
import { DealNotesModal } from "./deal-notes-modal"
import { DealRemindersModal } from "./deal-reminders-modal"
import { useGetProfileQuery } from "@/api/rtk/auth-api"
import { useGetTeamsQuery, useGetAllUsersQuery } from "@/api/rtk/teams-api"
import { DealTasksWidget } from "@/components/tasks/deal-tasks-widget"
import { getDealMemberUserIds } from "@/lib/deal-team-members"
import {
    formatTeamLabelForUi,
    listAssignedUserNames,
    resolveTeamDisplayName,
} from "@/lib/deal-display"
import {
    isDiscoverMeetingBookedStage,
    isEnteringDiscoverMeetingBookedStage,
    isDealInLostStage,
    listLostLeadStages,
} from "@/lib/deal-stage-labels"
import { DetailItemAssigneeChips } from "@/components/deals/deal-detail-assignee-chips"
import { DiscoveryMeetingBookedAlert } from "@/components/deals/discovery-meeting-booked-alert"
import { useAppDispatch } from "@/store/hooks"
import { openBusinessDealDialog } from "@/store/slices/business-deal-dialog-slice"
import { openMoveToLostDialog } from "@/store/slices/move-to-lost-dialog-slice"
import { openDiscoveryMeetingBookedDialog } from "@/store/slices/discovery-meeting-booked-dialog-slice"
import { canViewDealUserActivity, hasPermission, isAdminUser } from "@/lib/permissions"
import { buildLeadUpdatePayload } from "@/lib/lead-update-payload"
import { useSession } from "next-auth/react"
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
import dynamic from "next/dynamic"

const TaskFormModal = dynamic(() => import("@/components/tasks/task-form-modal").then(m => m.TaskFormModal))
const EditDealModal = dynamic(() => import("@/components/deals/edit-deal-modal").then(m => m.EditDealModal))



function DetailItem({ label, value, icon, className }: { label: string; value: string | number | undefined | null; icon?: React.ReactNode; className?: string }) {
    const display = value !== undefined && value !== null && value !== "" ? String(value) : "—"

    // 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]">{display}</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>
    )
}

function ClampedDescription({ text }: { text: string }) {
    const [expanded, setExpanded] = React.useState(false)
    const needsClamp = text.length > 280 || text.split("\n").length > 4

    return (
        <div className="rounded-2xl border border-gray-100 bg-white/20 p-4 backdrop-blur-sm sm:p-5">
            <p
                className={cn(
                    "text-sm leading-relaxed whitespace-pre-wrap text-gray-600",
                    !expanded && needsClamp && "line-clamp-4",
                )}
            >
                {text}
            </p>
            {needsClamp ? (
                <button
                    type="button"
                    onClick={() => setExpanded((prev) => !prev)}
                    className="mt-2 text-xs font-semibold text-[#6C63FF] hover:text-[#5a52d6]"
                >
                    {expanded ? "Show less" : "Show more"}
                </button>
            ) : null}
        </div>
    )
}




export function DealDetailView({ dealId, stages: providedStages, convertedDealIds: providedConvertedDealIds, defaultTab, onClose, isFullPage = false }: DealDetailViewProps) {
    const { data: deal, isLoading, isError, isFetching, refetch } = useGetDealQuery(dealId)
    const { data: pipelines } = useGetPipelinesQuery(undefined, { skip: !!providedStages })
    const router = useRouter()
    const searchParams = useSearchParams()
    const dispatch = useAppDispatch()
    const tabFromUrl = searchParams.get("tab")
    const resolvedTab = defaultTab ?? tabFromUrl
    const [notesModalOpen, setNotesModalOpen] = React.useState(resolvedTab === "notes")
    const [remindersModalOpen, setRemindersModalOpen] = React.useState(resolvedTab === "reminders")
    const mainScrollRef = React.useRef<HTMLDivElement>(null)

    React.useEffect(() => {
        if (isLoading || !deal) return

        const tab = defaultTab ?? tabFromUrl
        if (tab === "notes") {
            setNotesModalOpen(true)
            return
        }
        if (tab === "reminders") {
            setRemindersModalOpen(true)
            return
        }
        if (tab === "tasks" || tab === "task") {
            const timer = window.setTimeout(() => {
                const target =
                    mainScrollRef.current?.querySelector("#lead-section-tasks") ??
                    document.getElementById("lead-section-tasks")
                target?.scrollIntoView({ behavior: "smooth", block: "start" })
            }, 150)
            return () => window.clearTimeout(timer)
        }
    }, [defaultTab, tabFromUrl, isLoading, deal?.id])


    const [updateDeal, { isLoading: isUpdatingDeal }] = useUpdateDealMutation()
    const [moveDealMutation, { isLoading: isMovingDeal }] = useMoveDealMutation()
    const [closeLostMutation, { isLoading: isClosingLost }] = useCloseLostMutation()
    const { data: convertedIdsList } = useGetConvertedDealIdsQuery(undefined, { skip: !!providedConvertedDealIds })
    const queryClient = useQueryClient()

    const convertedDealIds = React.useMemo(() => {
        if (providedConvertedDealIds) return providedConvertedDealIds
        return new Set(convertedIdsList || [])
    }, [providedConvertedDealIds, convertedIdsList])

    // Resolve stages: provided > deal's pipeline (no hardcoded fallback columns)
    const stages = React.useMemo(() => {
        if (providedStages && providedStages.length > 0) return providedStages
        if (pipelines && deal?.pipelineId) {
            const pipeline = pipelines.find(p => p.id === deal.pipelineId)
            if (pipeline?.stages) return pipeline.stages as unknown as Stage[]
        }
        return [] as Stage[]
    }, [providedStages, pipelines, deal?.pipelineId])

    const channelName = typeof deal?.leadChannel === "object" && deal?.leadChannel !== null
        ? (deal.leadChannel as { name?: string }).name
        : (deal?.leadChannel as unknown as string | undefined)

    const { token: accessToken } = useAuthToken()
    const { data: session } = useSession()
    const { data: allUsers = [] } = useGetAllUsersQuery(undefined, { skip: !accessToken })
    const { data: fullTeams = [] } = useGetTeamsQuery(undefined, { skip: !accessToken })
    const { data: userProfile } = useGetProfileQuery(undefined, { skip: !accessToken })

    const teamDisplayName = React.useMemo(
        () => resolveTeamDisplayName(deal?.team, fullTeams),
        [deal?.team, fullTeams],
    )
    const assigneeAeNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.aes, deal.aeIds, allUsers) : []),
        [deal, allUsers],
    )
    const assigneeBdrNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.bdrs, deal.bdrIds, allUsers) : []),
        [deal, allUsers],
    )
    const assigneeContributorNames = React.useMemo(
        () => (deal ? listAssignedUserNames(deal.contributors, deal.contributorIds, allUsers) : []),
        [deal, allUsers],
    )
    const permissionSource = (session as { backendUser?: unknown } | null)?.backendUser ?? userProfile
    const isAdmin = isAdminUser(permissionSource)
    const canViewUserActivity = canViewDealUserActivity(permissionSource)
    const canUpdateDeal = hasPermission(permissionSource, "UPDATE", "LEAD")
    const currentUserId = (permissionSource as { id?: string } | null | undefined)?.id

    const canEditNotes = React.useMemo(() => {
        if (!deal) return false
        if (typeof deal.canEdit === "boolean") return deal.canEdit
        return (
            canUpdateDeal ||
            isAdmin ||
            (Boolean(currentUserId) && deal.ownerId === currentUserId)
        )
    }, [deal, canUpdateDeal, isAdmin, currentUserId])

    const [assignTaskOpen, setAssignTaskOpen] = React.useState(false)
    const [isEditLeadOpen, setIsEditLeadOpen] = React.useState(false)
    const [isMoveToLostDialogOpen, setIsMoveToLostDialogOpen] = React.useState(false)
    const [lostReason, setLostReason] = React.useState("")
    const [selectedClosedLeadTagId, setSelectedClosedLeadTagId] = React.useState("")
    const { data: closedLeadTagCatalog = [] } = useGetClosedLeadTagsQuery(undefined, {
        skip: !isMoveToLostDialogOpen,
    })
    const pipelineTimeline = React.useMemo(() => buildPipelineTimelineStages(stages), [stages])
    const lostLeadStages = React.useMemo(() => listLostLeadStages(stages), [stages])

    React.useEffect(() => {
        if (!isMoveToLostDialogOpen) {
            setSelectedClosedLeadTagId("")
            return
        }
        const defaultTag =
            closedLeadTagCatalog.find((t) => t.isDefaultForClosedLost) ??
            (closedLeadTagCatalog.length === 1 ? closedLeadTagCatalog[0] : undefined)
        if (defaultTag) setSelectedClosedLeadTagId(defaultTag.id)
    }, [isMoveToLostDialogOpen, closedLeadTagCatalog])

    const dealMemberUserIds = React.useMemo(() => {
        if (!deal) return [] as string[]
        const d = deal as { team?: string; ownerId?: string; contributorIds?: string[] }
        return getDealMemberUserIds(d.team, d.ownerId, fullTeams, d.contributorIds)
    }, [deal, fullTeams])

    const lastStageMove = React.useMemo(() => {
        const timeline = Array.isArray(deal?.timeline) ? (deal.timeline as any[]) : []
        const sorted = [...timeline].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
        return sorted.find(entry => entry.title && entry.title.startsWith("Moved to"))
    }, [deal?.timeline])

    const closedLeadTagsConfigured = closedLeadTagCatalog.length > 0
    const closedLeadTagOptions = React.useMemo(
        () =>
            closedLeadTagCatalog.map((t) => ({
                value: t.id,
                label: `${t.name}${t.isDefaultForClosedLost ? " (default)" : ""}`,
            })),
        [closedLeadTagCatalog],
    )

    if (isLoading) {
        return (
            <Loading
                layout="page"
                message="Fetching this deal's details from the server. This usually takes a moment."
            />
        )
    }
    if (isError || !deal)
        return (
            <div className="flex flex-col items-center justify-center min-h-[300px] gap-5 p-8 text-center">
                <X className="size-16 text-red-500 bg-red-50 rounded-full p-4" />
                <h3 className="text-lg font-semibold text-gray-900">Could not load deal info</h3>
                <Button variant="outline" size="relaxed" onClick={onClose}>
                    Close View
                </Button>
            </div>
        )

    const si = pipelineTimeline.findIndex((s) => s.id === deal.stage)
    const currentStage = si !== -1 ? pipelineTimeline[si] : stages.find((s) => s.id === deal.stage)
    const isDiscoverMeetingBooked = isDiscoverMeetingBookedStage(deal, currentStage)
    const canCreateBusinessDeal = hasPermission(permissionSource, ["CREATE", "UPDATE"], "DEAL")

    const handleCreateBusinessDeal = () => {
        const toDateInput = (iso?: string | null) => {
            if (!iso) return ""
            const d = new Date(iso)
            if (Number.isNaN(d.getTime())) return ""
            return d.toISOString().slice(0, 10)
        }
        const leadTypeName =
            typeof deal.leadType === "object" && deal.leadType?.name
                ? deal.leadType.name
                : ""
        const projectTypeName =
            typeof deal.projectType === "object" && deal.projectType?.name
                ? deal.projectType.name
                : ""
        dispatch(
            openBusinessDealDialog({
                prefill: {
                    linkKind: "lead",
                    leadId: deal.id,
                    leadDisplayName:
                        deal.customerName?.trim() ||
                        deal.leadId ||
                        "",
                    pipelineId: deal.pipelineId,
                    title:
                        deal.customerName?.trim() ||
                        deal.leadId ||
                        "New business deal",
                    dealType: leadTypeName || projectTypeName || "",
                    region: "",
                    expectedCloseDate: toDateInput(deal.expectedPaymentDate),
                    dealValue:
                        deal.budget != null && Number.isFinite(Number(deal.budget))
                            ? String(deal.budget)
                            : "",
                    probability:
                        currentStage?.prob != null
                            ? String(currentStage.prob)
                            : "",
                    brand: deal.brand ?? "",
                    notes: deal.leadDetails ?? "",
                    ownerId: deal.ownerId,
                    aeIds: deal.aeIds ?? [],
                },
            }),
        )
    }

    const isScopingStage = Boolean(currentStage && (String(currentStage.id).toLowerCase().includes("scoping") || String(currentStage.name || "").toLowerCase().includes("scoping")))
    const isAlreadyCustomer = !!deal.customerId

    const nextStage = si !== -1 && si < pipelineTimeline.length - 1 ? pipelineTimeline[si + 1] : null

    const handleSaveLeadEdits = async (updated: Deal) => {
        try {
            const { id, ...rest } = updated
            const body = buildLeadUpdatePayload(rest)
            await updateDeal({ id, body }).unwrap()
            await refetch()
            setIsEditLeadOpen(false)
            toast.success("Lead updated successfully")
        } catch (err) {
            toast.error("Failed to update lead")
        }
    }

    const handleMoveToClosed = () => {
        setIsMoveToLostDialogOpen(true)
    }

    const confirmMoveToClosed = async () => {
        if (!deal) return
        const closedStage = stages.find(s =>
            s.id.toLowerCase().includes("closed_lost") ||
            s.id.toLowerCase().includes("lost") ||
            (s.name.toLowerCase().includes("closed") && s.name.toLowerCase().includes("lost"))
        )

        if (!closedStage) {
            toast.error("Could not find a 'Closed Lost' stage in this pipeline")
            return
        }

        try {
            await closeLostMutation({
                id: deal.id,
                stageId: closedStage.id,
                prob: closedStage.prob || 0,
                lostReason: lostReason.trim(),
                closedLeadTagId: selectedClosedLeadTagId,
            }).unwrap()
            markLocalDealBoardMove(deal.id, deal.stage, closedStage.id)
            invalidateLeadsBoardColumnsTouchingStages(queryClient, [
                deal.stage,
                closedStage.id,
            ])
            toast.success(`Lead moved to ${closedStage.name}`)
            setIsMoveToLostDialogOpen(false)
            setLostReason("")
            setSelectedClosedLeadTagId("")
        } catch (err) {
            toast.error("Failed to move to closed stage")
        }
    }

    const canConfirmCloseLost =
        Boolean(lostReason.trim()) &&
        Boolean(selectedClosedLeadTagId) &&
        closedLeadTagsConfigured

    const handleNextStage = async () => {
        if (!nextStage || !deal) return

        if (
            isEnteringDiscoverMeetingBookedStage(
                deal.stage,
                nextStage.id,
                stages,
            )
        ) {
            dispatch(
                openDiscoveryMeetingBookedDialog({
                    dealId: deal.id,
                    pipelineId: deal.pipelineId,
                    targetStageId: nextStage.id,
                    targetProb: nextStage.prob || 0,
                    sourceStageId: deal.stage,
                    customerName: deal.customerName ?? null,
                    moveContext: { kind: "detail" },
                }),
            )
            return
        }

        try {
            await moveDealMutation({
                id: deal.id,
                stageId: nextStage.id,
                prob: nextStage.prob || 0,
                pipelineId: deal.pipelineId
            }).unwrap()
            markLocalDealBoardMove(deal.id, deal.stage, nextStage.id)
            invalidateLeadsBoardColumnsTouchingStages(queryClient, [
                deal.stage,
                nextStage.id,
            ])
            toast.success(`Lead advanced to ${nextStage.name}`)
        } catch (err) {
            toast.error("Failed to move to next stage")
        }
    }

    const handleOpenGlobalMoveToLost = () => {
        if (!deal) return
        dispatch(
            openMoveToLostDialog({
                dealId: deal.id,
                pipelineId: deal.pipelineId,
                targetStageId: null,
                targetProb: 0,
                sourceStageId: deal.stage,
                customerName: deal.customerName ?? null,
                moveContext: { kind: "detail" },
            }),
        )
    }

    const showMoveToLostButton =
        !deal.isBusinessDeal &&
        lostLeadStages.length > 0 &&
        !isDealInLostStage(deal, stages)

    const notesCount = deal.dealNotes?.length ?? 0
    const remindersCount = deal.dealReminders?.length ?? 0

    return (
        <div className={cn("flex h-full flex-col overflow-hidden", !isFullPage && "max-h-[85vh]")}>
            {/* IDENTITY STRIP */}
            <div className="relative shrink-0 border-b border-gray-100 px-4 py-3 sm:px-8">
                <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                    <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
                        <h2 className="truncate text-lg font-semibold tracking-tight text-gray-900 font-['Lexend'] sm:text-xl">
                            {deal.customerName || "Unnamed Lead"}
                        </h2>
                        {currentStage?.name ? (
                            <>
                                <span className="hidden text-gray-300 sm:inline">|</span>
                                <Badge variant="outline" className="h-[18px] rounded-md border-[#6C63FF]/20 bg-[#6C63FF]/5 px-2 py-0 text-[10px] font-black uppercase tracking-widest text-[#6C63FF]">
                                    {currentStage.name}
                                </Badge>
                            </>
                        ) : null}
                        {(teamDisplayName || deal.team) ? (
                            <>
                                <span className="hidden text-gray-300 sm:inline">|</span>
                                <span className="text-sm font-medium text-gray-600">
                                    {teamDisplayName || formatTeamLabelForUi(deal.team)}
                                </span>
                            </>
                        ) : null}
                        {isAlreadyCustomer ? (
                            <span className="rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700">
                                Already a customer
                            </span>
                        ) : null}
                        {deal.leadStatus ? (
                            <span className="text-sm font-medium text-gray-500">{deal.leadStatus}</span>
                        ) : null}
                        {deal.leadId ? (
                            <span className="text-[11px] font-medium text-gray-400 font-['Lexend_Deca']">
                                {deal.leadId}
                            </span>
                        ) : null}
                    </div>

                    <div className="flex flex-wrap items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            className="h-8 gap-1.5 rounded-lg border-gray-200 text-xs font-semibold"
                            onClick={() => setNotesModalOpen(true)}
                        >
                            <MessageSquare className="size-3.5" />
                            Notes ({notesCount})
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            className="h-8 gap-1.5 rounded-lg border-gray-200 text-xs font-semibold"
                            onClick={() => setRemindersModalOpen(true)}
                        >
                            <Bell className="size-3.5" />
                            Reminders ({remindersCount})
                        </Button>
                        {canViewUserActivity ? (
                            <Button
                                variant="outlineSuccess"
                                size="sm"
                                className="h-8 gap-1.5 rounded-lg text-xs font-semibold"
                                onClick={() => router.push(`/leads/${deal.id}/user-deal-timeline`)}
                            >
                                <Users className="size-3.5" />
                                User Activity
                            </Button>
                        ) : null}

                        <ButtonGroup className="h-8">
                            {canUpdateDeal ? (
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant="outline"
                                            onClick={() => setIsEditLeadOpen(true)}
                                            size="icon-sm"
                                            className="rounded-[8px] border-[#6C63FF]/30 text-[#6C63FF] hover:bg-[#6C63FF]/8"
                                            title="Edit Lead"
                                        >
                                            <Pencil className="h-4 w-4" />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <p>Edit Lead</p>
                                    </TooltipContent>
                                </Tooltip>
                            ) : null}
                            {canUpdateDeal && deal.stage !== "closed_lost" && deal.stage !== "closed_won" ? (
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant="outline"
                                            onClick={handleMoveToClosed}
                                            size="icon-sm"
                                            className="rounded-[8px] border-red-200 text-red-500 hover:bg-red-50 hover:text-red-600"
                                            title="Move to Closed Lost"
                                        >
                                            <XCircle className="h-4 w-4" />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <p>Move to Closed Lost</p>
                                    </TooltipContent>
                                </Tooltip>
                            ) : null}
                            {nextStage && canUpdateDeal ? (
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant="accentStageNext"
                                            onClick={handleNextStage}
                                            size="icon-sm"
                                            className="rounded-[8px] px-0"
                                            disabled={isMovingDeal}
                                        >
                                            {isMovingDeal ? <Loader2 /> : <ArrowRight className="h-4 w-4" />}
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <p>Move to {nextStage.name}</p>
                                    </TooltipContent>
                                </Tooltip>
                            ) : null}
                        </ButtonGroup>

                        {channelName ? (
                            <div className="hidden text-right lg:block">
                                <p className="mb-0.5 text-[10px] font-medium uppercase tracking-widest text-gray-400">Channel</p>
                                <p className="text-sm font-semibold tracking-tight text-[#6C63FF] font-['Lexend']">{channelName}</p>
                            </div>
                        ) : null}
                        {deal.brand ? (
                            <>
                                <div className="hidden h-8 w-px bg-gray-200 lg:block" />
                                <div className="hidden text-right lg:block">
                                    <p className="mb-0.5 text-[10px] font-medium uppercase tracking-widest text-gray-400">Brand</p>
                                    <p className="text-sm font-semibold tracking-tight text-gray-900 font-['Lexend']">{deal.brand}</p>
                                </div>
                            </>
                        ) : null}
                    </div>
                </div>
            </div>

            {/* BODY — Main scroll + BANT sidebar */}
            <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
                <div className="grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-hidden px-4 py-4 sm:px-8 lg:grid-cols-[minmax(0,58fr)_minmax(0,42fr)] lg:gap-6">
                    <div className="min-h-0 space-y-6 overflow-y-auto pr-1 custom-scrollbar" ref={mainScrollRef}>
                        {isDiscoverMeetingBooked && !isAlreadyCustomer && !deal.isBusinessDeal && !convertedDealIds.has(deal.id) ? (
                            <DiscoveryMeetingBookedAlert
                                deal={deal}
                                canCreateBusinessDeal={canCreateBusinessDeal}
                                onCreateBusinessDeal={handleCreateBusinessDeal}
                                permissionSource={permissionSource}
                                onAfterVerify={() => void refetch()}
                            />
                        ) : null}

                        <section id="lead-section-details">
                            <SectionHeading icon={<Layout size={14} />}>Contact & Info</SectionHeading>
                            <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                <DetailItem label="Company" value={deal.companyName} icon={<Building2 size={14} />} />
                                <DetailItem label="Phone" value={deal.phone} icon={<Phone size={14} />} />
                                <DetailItem label="Home Phone" value={deal.homePhone} icon={<Phone size={14} />} />
                                <DetailItem label="Email" value={deal.email} icon={<Mail size={14} />} />
                                <DetailItem label="Address" value={deal.address} icon={<MapPin size={14} />} />
                                <DetailItem label="Lead Owner" value={deal.owner?.name} icon={<Users size={14} />} />
                                <DetailItem label="Created At" value={deal.createdDate ? new Date(deal.createdDate).toISOString().split("T")[0] : "—"} icon={<Clock size={14} />} />
                                <DetailItem label="Team" value={teamDisplayName || formatTeamLabelForUi(deal.team)} icon={<Briefcase size={14} />} />
                                <DetailItem label="Lead Channel" value={channelName} icon={<Tag size={14} />} />
                                {deal.brand ? (
                                    <DetailItem label="Brand" value={deal.brand} icon={<Briefcase size={14} />} />
                                ) : null}
                                <DetailItemAssigneeChips label="Assign AE" names={assigneeAeNames} icon={<UserCheck size={14} />} />
                                <DetailItemAssigneeChips label="Assign BDR" names={assigneeBdrNames} icon={<Users2 size={14} />} />
                                <DetailItemAssigneeChips label="Contributors" names={assigneeContributorNames} icon={<UserPlus size={14} />} />
                            </div>
                        </section>

                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                            <section>
                                <SectionHeading icon={<TrendingUp size={14} />}>Metrics & Timeline</SectionHeading>
                                <div className="mt-3 grid grid-cols-1 gap-3">
                                    <DetailItem label="Timeline Intent" value={deal.timelineIntent?.name} icon={<Timer size={14} />} />
                                </div>
                            </section>

                            {deal.leadDetails ? (
                                <section>
                                    <SectionHeading icon={<Mail size={14} />}>Lead Description</SectionHeading>
                                    <div className="mt-3">
                                        <ClampedDescription text={deal.leadDetails} />
                                    </div>
                                </section>
                            ) : null}
                        </div>

                        <section id="lead-section-tasks">
                            <SectionHeading icon={<ClipboardList size={14} />}>Tasks</SectionHeading>
                            <div className="mt-3 rounded-2xl border border-gray-100 bg-gray-50/30 p-4">
                                <DealTasksWidget
                                    dealId={dealId}
                                    assignableUserIds={isScopingStage ? dealMemberUserIds : undefined}
                                    taskModuleType={deal.isBusinessDeal ? "DEAL" : "LEAD"}
                                />
                            </div>
                        </section>
                    </div>

                    <div
                        className={cn(
                            "flex min-h-0 w-full min-w-0 flex-col overflow-hidden",
                            isFullPage
                                ? "lg:sticky lg:top-0 lg:self-start lg:h-[calc(100vh-11rem)]"
                                : "lg:h-full",
                        )}
                    >
                        <DealBantSidebar deal={deal} className="h-full" />
                    </div>
                </div>
            </div>

            <DealNotesModal
                open={notesModalOpen}
                onOpenChange={setNotesModalOpen}
                dealId={dealId}
                notes={deal.dealNotes || []}
                canEditNotes={canEditNotes}
                apiBaseUrl={apiBaseUrl}
                isFetching={isFetching}
                isLoading={isLoading}
            />

            <DealRemindersModal
                open={remindersModalOpen}
                onOpenChange={setRemindersModalOpen}
                dealId={deal.id}
                reminders={deal.dealReminders || []}
                allUsers={allUsers}
            />



            {
                assignTaskOpen && (
                    <React.Suspense fallback={null}>
                        <TaskFormModal
                            open={assignTaskOpen}
                            onClose={() => setAssignTaskOpen(false)}
                            dealId={dealId}
                            assignableUserIds={dealMemberUserIds}
                            title="Assign task"
                            defaultModuleType={deal.isBusinessDeal ? "DEAL" : "LEAD"}
                        />
                    </React.Suspense>
                )
            }
            {
                isEditLeadOpen && (
                    <React.Suspense fallback={null}>
                        <EditDealModal
                            deal={deal}
                            stages={stages}
                            teams={fullTeams.map((t) => ({
                                id: t.id,
                                name: t.name,
                                color: t.color ?? "#6C63FF",
                            }))}
                            isOpen={isEditLeadOpen}
                            onClose={() => setIsEditLeadOpen(false)}
                            onSave={handleSaveLeadEdits}
                        />
                    </React.Suspense>
                )
            }

            <Dialog open={isMoveToLostDialogOpen} onOpenChange={setIsMoveToLostDialogOpen}>
                <DialogContent className="sm:max-w-[425px] rounded-2xl border border-gray-100 bg-white p-0 shadow-xl overflow-hidden">
                    <div className="px-6 pt-6 pb-4">
                        <DialogHeader>
                            <div className="flex items-start gap-3 mb-2">
                                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-red-50">
                                    <XCircle className="h-5 w-5 text-red-600" />
                                </div>
                                <div className="text-left mt-0.5">
                                    <DialogTitle className="text-lg font-semibold text-gray-900">Close Deal</DialogTitle>
                                    <DialogDescription className="text-sm text-gray-500 mt-1.5 leading-relaxed">
                                        Provide a reason and select a closed lead tag for reporting and search on the leads board.
                                    </DialogDescription>
                                </div>
                            </div>
                        </DialogHeader>

                        <div className="mt-4 space-y-2">
                            <Label htmlFor="lostReason" className="text-xs font-semibold text-gray-600">
                                Reason for Loss
                            </Label>
                            <Textarea
                                id="lostReason"
                                placeholder="e.g. Budget constraints, chose a competitor, timing not right..."
                                className="min-h-[100px] resize-none text-[13px] focus-visible:ring-red-500 rounded-xl bg-white"
                                value={lostReason}
                                onChange={(e) => setLostReason(e.target.value)}
                                autoFocus
                            />
                        </div>
                        <div className="mt-4 space-y-2">
                            <Label htmlFor="closedLeadTag" className="text-xs font-semibold text-gray-600">
                                Closed lead tag
                            </Label>
                            {closedLeadTagsConfigured ? (
                                <ReactSelect
                                    id="closedLeadTag"
                                    value={selectedClosedLeadTagId || ""}
                                    onValueChange={setSelectedClosedLeadTagId}
                                    options={closedLeadTagOptions}
                                    placeholder="Select a tag"
                                    triggerClassName="min-h-10 rounded-xl bg-white"
                                />
                            ) : (
                                <p className="text-[12px] text-amber-700 bg-amber-50 border border-amber-100 rounded-xl px-3 py-2">
                                    No closed lead tags configured — ask an admin (Extra Content).
                                </p>
                            )}
                        </div>
                    </div>

                    <DialogFooter className="bg-gray-50/80 px-6 py-4 border-t border-gray-100 sm:justify-end flex flex-row gap-2">
                        <Button
                            variant="outline"
                            onClick={() => setIsMoveToLostDialogOpen(false)}
                            className="rounded-lg text-[13px] font-semibold h-10 px-5"
                        >
                            Cancel
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={confirmMoveToClosed}
                            disabled={!canConfirmCloseLost || isClosingLost}
                            className="rounded-lg text-[13px] font-semibold h-10 px-5 bg-red-600 hover:bg-red-700 text-white shadow-sm"
                        >
                            {isClosingLost ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                            Move to Closed Lost
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div >
    )
}




