"use client";

import * as React from "react";
import { Deal, DealReminder, Stage } from "./types";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import {
  MessageSquare,
  Bell,
  User as UserIcon,
  Users2,
  Send,
  Building2,
  FileText,
  Upload,
  Trash2,
  ExternalLink,
  Phone,
  Mail,
  MapPin,
  Plus,
  ListChecks,
  Pencil,
  Settings2,
  Activity,
  Loader2,
} from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { DatePicker } from "@/components/ui/date-picker";
import { ReactSelect } from "@/components/ui/react-select";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { apiBaseUrl } from "@/api/client";
import {
  useAddDealNoteMutation,
  useUpdateDealNoteMutation,
  useDeleteDealNoteMutation,
  useGetDealProposalsQuery,
  useUploadDealProposalMutation,
  useDeleteDealProposalMutation,
  useCreateDealReminderMutation,
  useDeleteDealReminderMutation,
  useGetAllUsersQuery,
  useGetLeadChannelsQuery,
  useGetServicesQuery,
  useGetLeadTypesQuery,
  useCreateLeadTypeMutation,
  useUpdateLeadTypeMutation,
  useDeleteLeadTypeMutation,
  useGetProjectTypesQuery,
  useCreateProjectTypeMutation,
  useUpdateProjectTypeMutation,
  useDeleteProjectTypeMutation,
  useGetPipelinesQuery,
  useGetTimelineIntentsQuery,
  useGetCustomersQuery,
  useGetRolesQuery,
  useGetDealQuery,
} from "@/api/rtk";
import { useGetTeamsQuery } from "@/api/rtk/teams-api";
import { useAppSelector } from "@/store/hooks";
import { useAuthToken } from "@/hooks/use-auth-token";
import { DialogTitle, Dialog, DialogContent } from "@/components/ui/dialog";
import { DeleteDialog } from "@/components/ui/delete-dialog";
import { toast } from "sonner";
import { useAbility } from "@/components/providers/ability-provider";
import { BrandSelect } from "@/components/shared/brand-select";
import { LeadStatusSelect } from "@/components/shared/lead-status-select";
import { TagsInput } from "./tags-input";
import {
  ContributorUserPicker,
  pickRoleIdFromOrgRoles,
} from "./contributor-user-picker";
import type { AuthUser } from "@/api/auth/types";

const NO_OWNER_VALUE = "__none";

interface EditDealModalProps {
  deal: Deal | null;
  stages?: Stage[];
  teams?: { id: string; name: string; color: string }[];
  isOpen: boolean;
  onClose: () => void;
  onSave: (deal: Deal) => void;
}

/* ─── small reusable field label ─── */
function FieldLabel({ children }: { children: React.ReactNode }) {
  return (
    <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
      {children}
    </label>
  );
}

