"use client";

import * as React from "react";
import { useForm, Controller, type Resolver } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import useFormPersist from "react-hook-form-persist";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ReactSelect } from "@/components/ui/react-select";
import { DatePicker } from "@/components/ui/date-picker";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Deal, Stage, type AddDealModalProps } from "./types";
import {
  Building2,
  Phone,
  MapPin,
  Mail,
  Check,
  Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";

import { useAppSelector } from "@/store/hooks";
import { selectSelectedTeam } from "@/store/slices/team-filter-slice";
import { isTeamSlugFilter } from "@/lib/team-filter";
import { useSession } from "next-auth/react";
import { BrandSelect } from "@/components/shared/brand-select";
import {
  useGetTeamsQuery,
  useGetAllUsersQuery,
  useGetLeadChannelsQuery,
  useGetPipelinesQuery,
  useGetCustomersQuery,
  useGetRolesQuery,
} from "@/api/rtk";
import { AddDealImportTab } from "./add-deal-import-tab";
import { TimelineIntentField } from "./timeline-intent-field";
import { TeamSelectField } from "./team-select-field";
import { LeadOwnerSelectField } from "./lead-owner-select-field";
import { ServiceSelectField } from "./service-select-field";
import { toast } from "sonner";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Can } from "@/components/providers/ability-provider";
import { LeadStatusSelect } from "@/components/shared/lead-status-select";
import { TagsInput } from "./tags-input";
import {
  ContributorUserPicker,
  pickRoleIdFromOrgRoles,
} from "./contributor-user-picker";


import { formSchema, type AddDealFormValues } from "./add-deal-form-schema";

import { FieldLabel, SectionHeading, defaultStageId, GridIcon } from "./deal-form-helpers";