export function EditDealModal({
  deal,
  stages = [],
  teams,
  isOpen,
  onClose,
  onSave,
}: EditDealModalProps) {
  // const ability = useAbility()
  const { token: accessToken } = useAuthToken();
  const [editedDeal, setEditedDeal] = React.useState<Deal | null>(null);
  const [addNoteMutation] = useAddDealNoteMutation();
  const [updateNoteMutation] = useUpdateDealNoteMutation();
  const [deleteNoteMutation, { isLoading: isDeletingNote }] =
    useDeleteDealNoteMutation();
  const [uploadProposal] = useUploadDealProposalMutation();
  const [deleteProposal] = useDeleteDealProposalMutation();
  const [createReminder] = useCreateDealReminderMutation();
  const [deleteReminder] = useDeleteDealReminderMutation();
  const { data: proposals = [], isLoading: proposalsLoading } =
    useGetDealProposalsQuery(deal?.id ?? "", {
      skip: !deal?.id || !isOpen,
    });
  const [newNoteText, setNewNoteText] = React.useState("");
  const [editingNoteId, setEditingNoteId] = React.useState<string | null>(null);
  const [editingNoteText, setEditingNoteText] = React.useState("");
  const [deleteNoteId, setDeleteNoteId] = React.useState<string | null>(null);
  const [reminderText, setReminderText] = React.useState("");
  const [reminderDate, setReminderDate] = React.useState("");
  const [reminderTarget, setReminderTarget] = React.useState<"SELF" | "USERS">(
    "SELF",
  );
  const [selectedUserIds, setSelectedUserIds] = React.useState<string[]>([]);
  const [reminderErrors, setReminderErrors] = React.useState<{
    text?: string;
    date?: string;
    users?: string;
  }>({});
  const [isSaving, setIsSaving] = React.useState(false);
  const notesEndRef = React.useRef<HTMLDivElement>(null);

  const { data: allUsers = [] } = useGetAllUsersQuery(undefined, {
    skip: !accessToken,
  });
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, {
    skip: !isOpen || !accessToken,
  });
  const { data: fullTeams = [] } = useGetTeamsQuery(undefined, {
    skip: !isOpen,
  });

  const teamMembers = React.useMemo(() => {
    const teamSlug = editedDeal?.team;
    if (!teamSlug || teamSlug === "all") return allUsers;
    const matched = fullTeams.find(
      (t) => t.name.toLowerCase().replace(/\s+/g, "-") === teamSlug,
    );
    if (!matched || !matched.members?.length) return allUsers;
    return allUsers.filter((u) => matched.members.includes(u.id));
  }, [editedDeal?.team, fullTeams, allUsers]);

  /** Include current owner so the select can show a label when owner is outside teamMembers. */
  const leadOwnerSelectUsers = React.useMemo(() => {
    const base = teamMembers;
    const oid =
      editedDeal?.ownerId ?? editedDeal?.owner?.id;
    if (!oid) return base;
    if (base.some((u) => u.id === oid)) return base;
    const fromAll = allUsers.find((u) => u.id === oid);
    if (fromAll) return [fromAll, ...base];
    const owner = editedDeal?.owner;
    if (owner?.id && owner.name) {
      const synthetic: AuthUser = {
        _id: owner.id,
        id: owner.id,
        name: owner.name,
        email: owner.email ?? "",
      };
      return [synthetic, ...base];
    }
    return base;
  }, [teamMembers, editedDeal?.ownerId, editedDeal?.owner, allUsers]);

  const aeUsers = React.useMemo(() => {
    const usersArray = Array.isArray(teamMembers) ? teamMembers : [];
    return usersArray.filter((u) => {
      const roleName =
        typeof u.role === "string" ? u.role : (u.role as any)?.name;
      return (
        roleName?.toUpperCase() === "AE" ||
        roleName?.toUpperCase() === "ACCOUNT EXECUTIVE"
      );
    });
  }, [teamMembers]);

  const bdrUsers = React.useMemo(() => {
    const usersArray = Array.isArray(teamMembers) ? teamMembers : [];
    return usersArray.filter((u) => {
      const roleName =
        typeof u.role === "string" ? u.role : (u.role as any)?.name;
      return (
        roleName?.toUpperCase() === "BDR" ||
        roleName?.toUpperCase() === "BUSINESS DEVELOPMENT REPRESENTATIVE"
      );
    });
  }, [teamMembers]);

  const aeRoleId = React.useMemo(
    () => pickRoleIdFromOrgRoles(orgRoles, ["ae", "account executive"]),
    [orgRoles],
  );
  const bdrRoleId = React.useMemo(
    () =>
      pickRoleIdFromOrgRoles(orgRoles, [
        "bdr",
        "business development representative",
      ]),
    [orgRoles],
  );

  const assigneeRestrictToUserIds = React.useMemo(() => {
    const teamSlug = editedDeal?.team;
    if (!teamSlug || teamSlug === "all") return undefined;
    return teamMembers.map((u) => u.id);
  }, [editedDeal?.team, teamMembers]);

  const contributorLabelById = React.useMemo(() => {
    const m: Record<string, string> = {};
    for (const u of allUsers) {
      m[u.id] = u.name || u.email || u.id;
    }
    editedDeal?.contributors?.forEach((c) => {
      if (c.name) m[c.id] = c.name;
    });
    editedDeal?.aes?.forEach((a) => {
      if (a.name) m[a.id] = a.name;
    });
    editedDeal?.bdrs?.forEach((b) => {
      if (b.name) m[b.id] = b.name;
    });
    return m;
  }, [allUsers, editedDeal?.contributors, editedDeal?.aes, editedDeal?.bdrs]);

  const { data: pipelines = [] } = useGetPipelinesQuery(undefined, {
    skip: !isOpen,
  });
  const stagesFromPipeline: Stage[] = editedDeal?.pipelineId
    ? ((pipelines.find((p) => p.id === editedDeal.pipelineId)?.stages ??
        []) as Stage[])
    : [];
  const stagesForDropdown =
    stagesFromPipeline.length > 0 ? stagesFromPipeline : stages;
  const { data: leadChannels = [] } = useGetLeadChannelsQuery(undefined, {
    skip: !isOpen,
  });
  const { data: services = [] } = useGetServicesQuery(undefined, {
    skip: !isOpen,
  });
  const { data: leadTypes = [] } = useGetLeadTypesQuery(undefined, {
    skip: !isOpen,
  });
  const { data: projectTypes = [] } = useGetProjectTypesQuery(undefined, {
    skip: !isOpen,
  });
  const [createLeadType, { isLoading: creatingLeadType }] =
    useCreateLeadTypeMutation();
  const [updateLeadType, { isLoading: updatingLeadType }] =
    useUpdateLeadTypeMutation();
  const [deleteLeadType] = useDeleteLeadTypeMutation();
  const [addLeadTypeOpen, setAddLeadTypeOpen] = React.useState(false);
  const [manageLeadTypesOpen, setManageLeadTypesOpen] = React.useState(false);
  const [newLeadTypeName, setNewLeadTypeName] = React.useState("");
  const [editingLeadTypeId, setEditingLeadTypeId] = React.useState<
    string | null
  >(null);
  const [editingLeadTypeName, setEditingLeadTypeName] = React.useState("");
  const [createProjectType, { isLoading: creatingProjectType }] =
    useCreateProjectTypeMutation();
  const [updateProjectType, { isLoading: updatingProjectType }] =
    useUpdateProjectTypeMutation();
  const [deleteProjectType] = useDeleteProjectTypeMutation();
  const [addProjectTypeOpen, setAddProjectTypeOpen] = React.useState(false);
  const [manageProjectTypesOpen, setManageProjectTypesOpen] =
    React.useState(false);
  const [newProjectTypeName, setNewProjectTypeName] = React.useState("");
  const [editingProjectTypeId, setEditingProjectTypeId] = React.useState<
    string | null
  >(null);
  const [editingProjectTypeName, setEditingProjectTypeName] =
    React.useState("");
  const { data: timelineIntents = [], refetch: refetchTimelineIntents } =
    useGetTimelineIntentsQuery(undefined, { skip: !isOpen });
  const { data: customers = [] } = useGetCustomersQuery(undefined, {
    skip: !isOpen,
  });

  const timelineIntentOptions = React.useMemo(
    () => timelineIntents.map((opt) => ({ value: opt.id, label: opt.name })),
    [timelineIntents],
  );
  const teamOptions = React.useMemo(
    () => [
      { value: "all", label: "No Team" },
      ...(teams?.map((t) => ({
        value: t.name.toLowerCase().replace(/\s+/g, "-"),
        label: formatTeamLabelForUi(t.name),
      })) ?? []),
    ],
    [teams],
  );
  const leadOwnerOptions = React.useMemo(
    () => [
      { value: NO_OWNER_VALUE, label: "No owner" },
      ...leadOwnerSelectUsers.map((u) => ({ value: u.id, label: u.name })),
    ],
    [leadOwnerSelectUsers],
  );
  const leadChannelOptions = React.useMemo(
    () => leadChannels.map((c) => ({ value: c.id, label: c.name })),
    [leadChannels],
  );
  const serviceOptions = React.useMemo(
    () => services.map((s) => ({ value: s.id, label: s.name })),
    [services],
  );

  // Lead board payloads can omit heavy text fields (like leadDetails), so hydrate by id when needed.
  const shouldHydrateDeal = isOpen && !!deal?.id && deal.leadDetails === undefined;
  const { data: hydratedDeal } = useGetDealQuery(deal?.id ?? "", {
    skip: !shouldHydrateDeal,
  });

  // Prevent non-numeric input in number fields
  const handleNumericKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Allow: backspace, delete, tab, escape, enter, decimal point, minus
    if (
      [8, 9, 27, 13, 46, 110, 190, 189, 109].includes(e.keyCode) ||
      // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
      (e.keyCode === 65 && e.ctrlKey === true) ||
      (e.keyCode === 67 && e.ctrlKey === true) ||
      (e.keyCode === 86 && e.ctrlKey === true) ||
      (e.keyCode === 88 && e.ctrlKey === true) ||
      // Allow: home, end, left, right
      (e.keyCode >= 35 && e.keyCode <= 39)
    ) {
      return;
    }
    // Prevent if not a number
    if (
      (e.shiftKey || e.keyCode < 48 || e.keyCode > 57) &&
      (e.keyCode < 96 || e.keyCode > 105)
    ) {
      e.preventDefault();
    }
  };

  // Handle phone input - allow only numbers, spaces, dashes, plus, and brackets
  const handlePhoneKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Allow: backspace, delete, tab, escape, enter
    if (
      [8, 9, 27, 13, 46].includes(e.keyCode) ||
      // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
      (e.keyCode === 65 && e.ctrlKey === true) ||
      (e.keyCode === 67 && e.ctrlKey === true) ||
      (e.keyCode === 86 && e.ctrlKey === true) ||
      (e.keyCode === 88 && e.ctrlKey === true) ||
      // Allow: home, end, left, right
      (e.keyCode >= 35 && e.keyCode <= 39)
    ) {
      return;
    }
    // Allow: numbers (0-9), space, dash, plus, parentheses
    const char = e.key;
    if (!/^[0-9\s\-\+\(\)]$/.test(char)) {
      e.preventDefault();
    }
  };

  // Handle year input - restrict to exactly 4 digits
  const handleYearChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, "").slice(0, 4);
    handleUpdate({ year: value ? parseInt(value) : undefined });
  };

  React.useLayoutEffect(() => {
    if (!isOpen) {
      setEditedDeal(null);
      return;
    }
    if (!deal) return;
    const sourceDeal = (() => {
      if (!hydratedDeal) return deal;
      // Parent `deal` can already be richer (e.g. detail page payload). Only backfill missing fields.
      const merged = { ...hydratedDeal, ...deal } as Deal;
      for (const [key, value] of Object.entries(deal)) {
        if (value !== undefined && value !== null && value !== "") {
          (merged as unknown as Record<string, unknown>)[key] = value;
        }
      }
      return merged;
    })();
    setEditedDeal((prev) => {
      const ownerId = sourceDeal.ownerId ?? sourceDeal.owner?.id;
      const team = sourceDeal.team
        ? sourceDeal.team.toLowerCase().replace(/\s+/g, "-")
        : undefined;
      const base = {
        ...sourceDeal,
        team,
        ownerId,
        month:
          sourceDeal.month ||
          new Date().toLocaleString("en-US", { month: "long" }),
        year: sourceDeal.year ?? new Date().getFullYear(),
      };
      if (prev?.id !== sourceDeal.id) return base;
      const prevOwnerId = prev.ownerId ?? prev.owner?.id;
      if (ownerId && ownerId !== prevOwnerId) {
        return {
          ...prev,
          ownerId,
          owner: sourceDeal.owner ?? prev.owner,
        };
      }
      if (prev.leadDetails === undefined && sourceDeal.leadDetails !== undefined) {
        return {
          ...prev,
          leadDetails: sourceDeal.leadDetails,
        };
      }
      return prev;
    });
  }, [isOpen, deal, hydratedDeal]);

  const handleSaveLocal = async () => {
    if (!editedDeal) return;

    // Validate required fields
    if (!editedDeal.customerName?.trim()) {
      toast.error("Customer name is required");
      return;
    }
    if (!editedDeal.email?.trim()) {
      toast.error("Email is required");
      return;
    }
    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(editedDeal.email)) {
      toast.error("Invalid email format");
      return;
    }
    if (!editedDeal.phone?.trim()) {
      toast.error("Phone number is required");
      return;
    }
    // Validate phone format
    const phoneRegex = /^[\d\s\-\+\(\)]+$/;
    if (!phoneRegex.test(editedDeal.phone)) {
      toast.error("Invalid phone number format");
      return;
    }
    const homeTrim = editedDeal.homePhone?.trim();
    if (homeTrim && !phoneRegex.test(homeTrim)) {
      toast.error("Invalid home phone number format");
      return;
    }
    if (!editedDeal.address?.trim()) {
      toast.error("Address is required");
      return;
    }

    setIsSaving(true);
    try {
      await onSave({
        ...editedDeal,
        homePhone: homeTrim || undefined,
        purchaseCount: 0,
        budget: 0,
        expectedPaymentDate: undefined,
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddNote = async (text: string) => {
    if (!text.trim() || !editedDeal) return;
    try {
      await addNoteMutation({ dealId: editedDeal.id, text }).unwrap();
      toast.success("Note added successfully");
      setNewNoteText("");
      setTimeout(
        () => notesEndRef.current?.scrollIntoView({ behavior: "smooth" }),
        100,
      );
    } catch (err) {
      console.error("Failed to add note:", err);
      toast.error("Failed to add note");
    }
  };

  const handleUpdateNote = async (noteId: string, text: string) => {
    if (!text.trim() || !editedDeal) return;
    try {
      await updateNoteMutation({
        dealId: editedDeal.id,
        noteId,
        text,
      }).unwrap();
      toast.success("Note updated");
      setEditingNoteId(null);
      setEditingNoteText("");
    } catch (err) {
      console.error("Failed to update note:", err);
      toast.error("Failed to update note");
    }
  };

  const handleDeleteNote = async (noteId: string) => {
    if (!editedDeal) return;
    try {
      await deleteNoteMutation({ dealId: editedDeal.id, noteId }).unwrap();
      toast.success("Note deleted");
      setDeleteNoteId(null);
    } catch (err) {
      console.error("Failed to delete note:", err);
      toast.error("Failed to delete note");
      throw err;
    }
  };

  const handleUpdate = (updates: Partial<Deal>) => {
    setEditedDeal((prev) => (prev ? { ...prev, ...updates } : prev));
  };


  const handleAddLeadType = async () => {
    const name = newLeadTypeName.trim();
    if (!name) return;
    try {
      const result = await createLeadType({ name }).unwrap();
      handleUpdate({ leadTypeId: result.id });
      setNewLeadTypeName("");
      setAddLeadTypeOpen(false);
      toast.success("Lead Type added");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Failed to add Lead Type");
    }
  };

  const handleUpdateLeadType = async () => {
    if (!editingLeadTypeId || !editingLeadTypeName.trim()) return;
    try {
      await updateLeadType({
        id: editingLeadTypeId,
        name: editingLeadTypeName.trim(),
      }).unwrap();
      setEditingLeadTypeId(null);
      setEditingLeadTypeName("");
      toast.success("Lead Type updated");
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : "Failed to update Lead Type",
      );
    }
  };

  const handleDeleteLeadType = async (id: string, name: string) => {
    if (!confirm(`Delete Lead Type "${name}"?`)) return;
    try {
      await deleteLeadType(id).unwrap();
      if (editedDeal?.leadTypeId === id) handleUpdate({ leadTypeId: "" });
      toast.success("Lead Type deleted");
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : "Failed to delete Lead Type",
      );
    }
  };

  const handleAddProjectType = async () => {
    const name = newProjectTypeName.trim();
    if (!name) return;
    try {
      const result = await createProjectType({ name }).unwrap();
      handleUpdate({ projectTypeId: result.id });
      setNewProjectTypeName("");
      setAddProjectTypeOpen(false);
      toast.success("Project type added");
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : "Failed to add project type",
      );
    }
  };

  const handleUpdateProjectType = async () => {
    if (!editingProjectTypeId || !editingProjectTypeName.trim()) return;
    try {
      const result = await updateProjectType({
        id: editingProjectTypeId,
        name: editingProjectTypeName.trim(),
      }).unwrap();
      if (editedDeal?.projectTypeId === editingProjectTypeId)
        handleUpdate({ projectTypeId: result.id });
      setEditingProjectTypeId(null);
      setEditingProjectTypeName("");
      toast.success("Project type updated");
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : "Failed to update project type",
      );
    }
  };

  const handleDeleteProjectType = async (id: string, name: string) => {
    if (!confirm(`Delete project type "${name}"?`)) return;
    try {
      await deleteProjectType(id).unwrap();
      if (editedDeal?.projectTypeId === id) handleUpdate({ projectTypeId: "" });
      toast.success("Project type deleted");
    } catch (e) {
      toast.error(
        e instanceof Error ? e.message : "Failed to delete project type",
      );
    }
  };

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

  const handleAddReminder = async () => {
    setReminderErrors({});
    const errors: { text?: string; date?: string; users?: string } = {};
    if (!reminderText.trim()) errors.text = "Reminder text is required";
    if (!reminderDate) errors.date = "Date & time is required";
    if (reminderTarget === "USERS" && selectedUserIds.length === 0)
      errors.users = "Please select at least one user";
    if (Object.keys(errors).length > 0) {
      setReminderErrors(errors);
      toast.error("Please fill required fields");
      return;
    }
    if (!editedDeal) return;

    try {
      const created = await createReminder({
        dealId: editedDeal.id,
        text: reminderText.trim(),
        remindAt: new Date(reminderDate).toISOString(),
        targetType: reminderTarget,
        targetUserIds: reminderTarget === "USERS" ? selectedUserIds : undefined,
      }).unwrap();
      toast.success("Reminder added");
      setReminderText("");
      setReminderDate("");
      setSelectedUserIds([]);
      setReminderErrors({});
      setEditedDeal((prev) =>
        prev
          ? {
              ...prev,
              dealReminders: [...(prev.dealReminders || []), created],
            }
          : prev,
      );
    } catch (err) {
      console.error("Failed to add reminder:", err);
      toast.error("Failed to add reminder");
    }
  };

  const handleDeleteReminder = async (reminderId: string) => {
    if (!editedDeal) return;
    try {
      await deleteReminder({ dealId: editedDeal.id, reminderId }).unwrap();
      toast.success("Reminder removed");
      setEditedDeal((prev) =>
        prev
          ? {
              ...prev,
              dealReminders: (prev.dealReminders || []).filter(
                (r) => r.id !== reminderId,
              ),
            }
          : prev,
      );
    } catch (err) {
      console.error("Failed to delete reminder:", err);
      toast.error("Failed to remove reminder");
    }
  };

  const handleDeleteProposal = async (documentId: string) => {
    if (!editedDeal) return;
    try {
      await deleteProposal({ dealId: editedDeal.id, documentId }).unwrap();
      toast.success("Document removed");
    } catch (err) {
      console.error("Delete failed:", err);
      toast.error("Failed to remove document");
    }
  };

  const getDownloadUrl = (fileUrl: string) => {
    const base = apiBaseUrl.replace(/\/$/, "");
    const path = fileUrl.startsWith("/") ? fileUrl : `/${fileUrl}`;
    return `${base}${path}`;
  };

  if (!isOpen) return null;

  if (!deal) return null;

  if (!editedDeal) {
    return (
      <Dialog
        open={isOpen}
        onOpenChange={(open) => {
          if (!open) onClose();
        }}
      >
        <DialogContent className="flex w-[96vw] max-w-md items-center justify-center p-10 sm:max-w-md">
          <Loader2
            className="size-10 animate-spin text-[#6C63FF]"
            aria-label="Loading lead"
          />
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog
      open={isOpen}
      onOpenChange={(open) => {
        if (!open) onClose();
      }}
    >
      <DialogContent className="sm:max-w-[1120px] w-[96vw] max-h-[95vh] p-0 overflow-hidden animate-in zoom-in-95 duration-200">
        {/* HEADER */}
        <div className="relative overflow-hidden">
          <div className="absolute inset-0 bg-linear-to-br from-[#6C63FF] via-[#7C74FF] to-[#9B8FFF] opacity-100" />
          <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(255,255,255,0.12),transparent_60%)]" />

          <div className="relative px-7 py-5 flex items-start justify-between gap-4">
            <div className="flex items-center gap-4 min-w-0">
              <div className="h-12 w-12 rounded-xl bg-white/15 border border-white/25 backdrop-blur-sm flex items-center justify-center shrink-0 shadow-inner">
                <Building2 size={22} className="text-white/90" />
              </div>
              <div className="min-w-0">
                <DialogTitle className="text-[20px] font-extrabold text-white font-['Lexend'] leading-tight truncate">
                  Edit Lead: {editedDeal.customerName || "Unnamed Lead"}
                </DialogTitle>
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  {editedDeal.leadStatus && (
                    <span className="text-[12px] text-white/75 font-medium">
                      {editedDeal.leadStatus}
                    </span>
                  )}
                  {editedDeal.team && (
                    <>
                      <span className="text-white/30">·</span>
                      <span className="text-[12px] text-white/75 font-medium">
                        {formatTeamLabelForUi(editedDeal.team)}
                      </span>
                    </>
                  )}
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3 shrink-0">
              {editedDeal.leadChannel && (
                <div className="bg-white/10 border border-white/20 rounded-xl px-4 py-2.5 text-center backdrop-blur-sm">
                  <p className="text-[10px] font-bold text-white/60 uppercase tracking-widest font-['Lexend_Deca']">
                    Channel
                  </p>
                  <p className="text-[14px] font-extrabold text-white font-['Lexend'] leading-tight">
                    {typeof editedDeal.leadChannel === "string"
                      ? editedDeal.leadChannel
                      : editedDeal.leadChannel?.name || "—"}
                  </p>
                </div>
              )}
              {editedDeal.brand && (
                <div className="bg-white/10 border border-white/20 rounded-xl px-4 py-2.5 text-center backdrop-blur-sm">
                  <p className="text-[10px] font-bold text-white/60 uppercase tracking-widest font-['Lexend_Deca']">
                    Brand
                  </p>
                  <p className="text-[14px] font-extrabold text-white font-['Lexend'] leading-tight">
                    {editedDeal.brand}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* BODY */}
        <div className="overflow-y-auto max-h-[calc(95vh-210px)] scrollbar-themed">
          <div className="w-full">
            <div className="px-7 py-6 space-y-7">
              <section>
                <SectionHeading icon={<Building2 size={14} />}>
                  Customer Information
                </SectionHeading>
                <div className="grid grid-cols-2 gap-4 mt-4">
                  <div>
                    <FieldLabel>
                      Customer Name <span className="text-red-500">*</span>
                    </FieldLabel>
                    <Input
                      className="h-10 text-[14px] font-semibold bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.customerName || ""}
                      onChange={(e) =>
                        handleUpdate({ customerName: e.target.value })
                      }
                    />
                  </div>
                  <div>
                    <FieldLabel>Company Name</FieldLabel>
                    <Input
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.companyName || ""}
                      onChange={(e) =>
                        handleUpdate({
                          companyName: e.target.value || undefined,
                        })
                      }
                      placeholder="Organization (optional)"
                    />
                  </div>
                  <div>
                    <FieldLabel>
                      Email <span className="text-red-500">*</span>
                    </FieldLabel>
                    <Input
                      type="email"
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.email || ""}
                      onChange={(e) => handleUpdate({ email: e.target.value })}
                    />
                  </div>
                  <div>
                    <FieldLabel>
                      Phone <span className="text-red-500">*</span>
                    </FieldLabel>
                    <Input
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.phone || ""}
                      onChange={(e) => handleUpdate({ phone: e.target.value })}
                      onKeyDown={handlePhoneKeyDown}
                    />
                  </div>
                  <div>
                    <FieldLabel>Home Phone</FieldLabel>
                    <Input
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.homePhone || ""}
                      onChange={(e) =>
                        handleUpdate({
                          homePhone: e.target.value || undefined,
                        })
                      }
                      onKeyDown={handlePhoneKeyDown}
                      placeholder="Optional"
                    />
                  </div>
                  <div>
                    <FieldLabel>
                      Address <span className="text-red-500">*</span>
                    </FieldLabel>
                    <Input
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.address || ""}
                      onChange={(e) =>
                        handleUpdate({ address: e.target.value })
                      }
                    />
                  </div>
                  <div>
                    <FieldLabel>Postal Code</FieldLabel>
                    <Input
                      className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                      value={editedDeal.postalCode || ""}
                      onChange={(e) =>
                        handleUpdate({ postalCode: e.target.value })
                      }
                    />
                  </div>
                  <div>
                    <FieldLabel>Timeline Intent</FieldLabel>
                    <div className="flex items-center gap-2">
                      <ReactSelect
                        value={editedDeal.timelineIntentId ?? ""}
                        onValueChange={(v) =>
                          handleUpdate({
                            timelineIntentId: v === "" ? undefined : v,
                          })
                        }
                        options={timelineIntentOptions}
                        placeholder="ASAP / Within a week..."
                        allowEmpty
                        triggerClassName="h-10 min-h-10 flex-1 min-w-0 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        contentClassName="rounded-xl"
                      />
                    </div>
                  </div>
                </div>
              </section>
              <section>
                <SectionHeading icon={<Phone size={14} />}>
                  Lead Classification
                </SectionHeading>
                <div className="mt-4 grid grid-cols-1 gap-x-4 gap-y-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 [&>div]:min-w-0">
                  <div>
                    <FieldLabel>Team</FieldLabel>
                    <ReactSelect
                      value={
                        editedDeal.team
                          ? editedDeal.team.toLowerCase().replace(/\s+/g, "-")
                          : "all"
                      }
                      onValueChange={(val) =>
                        handleUpdate({
                          team: val === "all" ? undefined : val,
                        })
                      }
                      options={teamOptions}
                      triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                    />
                  </div>
                  <div>
                    <FieldLabel>Lead Owner</FieldLabel>
                    <ReactSelect
                      value={
                        editedDeal.ownerId ??
                        editedDeal.owner?.id ??
                        NO_OWNER_VALUE
                      }
                      onValueChange={(val) =>
                        handleUpdate({
                          ownerId: val === NO_OWNER_VALUE ? undefined : val,
                        })
                      }
                      options={leadOwnerOptions}
                      placeholder="Select owner"
                      triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                    />
                  </div>
                  <div>
                    <FieldLabel>Assign AE</FieldLabel>
                    <ContributorUserPicker
                      value={editedDeal.aeIds || []}
                      onChange={(val) => handleUpdate({ aeIds: val })}
                      labelById={contributorLabelById}
                      placeholder="Select AEs"
                      className="border-gray-200 bg-gray-50"
                      roleId={aeRoleId}
                      restrictToUserIds={assigneeRestrictToUserIds}
                      staticUserPool={aeRoleId ? undefined : aeUsers}
                      emptyListMessage="No account executives match your search for this team."
                    />
                  </div>
                  <div>
                    <FieldLabel>Assign BDR</FieldLabel>
                    <ContributorUserPicker
                      value={editedDeal.bdrIds || []}
                      onChange={(val) => handleUpdate({ bdrIds: val })}
                      labelById={contributorLabelById}
                      placeholder="Select BDRs"
                      className="border-gray-200 bg-gray-50"
                      roleId={bdrRoleId}
                      restrictToUserIds={assigneeRestrictToUserIds}
                      staticUserPool={bdrRoleId ? undefined : bdrUsers}
                      emptyListMessage="No BDRs match your search for this team."
                    />
                  </div>
                  <div>
                    <FieldLabel>Contributors</FieldLabel>
                    <ContributorUserPicker
                      value={editedDeal.contributorIds || []}
                      onChange={(val) => handleUpdate({ contributorIds: val })}
                      labelById={contributorLabelById}
                      placeholder="Select contributors"
                      className="border-gray-200 bg-gray-50"
                    />
                  </div>
                  <div>
                    <FieldLabel>Created By</FieldLabel>
                    <div className="h-10 flex items-center px-3 rounded-xl border border-gray-200 bg-gray-50/80 text-[13px] font-semibold text-gray-700">
                      {editedDeal.createdBy || "—"}
                    </div>
                  </div>
                  <div>
                    <LeadStatusSelect
                      value={editedDeal.leadStatus ?? ""}
                      onValueChange={(val) => handleUpdate({ leadStatus: val })}
                      label="Lead Status"
                      placeholder="Select status"
                      allowEmpty
                      skip={!isOpen}
                      triggerClassName="h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                    />
                  </div>
                  <div>
                    <FieldLabel>Lead Channel</FieldLabel>
                    <div className="flex items-center gap-2">
                      <ReactSelect
                        value={editedDeal.leadChannelId || ""}
                        onValueChange={(val) =>
                          handleUpdate({ leadChannelId: val })
                        }
                        options={leadChannelOptions}
                        placeholder="Select"
                        triggerClassName="h-10 min-h-10 flex-1 min-w-0 bg-gray-50 border-gray-200 rounded-xl text-[14px] font-medium"
                        contentClassName="rounded-xl"
                      />
                    </div>
                  </div>
                  <div>
                    <BrandSelect
                      value={editedDeal?.brand ?? ""}
                      onValueChange={(val) => handleUpdate({ brand: val })}
                      label="Brand"
                      placeholder="e.g. AcmeCorp"
                      skip={!isOpen}
                    />
                  </div>
                  <div>
                    <FieldLabel>Service</FieldLabel>
                    <div className="flex items-center gap-2">
                      <ReactSelect
                        value={editedDeal.serviceId || ""}
                        onValueChange={(val) =>
                          handleUpdate({ serviceId: val })
                        }
                        options={serviceOptions}
                        placeholder="Select"
                        triggerClassName="h-10 min-h-10 flex-1 min-w-0 bg-gray-50 border-gray-200 rounded-xl text-[14px] font-medium"
                        contentClassName="rounded-xl"
                      />
                    </div>
                  </div>

                  <div>
                    <FieldLabel>Tags</FieldLabel>
                    <TagsInput
                      value={editedDeal.tags ?? []}
                      onChange={(tags) => handleUpdate({ tags })}
                      placeholder="Type a tag and press Enter"
                    />
                  </div>
                </div>
              </section>

              <section>
                <SectionHeading icon={<Mail size={14} />}>
                  Lead Details
                </SectionHeading>
                <div className="mt-4">
                  <Textarea
                    dir="ltr"
                    lang="en"
                    className="min-h-[100px] text-[13px] text-left bg-gray-50 border-gray-200 rounded-xl"
                    placeholder="Additional lead information..."
                    value={editedDeal.leadDetails || ""}
                    onChange={(e) =>
                      handleUpdate({ leadDetails: e.target.value })
                    }
                  />
                </div>
              </section>
            </div>
          </div>
        </div>

        {/* FOOTER */}
        <div className="bg-white/60 backdrop-blur-[15px] border-t border-white px-7 py-4 flex items-center justify-end gap-3">
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            className="text-gray-500 rounded-xl"
          >
            Cancel
          </Button>
          <Button
            size="sm"
            onClick={handleSaveLocal}
            loading={isSaving}
            className="h-10 px-6 rounded-xl text-[13px] font-bold bg-[#6C63FF] hover:bg-[#5a52e0] text-white shadow-lg shadow-[#6C63FF]/30 min-w-[140px]"
          >
            Update Deal
          </Button>
        </div>
      </DialogContent>

      {/* Delete Note Confirmation Dialog */}
      <DeleteDialog
        open={!!deleteNoteId}
        onOpenChange={(open) => !open && setDeleteNoteId(null)}
        onConfirm={async () => {
          if (deleteNoteId) await handleDeleteNote(deleteNoteId);
        }}
        title="Delete Note?"
        description="Are you sure you want to delete this note? This action cannot be undone."
        confirmText="Delete Note"
        isLoading={isDeletingNote}
      />
    </Dialog>
  );
}

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-extrabold text-gray-400 uppercase tracking-widest">
        {children}
      </h3>
      <div className="flex-1 h-px bg-gray-100 ml-1" />
    </div>
  );
}