export function AddDealModal({
  isOpen,
  onClose,
  onCreate,
  stages,
  teams,
  pipelineId,
  initialStageId,
  onImportSuccess,
}: AddDealModalProps) {
  // Get current selected team from Redux
  const selectedTeamFilter = useAppSelector(selectSelectedTeam);
  const defaultTeamFromFilter = isTeamSlugFilter(selectedTeamFilter)
    ? selectedTeamFilter
    : "all";
  const EMPTY_ARRAY = React.useMemo(() => [] as const, []);
  const { data: pipelinesData } = useGetPipelinesQuery(undefined, {
    skip: !isOpen,
  });
  const pipelines = pipelinesData ?? EMPTY_ARRAY;

  const { data: allUsersData } = useGetAllUsersQuery(undefined, {
    skip: !isOpen,
  });
  const allUsers = allUsersData ?? EMPTY_ARRAY;

  const { data: orgRoles = [] } = useGetRolesQuery(undefined, {
    skip: !isOpen,
  });

  const { data: fullTeamsData } = useGetTeamsQuery(undefined, {
    skip: !isOpen,
  });
  const fullTeams = fullTeamsData ?? EMPTY_ARRAY;

  const stagesFromPipelineInitial = React.useMemo(() => {
    if (!pipelineId) return EMPTY_ARRAY;
    return pipelines.find((p) => p.id === pipelineId)?.stages ?? EMPTY_ARRAY;
  }, [pipelines, pipelineId, EMPTY_ARRAY]);

  const stagesForDropdownInitial = (
    stagesFromPipelineInitial.length > 0 ? stagesFromPipelineInitial : stages
  ) as Stage[];
  const { data: leadChannelsData } = useGetLeadChannelsQuery(undefined, {
    skip: !isOpen,
  });
  const leadChannels = leadChannelsData ?? EMPTY_ARRAY;
  const leadChannelOptions = React.useMemo(
    () => leadChannels.map((c) => ({ value: c.id, label: c.name })),
    [leadChannels],
  );
  const { data: customers = [] } = useGetCustomersQuery(undefined, {
    skip: !isOpen,
  });
  // Get logged-in user from session
  const { data: session } = useSession();
  const userName =
    (session?.user as { name?: string })?.name ||
    (session as { backendUser?: { name?: string } })?.backendUser?.name ||
    "Unknown";

  const [importUiLocked, setImportUiLocked] = React.useState(false);



  // 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();
    }
  };



  const {
    register,
    handleSubmit,
    control,
    reset,
    setValue,
    getValues,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<AddDealFormValues>({
    resolver: yupResolver(formSchema) as Resolver<AddDealFormValues>,
    defaultValues: {
      customerName: "",
      companyName: "",
      phone: "",
      homePhone: "",
      address: "",
      email: "",
      postalCode: "",
      team: defaultTeamFromFilter,
      leadStatus: "",
      brand: "",
      leadChannelId: "",
      purchaseCount: "",
      month: "",
      year: "",
      tags: [],
      leadDetails: "",
      igCs: "",
      selectedPipelineId: "",
      budget: "",
      expectedPaymentDate: "",
      timelineIntentId: "",
      serviceId: "",
      stage: defaultStageId(stagesForDropdownInitial) || "",
      ownerId: "",
      customerId: "",
      aeIds: [],
      bdrIds: [],
      contributorIds: [],
    },
  });

  useFormPersist("add-deal-lead-data", {
    watch,
    setValue,
    storage: typeof window !== "undefined" ? window.localStorage : undefined,
  });

  const watchedPipelineId = watch("selectedPipelineId");
  const watchedTeam = watch("team");
  const effectivePipelineId = watchedPipelineId || pipelineId || null;
  const stagesFromPipeline = React.useMemo(() => {
    if (!effectivePipelineId) return EMPTY_ARRAY;
    return (
      pipelines.find((p) => p.id === effectivePipelineId)?.stages ?? EMPTY_ARRAY
    );
  }, [pipelines, effectivePipelineId, EMPTY_ARRAY]);
  const stagesForDropdown = (
    stagesFromPipeline.length > 0 ? stagesFromPipeline : stages || EMPTY_ARRAY
  ) as Stage[];

  const teamMembers = React.useMemo(() => {
    const usersArray = Array.isArray(allUsers) ? allUsers : [];
    if (!watchedTeam || watchedTeam === "all") return usersArray;

    const teamsArray = Array.isArray(fullTeams) ? fullTeams : [];
    const matched = teamsArray.find(
      (t) => t.name.toLowerCase().replace(/\s+/g, "-") === watchedTeam,
    );
    if (!matched || !Array.isArray(matched.members) || !matched.members.length)
      return usersArray;
    return usersArray.filter((u) => matched.members.includes(u.id));
  }, [watchedTeam, fullTeams, allUsers]);

  const watchedOwnerId = watch("ownerId");
  const leadOwnerSelectUsers = React.useMemo(() => {
    if (!watchedOwnerId?.trim()) return teamMembers;
    if (teamMembers.some((u) => u.id === watchedOwnerId)) return teamMembers;
    const usersArray = Array.isArray(allUsers) ? allUsers : [];
    const extra = usersArray.find((u) => u.id === watchedOwnerId);
    return extra ? [...teamMembers, extra] : teamMembers;
  }, [teamMembers, watchedOwnerId, 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(() => {
    if (!watchedTeam || watchedTeam === "all") return undefined;
    return teamMembers.map((u) => u.id);
  }, [watchedTeam, teamMembers]);

  const contributorLabelById = React.useMemo(() => {
    const m: Record<string, string> = {};
    for (const u of Array.isArray(allUsers) ? allUsers : []) {
      m[u.id] = u.name || u.email || u.id;
    }
    return m;
  }, [allUsers]);

  // Update team field when modal opens with current Redux team
  React.useEffect(() => {
    if (isOpen) {
      setValue("team", defaultTeamFromFilter);
    }
  }, [isOpen, defaultTeamFromFilter, setValue]);

  const prevTeamForOwnerRef = React.useRef<string | null>(null);
  // Reset lead owner only when the user changes team (not on modal open / initial mount)
  React.useEffect(() => {
    if (!isOpen) {
      prevTeamForOwnerRef.current = null;
      return;
    }
    const prev = prevTeamForOwnerRef.current;
    prevTeamForOwnerRef.current = watchedTeam;
    if (prev !== null && prev !== watchedTeam) {
      setValue("ownerId", "");
    }
  }, [isOpen, watchedTeam, setValue]);

  React.useEffect(() => {
    if (isOpen && initialStageId) {
      setValue("stage", initialStageId);
    } else if (isOpen && !initialStageId && stagesForDropdown.length > 0) {
      setValue("stage", defaultStageId(stagesForDropdown));
    }
  }, [isOpen, initialStageId, stagesForDropdown, setValue]);

  // When modal opens, set selected pipeline from prop so Stage is initialized correctly
  React.useEffect(() => {
    if (isOpen && pipelineId) {
      setValue("selectedPipelineId", pipelineId);
    }
  }, [isOpen, pipelineId, pipelines, setValue]);

  // Note: Automatic reset on close has been removed to allow form persistence.
  // reset() is now only called after successful submission on on success.




  const onSubmit = async (formData: AddDealFormValues) => {
    const effectivePipelineId = formData.selectedPipelineId || pipelineId;
    if (effectivePipelineId) {
      const dealPayload: Partial<Deal> = {
        customerName: formData.customerName,
        companyName: formData.companyName?.trim() || undefined,
        phone: formData.phone || undefined,
        homePhone: formData.homePhone?.trim() || undefined,
        address: formData.address || undefined,
        email: formData.email || undefined,
        postalCode: formData.postalCode || undefined,
        team: formData.team === "all" ? undefined : formData.team,
        leadStatus: formData.leadStatus || undefined,
        brand: formData.brand || undefined,
        leadChannelId: formData.leadChannelId || undefined,
        purchaseCount: 0,
        budget: 0,
        expectedPaymentDate: undefined,
        serviceId: formData.serviceId || undefined,
        stage: formData.stage,
        ownerId: formData.ownerId?.trim() || undefined,
        pipelineId: effectivePipelineId,
        leadDetails: formData.leadDetails ?? "",
        customerId: formData.customerId || undefined,
        aeIds: formData.aeIds || [],
        bdrIds: formData.bdrIds || [],
        contributorIds: formData.contributorIds || [],
        createdDate: (() => {
          const d = new Date();
          return `${String(d.getMonth() + 1).padStart(2, "0")}/${String(d.getDate()).padStart(2, "0")}/${d.getFullYear()}`;
        })(),
      };
      try {
        await onCreate(dealPayload);
        if (typeof window !== "undefined") {
          window.localStorage.removeItem("add-deal-lead-data");
        }
        onClose();
        reset();
      } catch (err) {
        // Keep data on failure
        console.error("Failed to create deal:", err);
      }
    }
  };

  const handleDialogOpenChange = React.useCallback(
    (open: boolean) => {
      if (open) return;
      if (importUiLocked) return;
      onClose();
    },
    [importUiLocked, onClose],
  );

  return (
    <Dialog open={isOpen} onOpenChange={handleDialogOpenChange}>
      <DialogContent
        className="sm:max-w-[1120px] w-full h-full sm:h-[95vh] sm:max-h-[95vh] p-0 overflow-hidden bg-white rounded-none sm:rounded-3xl shadow-2xl flex flex-col border-none"
        showCloseButton={!importUiLocked}
        onPointerDownOutside={(e) => {
          if (importUiLocked) e.preventDefault();
        }}
        onInteractOutside={(e) => {
          if (importUiLocked) e.preventDefault();
        }}
        onEscapeKeyDown={(e) => {
          if (importUiLocked) e.preventDefault();
        }}
      >
        {/* 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-5 md:px-7 py-4 md:py-5 flex items-start justify-between gap-4">
            <div className="flex items-center gap-3 md:gap-4 min-w-0">
              <div className="h-10 w-10 md:h-12 md: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={20} className="text-white/90 md:size-[22px]" />
              </div>
              <div className="min-w-0">
                <DialogTitle className="text-[18px] md:text-[20px] font-extrabold text-white font-['Lexend'] leading-tight truncate">
                  Create New Lead
                </DialogTitle>
                <div className="text-[12px] md:text-[13px] text-white/75 font-medium mt-0.5 md:mt-1">
                  Add a new lead to your pipeline
                </div>
              </div>
            </div>
          </div>
        </div>

        <Tabs
          defaultValue="new"
          className="flex flex-col flex-1 min-h-0 overflow-hidden"
        >
          <div className="px-5 md:px-7 pt-4 pb-2 shrink-0 border-b border-gray-100">
            <TabsList className="bg-gray-100/80 p-1 rounded-xl w-full flex overflow-x-auto scrollbar-none">
              <TabsTrigger
                value="new"
                className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm"
              >
                New Lead
              </TabsTrigger>
              <Can action="create" subject="excel_import">
                <TabsTrigger
                  value="import"
                  className="rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm"
                >
                  Import
                </TabsTrigger>
              </Can>
            </TabsList>
          </div>
          <TabsContent
            value="new"
            className="flex-1 min-h-0 overflow-y-auto scrollbar-themed mt-0 bg-white"
          >
            <form
              onSubmit={handleSubmit(onSubmit)}
              className="h-full flex flex-col"
            >
              <div className="px-5 md:px-7 py-6 space-y-7 flex-1">
                <section>
                  <SectionHeading icon={<Building2 size={14} />}>
                    Customer Information
                  </SectionHeading>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
                    <div>
                      <FieldLabel>
                        Customer Name <span className="text-red-500">*</span>
                      </FieldLabel>
                      <Input
                        {...register("customerName")}
                        className={cn(
                          "h-10 text-[14px] font-semibold bg-gray-50 border-gray-200 rounded-xl",
                          errors.customerName && "border-red-500",
                        )}
                        placeholder="Enter customer name..."
                      />
                      {errors.customerName && (
                        <p className="text-red-500 text-[10px] mt-1 ml-1">
                          {errors.customerName.message}
                        </p>
                      )}
                    </div>
                    <div>
                      <FieldLabel>Company Name</FieldLabel>
                      <Input
                        {...register("companyName")}
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        placeholder="Organization (optional)"
                      />
                    </div>
                    <div>
                      <FieldLabel>
                        Email <span className="text-red-500">*</span>
                      </FieldLabel>
                      <Input
                        {...register("email")}
                        type="email"
                        className={cn(
                          "h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl",
                          errors.email && "border-red-500",
                        )}
                        placeholder="e.g. jane@example.com"
                      />
                      {errors.email && (
                        <p className="text-red-500 text-[10px] mt-1 ml-1">
                          {errors.email.message}
                        </p>
                      )}
                    </div>
                    <div>
                      <FieldLabel>
                        Phone <span className="text-red-500">*</span>
                      </FieldLabel>
                      <Input
                        {...register("phone")}
                        onKeyDown={handlePhoneKeyDown}
                        className={cn(
                          "h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl",
                          errors.phone && "border-red-500",
                        )}
                        placeholder="e.g. +1 555-1234"
                      />
                      {errors.phone && (
                        <p className="text-red-500 text-[10px] mt-1 ml-1">
                          {errors.phone.message}
                        </p>
                      )}
                    </div>
                    <div>
                      <FieldLabel>Home Phone</FieldLabel>
                      <Input
                        {...register("homePhone")}
                        onKeyDown={handlePhoneKeyDown}
                        className={cn(
                          "h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl",
                          errors.homePhone && "border-red-500",
                        )}
                        placeholder="Optional — e.g. +1 555-9876"
                      />
                      {errors.homePhone && (
                        <p className="text-red-500 text-[10px] mt-1 ml-1">
                          {errors.homePhone.message}
                        </p>
                      )}
                    </div>
                    <div>
                      <FieldLabel>
                        Address <span className="text-red-500">*</span>
                      </FieldLabel>
                      <Input
                        {...register("address")}
                        className={cn(
                          "h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl",
                          errors.address && "border-red-500",
                        )}
                        placeholder="e.g. 123 Main St"
                      />
                      {errors.address && (
                        <p className="text-red-500 text-[10px] mt-1 ml-1">
                          {errors.address.message}
                        </p>
                      )}
                    </div>
                    <div>
                      <FieldLabel>Postal Code</FieldLabel>
                      <Input
                        {...register("postalCode")}
                        className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
                        placeholder="e.g. 10001"
                      />
                    </div>
                    <TimelineIntentField
                      control={control}
                      watch={watch}
                      setValue={setValue}
                      isOpen={isOpen}
                    />
                  </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">
                    <TeamSelectField control={control} teams={teams} />
                    <LeadOwnerSelectField control={control} leadOwnerSelectUsers={leadOwnerSelectUsers} />
                    <div>
                      <FieldLabel>Assign AE</FieldLabel>
                      <Controller
                        name="aeIds"
                        control={control}
                        render={({ field }) => (
                          <ContributorUserPicker
                            value={field.value || []}
                            onChange={field.onChange}
                            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>
                      <Controller
                        name="bdrIds"
                        control={control}
                        render={({ field }) => (
                          <ContributorUserPicker
                            value={field.value || []}
                            onChange={field.onChange}
                            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>
                      <Controller
                        name="contributorIds"
                        control={control}
                        render={({ field }) => (
                          <ContributorUserPicker
                            value={field.value || []}
                            onChange={field.onChange}
                            labelById={contributorLabelById}
                            placeholder="Select contributors"
                            className="border-gray-200 bg-gray-50"
                          />
                        )}
                      />
                    </div>
                    <div>
                      <Controller
                        name="leadStatus"
                        control={control}
                        render={({ field }) => (
                          <LeadStatusSelect
                            value={field.value ?? ""}
                            onValueChange={field.onChange}
                            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">
                        <Controller
                          name="leadChannelId"
                          control={control}
                          render={({ field }) => (
                            <ReactSelect
                              value={field.value || ""}
                              onValueChange={field.onChange}
                              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>
                      <Controller
                        name="brand"
                        control={control}
                        render={({ field }) => (
                          <BrandSelect
                            value={field.value ?? ""}
                            onValueChange={field.onChange}
                            label="Brand"
                            placeholder="e.g. AcmeCorp"
                            skip={!isOpen}
                          />
                        )}
                      />
                    </div>
                    <ServiceSelectField
                      control={control}
                      setValue={setValue}
                      getValues={getValues}
                      isOpen={isOpen}
                    />

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

                <section>
                  <SectionHeading icon={<Mail size={14} />}>
                    Lead Details
                  </SectionHeading>
                  <div className="mt-4">
                    <Controller
                      name="leadDetails"
                      control={control}
                      render={({ field }) => (
                        <Textarea
                          {...field}
                          value={field.value ?? ""}
                          dir="ltr"
                          lang="en"
                          placeholder="Additional lead information..."
                          className="min-h-[120px] text-[13px] text-left bg-gray-50 border border-gray-200 rounded-xl focus-within:border-[#6C63FF] focus-within:ring-2 focus-within:ring-[#6C63FF]/20 outline-none whitespace-pre-wrap break-words leading-6"
                        />
                      )}
                    />
                  </div>
                </section>

                <div className="flex flex-col-reverse sm:flex-row items-center justify-end gap-3 pt-6 border-t border-gray-100 mt-6 md:mt-10 pb-4">
                  <Button
                    type="button"
                    variant="ghost"
                    onClick={onClose}
                    disabled={isSubmitting}
                    className="w-full sm:w-auto rounded-xl font-bold h-11 px-6 text-gray-500 hover:bg-gray-100"
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    loading={isSubmitting}
                    className="w-full sm:w-auto rounded-xl bg-[#6C63FF] hover:bg-[#5a52e0] px-8 font-extrabold text-white h-11 shadow-md shadow-[#6C63FF]/20 transition-all duration-200"
                  >
                    Create Lead
                  </Button>
                </div>
              </div>
            </form>
          </TabsContent>
          <TabsContent
            value="import"
            className="flex-1 min-h-0 overflow-hidden mt-0 flex flex-col bg-white"
          >
            <Can action="create" subject="excel_import">
              <AddDealImportTab
                hideTargetSelection
                defaultTargetType="LEAD"
                pipelineId={watchedPipelineId || pipelineId}
                onClose={onClose}
                onSuccess={onImportSuccess}
                onUiLockedChange={setImportUiLocked}
                sessionKey="lead-import-dialog"
              />
            </Can>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
