"use client";

import type React from "react";

import { useCallback, useEffect, useMemo, useState, useRef } from "react";
import { useFieldArray, useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  ChevronLeft,
  Eye,
  MessageSquareText,
  Upload,
  Cloud,
} from "lucide-react";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import { Input } from "@/shared/common/ui/input";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Button } from "@/shared/common/ui/button";
import { Switch } from "@/shared/common/ui/switch";
import { Sheet, SheetContent, SheetTitle } from "@/shared/common/ui/sheet";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Badge } from "@/shared/common/ui/badge";

import {
  type CreateOrEditLetter,
  createLetterSchema,
  defaultCreateLetterValues,
  normalizePreferredLanguage,
} from "./formSchema";
import {
  useCanJumpOnStepUp,
  useInitiationTypeOptions,
} from "@/record-management/components/hooks/useUserRecords";
import useSettings from "@/record-management/components/hooks/useSettings";
import useTemplate, {
  type LetterTemplateDto,
} from "@/record-management/components/hooks/useTemplate";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { usePrefixSuffix } from "@/shared/hooks/usePrefixSuffix";
import { useHeaderFooterPresigned } from "../../hooks/useHeaderFooterPresigned";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useRecordPreview } from "../../hooks/useRecordPreview";

import {
  CustomSelect,
  FormAddableList,
  FormMultiSelectField,
  FormSelectField,
  FormTreeSelectField,
} from "@/shared/common/form/fields/FormFields";
import FullPageSpinner from "./fullPageSpinner";
import RichTextEditor from "@/record-management/common/RichTextEditor";
import { ReusableFileUploader } from "@/shared/common/ui/fileUploader/reusableFileUploader";
import RecordPreviewPage from "@/record-management/pages/RecordPreviewPage";
import { DmsFilePickerModal } from "./DmsFilePickerModal";
import { DmsAttachmentItem } from "./DmsAttachmentItem";
import CollaborationCommentsDialog from "@/record-management/components/collaborations/CollaborationCommentsDialog";

import type { KeyValue } from "@/record-management/types/recordSelectTypes";
import type { EmployeeWithUnitDto } from "@/user-management/dto/employees/employees";
import type { OrganizationsPositions } from "@/record-management/services/api/departmentService";
import type { TreeViewItem } from "@/shared/common/ui/treeSelect";
import { getLeafCheckedItems, updateCheckState } from "./treeUtils";
import { SingleSelect } from "@/shared/common/ui/single-select";
import { usePermissions } from "@/shared/context/PermissionContext";
import { useUserDetail } from "../../hooks/useUserDetail";
import { MeDto } from "@/shared/dto/user/meDto";
import { useTenantConfig } from "@/layout/components/TenantConfig";
import { config } from "zod/v4/core";
export type RecordFormIntent = "draft" | "forward" | "approve" | "direct";

const DISABLED_DIRECT_HEADER_FOOTER_VALUE = "__disabled__";
const EXTERNAL_LIKE_RECORD_TYPE_KEYS = ["external", "bank"];

const normalizeRecordTypeKey = (recordType?: string) =>
  String(recordType || "").toLowerCase();

const isExternalLikeRecordType = (recordType?: string) =>
  EXTERNAL_LIKE_RECORD_TYPE_KEYS.includes(normalizeRecordTypeKey(recordType));

type RecordFormProps = {
  onSubmit: (
    values: CreateOrEditLetter,
    intent?: RecordFormIntent,
  ) => void | Promise<void>;
  files: File[];
  treeOrganizationsOptions: TreeViewItem[];
  ccTreeOrganizationsOptions: TreeViewItem[];
  fyrTreeOrganizationsOptions: TreeViewItem[];
  defaultValues?: CreateOrEditLetter | null;
  fullApiResponse?: any;
  recordId?: string;
  isEditMode?: boolean;
  isLoading?: boolean;
  isLoadingRecord?: boolean;
  setFiles?: (files: File[]) => void;
  existingAttachmentComponent?: React.ReactNode;
  dmsAttachments?: any[];
  setDmsAttachments?: React.Dispatch<React.SetStateAction<any[]>>;
};

type PrefixSuffixOption = { id: string; name: { en: string; am: string } };
type LocalizedName = { am: string; en: string };

type ReceiverItem = {
  unitId?: string;
  name?: string | LocalizedName;
  type: "unit" | "non_smart";
};

type ReceiverGroup = {
  prefix?: string;
  suffix?: string;
  receivers: ReceiverItem[];
};

const createEmptyReceiverGroup = (): ReceiverGroup => ({
  prefix: "",
  suffix: "",
  receivers: [],
});

const deepCloneTreeItems = (items: TreeViewItem[]): TreeViewItem[] =>
  items.map((item) => ({
    ...item,
    checked: item.checked ?? false,
    children: item.children ? deepCloneTreeItems(item.children) : [],
  }));

const syncCheckedState = (
  items: TreeViewItem[],
  selectedIds: Set<string>,
): TreeViewItem[] =>
  items.map((item) => {
    const children = item.children
      ? syncCheckedState(item.children, selectedIds)
      : [];

    if (children.length === 0) {
      return {
        ...item,
        checked: selectedIds.has(item.id),
        children,
      };
    }

    const allChildrenChecked = children.every(
      (child) => child.checked === true,
    );
    const someChildrenChecked = children.some(
      (child) => child.checked === true || child.checked === "indeterminate",
    );

    return {
      ...item,
      checked: allChildrenChecked
        ? true
        : someChildrenChecked
          ? "indeterminate"
          : false,
      children,
    };
  });

const isUnitReceiver = (receiver: unknown): receiver is ReceiverItem =>
  Boolean(
    receiver &&
    typeof receiver === "object" &&
    (receiver as ReceiverItem).type === "unit" &&
    (receiver as ReceiverItem).unitId,
  );

const isNonSmartReceiver = (receiver: unknown): receiver is ReceiverItem =>
  Boolean(
    receiver &&
    typeof receiver === "object" &&
    (receiver as ReceiverItem).type === "non_smart" &&
    getReceiverNameText((receiver as ReceiverItem).name).trim(),
  );

const getReceiverNameText = (name?: string | LocalizedName): string => {
  if (!name) return "";
  if (typeof name === "string") return name;
  return name.en || name.am || "";
};

const dedupeUnitReceivers = (receivers: ReceiverItem[]): ReceiverItem[] => {
  const map = new Map<string, ReceiverItem>();
  receivers.filter(isUnitReceiver).forEach((receiver) => {
    if (!map.has(receiver.unitId!)) {
      map.set(receiver.unitId!, {
        unitId: receiver.unitId,
        name: receiver.name,
        type: "unit",
      });
    }
  });
  return Array.from(map.values());
};

const dedupeNonSmartReceivers = (receivers: ReceiverItem[]): ReceiverItem[] => {
  const normalized = Array.from(
    new Set(
      receivers
        .filter(isNonSmartReceiver)
        .map((receiver) => getReceiverNameText(receiver.name).trim())
        .filter(Boolean),
    ),
  );
  return normalized.map((name) => ({
    name,
    type: "non_smart",
  }));
};

const normalizeReceiverGroups = (
  groups?: ReceiverGroup[] | null,
): ReceiverGroup[] => {
  const normalized =
    groups?.map((group) => ({
      prefix: group?.prefix ?? "",
      suffix: group?.suffix ?? "",
      receivers: [
        ...dedupeUnitReceivers(
          Array.isArray(group?.receivers) ? group.receivers : [],
        ),
        ...dedupeNonSmartReceivers(
          Array.isArray(group?.receivers) ? group.receivers : [],
        ),
      ],
    })) ?? [];

  if (normalized.length === 0) {
    return [createEmptyReceiverGroup()];
  }

  return normalized;
};

const hasReceiverGroupContent = (group: ReceiverGroup) =>
  Boolean(group.prefix?.trim()) ||
  Boolean(group.suffix?.trim()) ||
  group.receivers.length > 0;

const stripEmptyReceiverGroups = (groups?: ReceiverGroup[] | null) =>
  (groups ?? []).filter(hasReceiverGroupContent);

const findTreeItemById = (
  items: TreeViewItem[],
  id: string,
): TreeViewItem | undefined => {
  for (const item of items) {
    if (item.id === id) {
      return item;
    }
    if (item.children?.length) {
      const found = findTreeItemById(item.children, id);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
};

const receiverToTreeViewItem = (
  receiver: ReceiverItem,
  options: TreeViewItem[],
): TreeViewItem | null => {
  if (!isUnitReceiver(receiver)) {
    return null;
  }

  const matched = findTreeItemById(options, receiver.unitId!);
  if (matched) {
    return {
      id: matched.id,
      name: matched.name,
      hierarchyType: matched.hierarchyType,
      checked: true,
    };
  }

  const fallbackName =
    getReceiverNameText(receiver.name) || receiver.unitId || "";
  return {
    id: receiver.unitId!,
    name: {
      en: fallbackName,
      am: fallbackName,
    },
    hierarchyType: "unit",
    checked: true,
  };
};

const buildReceiverGroupsFromLegacy = ({
  groupedTreeItems,
  groupedItems,
  prefix,
  suffix,
  fallbackUnits,
  fallbackNames,
}: {
  groupedTreeItems?: {
    prefix?: string;
    suffix?: string;
    values?: TreeViewItem[];
  }[];
  groupedItems?: { prefix?: string; suffix?: string; values?: string[] }[];
  prefix?: string;
  suffix?: string;
  fallbackUnits?: TreeViewItem[];
  fallbackNames?: string[];
}): ReceiverGroup[] => {
  const maxLength = Math.max(
    groupedTreeItems?.length ?? 0,
    groupedItems?.length ?? 0,
  );
  const groups: ReceiverGroup[] = [];

  for (let index = 0; index < maxLength; index += 1) {
    const treeGroup = groupedTreeItems?.[index];
    const listGroup = groupedItems?.[index];
    const unitReceivers =
      treeGroup?.values?.map((unit) => ({
        unitId: unit.id,
        name: {
          en: unit.name?.en || unit.name?.am || unit.id,
          am: unit.name?.am || unit.name?.en || unit.id,
        },
        type: "unit" as const,
      })) ?? [];
    const nonSmartReceivers =
      listGroup?.values?.map((name) => ({
        name,
        type: "non_smart" as const,
      })) ?? [];

    groups.push({
      prefix: treeGroup?.prefix ?? listGroup?.prefix ?? prefix ?? "",
      suffix: treeGroup?.suffix ?? listGroup?.suffix ?? suffix ?? "",
      receivers: [...unitReceivers, ...nonSmartReceivers],
    });
  }

  if (groups.length > 0) {
    return normalizeReceiverGroups(groups);
  }

  const fallbackReceivers: ReceiverItem[] = [
    ...((fallbackUnits ?? []).map((unit) => ({
      unitId: unit.id,
      name: {
        en: unit.name?.en || unit.name?.am || unit.id,
        am: unit.name?.am || unit.name?.en || unit.id,
      },
      type: "unit" as const,
    })) || []),
    ...((fallbackNames ?? []).map((name) => ({
      name,
      type: "non_smart" as const,
    })) || []),
  ];

  return normalizeReceiverGroups([
    {
      prefix: prefix ?? "",
      suffix: suffix ?? "",
      receivers: fallbackReceivers,
    },
  ]);
};

const buildLegacyGroupedValues = (
  groups: ReceiverGroup[],
  options: TreeViewItem[],
) => {
  const groupedTreeItems = groups.map((group) => ({
    prefix: group.prefix ?? "",
    suffix: group.suffix ?? "",
    values: group.receivers
      .filter(isUnitReceiver)
      .map((receiver) => receiverToTreeViewItem(receiver, options))
      .filter((item): item is TreeViewItem => Boolean(item)),
  }));

  const groupedItems = groups.map((group) => ({
    prefix: group.prefix ?? "",
    suffix: group.suffix ?? "",
    values: group.receivers
      .filter(isNonSmartReceiver)
      .map((receiver) => getReceiverNameText(receiver.name).trim()),
  }));

  return {
    groupedTreeItems,
    groupedItems,
    units: groupedTreeItems.flatMap((group) => group.values),
    names: groupedItems.flatMap((group) => group.values),
  };
};

const resolveLocalizedPrefixSuffixValue = (
  value: string | undefined,
  options: PrefixSuffixOption[],
  language: "am" | "en",
): string => {
  if (!value) return "";

  const matched = options.find((option) => {
    const english = option.name?.en ?? "";
    const amharic = option.name?.am ?? "";
    return value === option.id || value === english || value === amharic;
  });

  if (!matched) {
    return value;
  }

  return matched.name?.[language] || matched.name?.en || matched.name?.am || "";
};

const localizeReceiverGroups = (
  groups: ReceiverGroup[],
  {
    prefixOptions,
    suffixOptions,
    language,
  }: {
    prefixOptions: PrefixSuffixOption[];
    suffixOptions: PrefixSuffixOption[];
    language: "am" | "en";
  },
): ReceiverGroup[] =>
  groups.map((group) => ({
    ...group,
    prefix: resolveLocalizedPrefixSuffixValue(
      group.prefix,
      prefixOptions,
      language,
    ),
    suffix: resolveLocalizedPrefixSuffixValue(
      group.suffix,
      suffixOptions,
      language,
    ),
  }));

type GroupedExternalReceiverBlockProps = {
  form: any;
  title: string;
  fieldArrayName: "ReceiversList" | "ccList" | "forYourReferenceList";
  prefixOptions: PrefixSuffixOption[];
  suffixOptions: PrefixSuffixOption[];
  treeLabel: string;
  addableLabel: string;
  addablePlaceholder: string;
  initialOptions: TreeViewItem[];
  excludedIds: { id: string }[];
  localizedName: (
    name?:
      | {
          am: string;
          en: string;
        }
      | undefined,
  ) => string;
  prefixLabel: string;
  suffixLabel: string;
  prefixPlaceholder: string;
  suffixPlaceholder: string;
  addLabel: string;
  removeLabel: string;
};

const GroupedExternalReceiverBlock = ({
  form,
  title,
  fieldArrayName,
  prefixOptions,
  suffixOptions,
  treeLabel,
  addableLabel,
  addablePlaceholder,
  initialOptions,
  excludedIds,
  localizedName,
  prefixLabel,
  suffixLabel,
  prefixPlaceholder,
  suffixPlaceholder,
  addLabel,
  removeLabel,
}: GroupedExternalReceiverBlockProps) => {
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: fieldArrayName,
  });
  const watchedGroups = useWatch({
    control: form.control,
    name: fieldArrayName,
    defaultValue: [],
  });
  const [localOptionsMap, setLocalOptionsMap] = useState<
    Record<string, TreeViewItem[]>
  >({});

  // For each group index, the set of leaf unit IDs already picked in any
  // OTHER group within this same section. Used to hide already-selected
  // organizations from the "+ Add" flow so the user can't pick the same
  // org twice across groups.
  const otherGroupSelectedIdsByIndex = useMemo(() => {
    const perGroup: Set<string>[] = (watchedGroups ?? []).map((group: any) => {
      const ids = new Set<string>();
      (group?.receivers ?? []).forEach((r: ReceiverItem) => {
        if (r?.type === "unit" && r?.unitId) ids.add(r.unitId);
      });
      return ids;
    });
    return perGroup.map((_, i) => {
      const union = new Set<string>();
      perGroup.forEach((set, j) => {
        if (j !== i) set.forEach((id) => union.add(id));
      });
      return union;
    });
  }, [watchedGroups]);

  useEffect(() => {
    if (fields.length === 0) {
      append(createEmptyReceiverGroup());
    }
  }, [append, fields.length]);

  useEffect(() => {
    setLocalOptionsMap((prev) => {
      const next: Record<string, TreeViewItem[]> = { ...prev };
      let changed = false;

      fields.forEach((field) => {
        if (!next[field.id]) {
          next[field.id] = deepCloneTreeItems(initialOptions);
          changed = true;
        }
      });

      Object.keys(next).forEach((id) => {
        if (!fields.some((field) => field.id === id)) {
          delete next[id];
          changed = true;
        }
      });

      return changed ? next : prev;
    });
  }, [fields, initialOptions]);

  useEffect(() => {
    setLocalOptionsMap((prev) => {
      const next: Record<string, TreeViewItem[]> = { ...prev };
      let changed = false;

      fields.forEach((field, index) => {
        const selectedIds: Set<string> = new Set<string>(
          (watchedGroups[index]?.receivers || [])
            .filter(
              (receiver: ReceiverItem) =>
                receiver?.type === "unit" && Boolean(receiver.unitId),
            )
            .map((receiver: ReceiverItem) => receiver.unitId as string),
        );
        const baseOptions =
          prev[field.id] ?? deepCloneTreeItems(initialOptions);
        const syncedOptions = syncCheckedState(baseOptions, selectedIds);

        if (JSON.stringify(baseOptions) !== JSON.stringify(syncedOptions)) {
          next[field.id] = syncedOptions;
          changed = true;
        }
      });

      return changed ? next : prev;
    });
  }, [fields, watchedGroups, initialOptions]);

  const handleLocalCheckChange =
    (fieldId: string, index: number) =>
    (items: TreeViewItem | TreeViewItem[], checked: boolean) => {
      const currentOptions =
        localOptionsMap[fieldId] ?? deepCloneTreeItems(initialOptions);
      const itemsArray = Array.isArray(items) ? items : [items];
      const updatedOptions = updateCheckState(
        currentOptions,
        itemsArray,
        checked,
      );

      setLocalOptionsMap((prev) => ({
        ...prev,
        [fieldId]: updatedOptions,
      }));

      // Clicking a parent cascades the check across the FULL local tree —
      // including children that are visually filtered out by getFilteredOptions
      // because they're already selected in the other tree (receiver ↔ CC) or
      // in another group within this same section. Drop those filtered leaves
      // here so the cascade can never silently re-add a unit the user already
      // picked elsewhere.
      const excludedIdSet = new Set(excludedIds.map((e) => e.id));
      (otherGroupSelectedIdsByIndex[index] ?? new Set<string>()).forEach((id) =>
        excludedIdSet.add(id),
      );
      const newCheckedLeaves = getLeafCheckedItems(updatedOptions).filter(
        (leaf) => !excludedIdSet.has(leaf.id),
      );
      const newCheckedIds = new Set(newCheckedLeaves.map((leaf) => leaf.id));

      const currentReceivers: ReceiverItem[] =
        form.getValues(`${fieldArrayName}.${index}.receivers`) || [];
      const currentUnitReceivers = currentReceivers.filter(
        (r): r is ReceiverItem & { unitId: string } =>
          r?.type === "unit" && Boolean(r?.unitId),
      );
      const nonSmartReceivers = dedupeNonSmartReceivers(currentReceivers);

      // Preserve user-selection order: keep existing receivers in their
      // current order (dropping any that became unchecked) and append the
      // newly-checked leaves at the end. Rebuilding from
      // getLeafCheckedItems alone would resort everything by tree-traversal
      // order, which is what made multi-select external CC display in
      // directory order instead of the order the user picked.
      const keptUnitReceivers = currentUnitReceivers.filter((r) =>
        newCheckedIds.has(r.unitId),
      );
      const currentIds = new Set(currentUnitReceivers.map((r) => r.unitId));
      const newlyAddedReceivers: ReceiverItem[] = newCheckedLeaves
        .filter((leaf) => !currentIds.has(leaf.id))
        .map((leaf) => ({
          unitId: leaf.id,
          name:
            typeof leaf.name === "string"
              ? { en: leaf.name, am: leaf.name }
              : {
                  en: leaf.name?.en || leaf.name?.am || leaf.id,
                  am: leaf.name?.am || leaf.name?.en || leaf.id,
                },
          type: "unit",
        }));
      const orderedUnitReceivers: ReceiverItem[] = [
        ...keptUnitReceivers,
        ...newlyAddedReceivers,
      ];

      form.setValue(
        `${fieldArrayName}.${index}.receivers`,
        [...dedupeUnitReceivers(orderedUnitReceivers), ...nonSmartReceivers],
        { shouldDirty: true, shouldValidate: true },
      );
    };

  const handleRemoveSelectedUnit = (index: number, unitId: string) => {
    const fieldPath = `${fieldArrayName}.${index}.receivers`;
    const currentReceivers: ReceiverItem[] = form.getValues(fieldPath) || [];
    const updatedReceivers = currentReceivers.filter(
      (item) => !(item?.type === "unit" && item?.unitId === unitId),
    );

    form.setValue(fieldPath, updatedReceivers, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };

  const combineNames = (
    parent: TreeViewItem["name"],
    child: TreeViewItem["name"],
  ): { am: string; en: string } => {
    const toObj = (n: TreeViewItem["name"]) =>
      typeof n === "string"
        ? { en: n, am: n }
        : { en: n?.en ?? "", am: n?.am ?? "" };
    const p = toObj(parent);
    const c = toObj(child);
    const join = (a: string, b: string) => (a && b ? `${a} / ${b}` : a || b);
    return { en: join(p.en, c.en), am: join(p.am, c.am) };
  };

  const getFilteredOptions = (
    treeItems: TreeViewItem[],
    extraExcluded?: Set<string>,
  ): TreeViewItem[] =>
    treeItems.flatMap((node) => {
      if (
        excludedIds.some((receiving) => receiving.id === node.id) ||
        extraExcluded?.has(node.id)
      )
        return [];
      const hadChildren = !!node.children && node.children.length > 0;
      const filteredChildren = node.children
        ? getFilteredOptions(node.children, extraExcluded)
        : [];
      // If the node was a parent and every one of its children got filtered
      // out, drop the parent too — otherwise it would render as an empty
      // group that, when clicked, selects nothing useful.
      if (hadChildren && filteredChildren.length === 0) return [];
      // When exactly one leaf descendant remains after filtering, collapse
      // the visual hierarchy into a single "Parent / Child" entry so the
      // user doesn't have to expand a group that contains one option.
      // Keeping the child's id/checked state means clicking this entry
      // selects exactly that leaf — the cascade still does the right thing.
      if (
        filteredChildren.length === 1 &&
        (!filteredChildren[0].children ||
          filteredChildren[0].children.length === 0)
      ) {
        const child = filteredChildren[0];
        return [
          {
            ...child,
            name: combineNames(node.name, child.name),
          },
        ];
      }
      return [{ ...node, children: filteredChildren }];
    });

  return (
    <div className="space-y-6 w-full">
      {fields.map((field, index) => {
        const localOptions =
          localOptionsMap[field.id] ?? deepCloneTreeItems(initialOptions);
        const selectedUnitReceivers: ReceiverItem[] = dedupeUnitReceivers(
          (watchedGroups[index]?.receivers || []).filter(
            (item: ReceiverItem) => item?.type === "unit" && item?.unitId,
          ),
        );

        return (
          <div
            key={field.id}
            className="space-y-4 p-4 rounded-lg border border-gray-200 bg-white dark:bg-gray-900 w-full"
          >
            <div className="flex items-center justify-between gap-3">
              <div className="text-sm font-semibold text-slate-700 dark:text-slate-200">
                {`${title} #${index + 1}`}
              </div>
              {fields.length > 1 && (
                <Button
                  type="button"
                  variant="ghost"
                  className="h-9 px-3 text-red-600"
                  onClick={() => remove(index)}
                >
                  {removeLabel}
                </Button>
              )}
            </div>

            <CustomSelect
              form={form}
              name={`${fieldArrayName}.${index}.prefix`}
              label={prefixLabel}
              placeholder={prefixPlaceholder}
              options={prefixOptions || []}
              localizedName={localizedName}
            />

            {selectedUnitReceivers.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                {selectedUnitReceivers.map((unit, unitIndex) => (
                  <div
                    key={`${unit.unitId}-${unitIndex}`}
                    className="flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-md"
                  >
                    <span className="text-sm truncate max-w-[220px]">
                      {localizedName(
                        typeof unit.name === "string"
                          ? { en: unit.name, am: unit.name }
                          : unit.name,
                      ) || unit.unitId}
                    </span>
                    <button
                      type="button"
                      className="cursor-pointer text-blue-700 hover:text-red-600 ml-1"
                      onClick={() =>
                        unit.unitId &&
                        handleRemoveSelectedUnit(index, unit.unitId)
                      }
                    >
                      x
                    </button>
                  </div>
                ))}
              </div>
            )}

            <FormTreeSelectField
              control={form.control}
              name={`${fieldArrayName}.${index}.receivers`}
              label={treeLabel}
              options={getFilteredOptions(
                localOptions,
                otherGroupSelectedIdsByIndex[index],
              )}
              handleCheckChange={handleLocalCheckChange(field.id, index)}
              collapsible={true}
              localizedName={localizedName}
              selectedCountResolver={(value) =>
                Array.isArray(value)
                  ? value.filter(
                      (item) => item?.type === "unit" && item?.unitId,
                    ).length
                  : 0
              }
            />

            <FormAddableList
              form={form}
              name={`${fieldArrayName}.${index}.receivers`}
              label={addableLabel}
              placeholder={addablePlaceholder}
              valueAdapter={{
                getDisplayItems: (fieldValue) =>
                  Array.isArray(fieldValue)
                    ? fieldValue
                        .filter(
                          (item) => item?.type === "non_smart" && item?.name,
                        )
                        .map((item) => getReceiverNameText(item.name))
                    : [],
                onItemsChange: (items, fieldValue) => {
                  const source = Array.isArray(fieldValue) ? fieldValue : [];
                  const unitReceivers = dedupeUnitReceivers(source);
                  const nonSmartReceivers = dedupeNonSmartReceivers(
                    items.map((name) => ({
                      name,
                      type: "non_smart" as const,
                    })),
                  );
                  return [...unitReceivers, ...nonSmartReceivers];
                },
              }}
            />

            <CustomSelect
              form={form}
              name={`${fieldArrayName}.${index}.suffix`}
              label={suffixLabel}
              placeholder={suffixPlaceholder}
              options={suffixOptions || []}
              localizedName={localizedName}
            />
          </div>
        );
      })}

      <Button
        type="button"
        variant="outline"
        className="h-9 px-3"
        onClick={() => append(createEmptyReceiverGroup())}
      >
        + {addLabel}
      </Button>
    </div>
  );
};

const RecordForm = ({
  defaultValues,
  fullApiResponse,
  recordId,
  treeOrganizationsOptions,
  ccTreeOrganizationsOptions,
  fyrTreeOrganizationsOptions,
  isEditMode,
  onSubmit,
  files,
  setFiles,
  existingAttachmentComponent,
  isLoading,
  isLoadingRecord,
  dmsAttachments = [],
  setDmsAttachments,
}: RecordFormProps) => {
  const [isDmsPickerOpen, setIsDmsPickerOpen] = useState(false);
  const localFileInputRef = useRef<HTMLInputElement>(null);
  const { config: tenantConfig } = useTenantConfig();
  const handleLocalUploadClick = () => {
    localFileInputRef.current?.click();
  };

  const handleLocalFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && setFiles) {
      const selected = Array.from(e.target.files);
      setFiles([...files, ...selected]);
    }
  };

  const handleAttachDmsDocs = (docs: any[]) => {
    if (setDmsAttachments) {
      setDmsAttachments((prev) => {
        const next = [...prev];
        docs.forEach((doc) => {
          if (!next.some((x) => x.id === doc.id)) {
            next.push(doc);
          }
        });
        return next;
      });
    }
  };

  const handleRemoveDmsAttachment = (id: string) => {
    if (setDmsAttachments) {
      setDmsAttachments((prev) => prev.filter((x) => x.id !== id));
    }
  };

  const navigate = useNavigate();
  const location = useLocation();
  const localizedName = useLocalizedName();
  const { t, i18n } = useTranslation();
  const lang = i18n.language;
  const queryClient = useQueryClient();
  const { data: canJumpOnStepUpData, isFetched: hasLoadedCanJumpOnStepUp } =
    useCanJumpOnStepUp();
  // const { permissions } = usePermissions();
  const {
    userDetails,
    unFilteredUserDetails,
    selectedPositionPermissionKeys,
    selectedPositionId,
  } = useAuthUser();

  const allPositions =
    unFilteredUserDetails?.employee?.flatMap((emp) => emp.positions) || [];
  const currentPosition = allPositions.find(
    (pos) =>
      pos.employeePositionId === selectedPositionId ||
      pos.id === selectedPositionId,
  );
  const permissionKeys = currentPosition?.permissions?.map((p) => p.key) || [];
  const currentPositionId = currentPosition?.id;
  const canApprove =
    permissionKeys.includes("can:sendExternalRecordToRo") ||
    (selectedPositionPermissionKeys?.includes("can:sendExternalRecordToRo") ??
      false);
  const canapproveinternal =
    permissionKeys.includes("can:sendInternalRecordToRo") ||
    (selectedPositionPermissionKeys?.includes("can:sendInternalRecordToRo") ??
      false);
  const canapproveinternalMemo =
    permissionKeys.includes("can:dispatchInternalMemo") ||
    (selectedPositionPermissionKeys?.includes("can:dispatchInternalMemo") ??
      false);
  const intentRef = useRef<RecordFormIntent>("draft");
  // Guards against re-entrant submissions: set synchronously on the form's
  // submit event, before validation/normalization runs, so a second click
  // fired while those are still in flight is rejected immediately.
  const isSubmittingRef = useRef(false);
  // When the user reached this form via another tab (?from=collaborations
  // or ?from=approval), the back/cancel/save fallback should return them
  // there instead of the default Outgoing list. Forward and Update-and-
  // Approve buttons honor the same target via their consumer's onSuccess.
  const fromParam = new URLSearchParams(location.search).get("from");

  const isFromCollaboration = fromParam === "collaborations";
  const fallbackReturnUrl =
    fromParam === "collaborations"
      ? "/record-management/collaborations"
      : fromParam === "approval"
        ? "/record-management/approval"
        : "/record-management/userRecords";
  // Use refs to track initialization to prevent loops
  const initializedRef = useRef(false);
  useEffect(() => {
    initializedRef.current = false;
  }, [defaultValues, defaultValues?.mode]); // Reset when key properties change
  const shouldUseProvidedDefaultValues = Boolean(
    defaultValues && (isEditMode || defaultValues.mode === "edit"),
  );

  const getFormDefaultValues = useCallback(() => {
    if (shouldUseProvidedDefaultValues && defaultValues) {
      const receiversList = normalizeReceiverGroups(
        defaultValues.ReceiversList && defaultValues.ReceiversList.length > 0
          ? defaultValues.ReceiversList
          : buildReceiverGroupsFromLegacy({
              groupedTreeItems: defaultValues.groupedTreeItems,
              groupedItems: defaultValues.groupedItems,
              prefix: defaultValues.prefix ?? "",
              suffix: defaultValues.suffix ?? "",
              fallbackUnits: defaultValues.receivingUnitIds ?? [],
              fallbackNames: defaultValues.nonSmartOfficeReceivers ?? [],
            }),
      );

      const ccListSource =
        defaultValues.ccList && defaultValues.ccList.length > 0
          ? defaultValues.ccList
          : [createEmptyReceiverGroup()];
      const ccList: ReceiverGroup[] = ccListSource.map((group) => ({
        prefix: group?.prefix ?? "",
        suffix: group?.suffix ?? "",
        receivers: Array.isArray(group?.receivers) ? group.receivers : [],
      }));

      // FIX: Build forYourReferenceList properly from API data
      const forYourReferenceList = normalizeReceiverGroups(
        defaultValues.forYourReferenceList &&
          defaultValues.forYourReferenceList.length > 0
          ? defaultValues.forYourReferenceList
          : buildReceiverGroupsFromLegacy({
              groupedTreeItems: defaultValues.groupedFYRTreeItems, // Use FYR-specific legacy fields
              groupedItems: defaultValues.groupedFYRItems, // Use FYR-specific legacy fields
              prefix: defaultValues.ccPrefix ?? "", // FYR uses CC prefix/suffix
              suffix: defaultValues.ccSuffix ?? "",
              fallbackUnits: defaultValues.forYourReferenceUnitIds ?? [],
              fallbackNames: defaultValues.nonSmartOfficeReceiverCCs ?? [],
            }),
      );

      const receiverLegacy = buildLegacyGroupedValues(
        receiversList,
        treeOrganizationsOptions,
      );
      const ccLegacy = buildLegacyGroupedValues(
        ccList,
        ccTreeOrganizationsOptions,
      );
      const fyrLegacy = buildLegacyGroupedValues(
        forYourReferenceList,
        fyrTreeOrganizationsOptions,
      );

      return {
        ...defaultValues,
        // A returned/adjustment letter created under a delegated position can
        // come back from the API without a stored `preferredLanguage`. Falling
        // through to an empty value blanks out the Preferred Language select
        // and its placeholder. Keep the UI consistent with the rest of the app
        // by defaulting to the current application language. UI-only — does not
        // alter stored data.
        preferredLanguage: normalizePreferredLanguage(
          defaultValues.preferredLanguage,
          lang === "en" ? "en" : "am",
        ),
        headerId: defaultValues.headerId ?? "",
        footerId: defaultValues.footerId ?? "",
        ReceiversList: receiversList,
        ReceiverList: receiversList,
        ccList,
        forYourReferenceList,
        groupedTreeItems: receiverLegacy.groupedTreeItems,
        groupedItems: receiverLegacy.groupedItems,
        groupedCCTreeItems: ccLegacy.groupedTreeItems,
        groupedCCItems: ccLegacy.groupedItems,
        groupedFYRTreeItems: fyrLegacy.groupedTreeItems,
        groupedFYRItems: fyrLegacy.groupedItems,
        receivingUnitIds: receiverLegacy.units,
        nonSmartOfficeReceivers: receiverLegacy.names,
        externalCC: ccLegacy.units,
        nonSmartOfficeReceiverCCs: ccLegacy.names,
        forYourReferenceUnitIds: fyrLegacy.units,
        prefix: defaultValues.prefix ?? receiversList[0]?.prefix ?? "",
        suffix: defaultValues.suffix ?? receiversList[0]?.suffix ?? "",
        ccPrefix: defaultValues.ccPrefix ?? ccList[0]?.prefix ?? "",
        ccSuffix: defaultValues.ccSuffix ?? ccList[0]?.suffix ?? "",
        skipOneLevel: defaultValues.skipOneLevel ?? false,
      };
    }

    const values = { ...defaultCreateLetterValues };
    values.sincerelyText = i18n.getFixedT("am")("msg.sincerely");
    values.ReceiversList = normalizeReceiverGroups(values.ReceiversList);
    values.ReceiverList = values.ReceiversList;
    values.ccList = normalizeReceiverGroups(values.ccList);
    values.forYourReferenceList = normalizeReceiverGroups(
      values.forYourReferenceList,
    );

    const receiverLegacy = buildLegacyGroupedValues(
      values.ReceiversList,
      treeOrganizationsOptions,
    );
    const ccLegacy = buildLegacyGroupedValues(
      values.ccList,
      ccTreeOrganizationsOptions,
    );
    const fyrLegacy = buildLegacyGroupedValues(
      values.forYourReferenceList,
      fyrTreeOrganizationsOptions,
    );

    values.groupedTreeItems = receiverLegacy.groupedTreeItems;
    values.groupedItems = receiverLegacy.groupedItems;
    values.groupedCCTreeItems = ccLegacy.groupedTreeItems;
    values.groupedCCItems = ccLegacy.groupedItems;
    values.groupedFYRTreeItems = fyrLegacy.groupedTreeItems;
    values.groupedFYRItems = fyrLegacy.groupedItems;
    values.receivingUnitIds = receiverLegacy.units;
    values.nonSmartOfficeReceivers = receiverLegacy.names;
    values.externalCC = ccLegacy.units;
    values.nonSmartOfficeReceiverCCs = ccLegacy.names;
    values.forYourReferenceUnitIds = fyrLegacy.units;
    values.prefix = values.prefix ?? values.ReceiversList[0]?.prefix ?? "";
    values.suffix = values.suffix ?? values.ReceiversList[0]?.suffix ?? "";
    values.ccPrefix = values.ccPrefix ?? values.ccList[0]?.prefix ?? "";
    values.ccSuffix = values.ccSuffix ?? values.ccList[0]?.suffix ?? "";
    values.skipOneLevel = values.skipOneLevel ?? false;
    return values;
  }, [
    defaultValues,
    shouldUseProvidedDefaultValues,
    treeOrganizationsOptions,
    ccTreeOrganizationsOptions,
    fyrTreeOrganizationsOptions,
    lang,
  ]);
  const form = useForm<CreateOrEditLetter>({
    resolver: zodResolver(createLetterSchema),
    defaultValues: getFormDefaultValues(),
    mode: "onSubmit",
  });

  // Field-array `replace` handles for ccList / ReceiversList. RHF v7's
  // `form.reset()` doesn't reliably update useFieldArray internal state,
  // which is why edit mode was showing a stale empty group alongside the
  // API group. Calling `replace(newArray)` after reset forces useFieldArray
  // to mirror the new array exactly (1:1 with the API group count).
  const { replace: replaceCcList } = useFieldArray({
    control: form.control,
    name: "ccList",
  });
  const { replace: replaceReceiversList } = useFieldArray({
    control: form.control,
    name: "ReceiversList",
  });
  const { replace: replaceForYourReferenceList } = useFieldArray({
    control: form.control,
    name: "forYourReferenceList",
  });
  const recordTemplateId = form.watch("recordTemplateId");
  const preferredLanguageWatch = useWatch({
    control: form.control,
    name: "preferredLanguage",
    defaultValue: getFormDefaultValues().preferredLanguage ?? "am",
  });
  const sincerelyTextWatch = useWatch({
    control: form.control,
    name: "sincerelyText",
    defaultValue: getFormDefaultValues().sincerelyText ?? "",
  });
  const localizedFormName = useCallback(
    (name?: { am: string; en: string }) => {
      if (!name) return "";
      return lang === "am" ? name.am || name.en : name.en || name.am;
    },
    [lang],
  );
  const defaultSincerelyTextByLanguage = useMemo(
    () => ({
      am: i18n.getFixedT("am")("msg.sincerely"),
      en: i18n.getFixedT("en")("msg.sincerely"),
    }),
    [i18n],
  );
  const { checkHaveParent } = useUserDetail(userDetails as MeDto);
  const hasParent = !!checkHaveParent;

  useEffect(() => {
    if (shouldUseProvidedDefaultValues) {
      const next = getFormDefaultValues();
      form.reset(next);
      replaceCcList(next.ccList ?? []);
      replaceReceiversList(next.ReceiversList ?? []);
    }
  }, [
    form,
    getFormDefaultValues,
    replaceCcList,
    replaceReceiversList,
    shouldUseProvidedDefaultValues,
  ]);

  // Belt-and-suspenders: there are two competing `form.reset` effects above
  // that can race when `defaultValues` arrives mid-load. Specific fields
  // bound to <Select> components (initiationType) and <MultiSelect>
  // (collaborators) can end up empty in edit mode if a reset runs with
  // partial data. After both resets settle, force-set these two fields from
  // the latest defaultValues. Uses shouldDirty:false so it doesn't mark the
  // form as dirty.
  useEffect(() => {
    if (!shouldUseProvidedDefaultValues || !defaultValues) return;
    if (defaultValues.initiationType) {
      form.setValue("initiationType", defaultValues.initiationType, {
        shouldDirty: false,
      });
    }
    if (defaultValues.initiatedAs) {
      form.setValue("initiatedAs", defaultValues.initiatedAs, {
        shouldDirty: false,
      });
    }
    if (defaultValues.collaborators) {
      form.setValue("collaborators", defaultValues.collaborators, {
        shouldDirty: false,
      });
    }
    form.setValue("skipOneLevel", defaultValues.skipOneLevel ?? false, {
      shouldDirty: false,
    });
    const resolvedPreferredLanguage = normalizePreferredLanguage(
      defaultValues.preferredLanguage,
      lang === "en" ? "en" : "am",
    );
    form.setValue("preferredLanguage", resolvedPreferredLanguage, {
      shouldDirty: false,
    });
    if (defaultValues.headerId) {
      form.setValue("headerId", defaultValues.headerId, {
        shouldDirty: false,
      });
    }
    if (defaultValues.footerId) {
      form.setValue("footerId", defaultValues.footerId, {
        shouldDirty: false,
      });
    }
  }, [
    defaultValues,
    defaultValues?.initiationType,
    defaultValues?.initiatedAs,
    defaultValues?.collaborators,
    defaultValues?.skipOneLevel,
    defaultValues?.preferredLanguage,
    defaultValues?.headerId,
    defaultValues?.footerId,
    form,
    shouldUseProvidedDefaultValues,
    lang,
  ]);

  useEffect(() => {
    const nextSincerelyText =
      defaultSincerelyTextByLanguage[
        preferredLanguageWatch === "en" ? "en" : "am"
      ];
    const currentSincerelyText = sincerelyTextWatch ?? "";
    const isUsingDefaultSincerelyText =
      currentSincerelyText === defaultSincerelyTextByLanguage.am ||
      currentSincerelyText === defaultSincerelyTextByLanguage.en;

    if (
      !isUsingDefaultSincerelyText ||
      currentSincerelyText === nextSincerelyText
    ) {
      return;
    }

    form.setValue("sincerelyText", nextSincerelyText, {
      shouldDirty: false,
      shouldValidate: true,
    });
  }, [
    defaultSincerelyTextByLanguage,
    form,
    preferredLanguageWatch,
    sincerelyTextWatch,
  ]);

  // Direct guard: use the raw API response to force-set initiatedAs and
  // skipOneLevel in edit mode. These fields are not reliably populated via
  // the defaultValues chain because of render-order races between options
  // availability and form.reset timing. fullApiResponse is always the
  // authoritative source and arrives alongside defaultValues.
  useEffect(() => {
    if (!isEditMode || !fullApiResponse) return;
    if (fullApiResponse.initiatedAs) {
      form.setValue("initiatedAs", fullApiResponse.initiatedAs, {
        shouldDirty: false,
      });
    }
    if (fullApiResponse.initiationType) {
      form.setValue("initiationType", fullApiResponse.initiationType, {
        shouldDirty: false,
        shouldValidate: true,
      });
    }
    if (fullApiResponse.skipOneLevel !== undefined) {
      form.setValue("skipOneLevel", fullApiResponse.skipOneLevel, {
        shouldDirty: false,
      });
    }
    const content = fullApiResponse.content?.[0];
    if (content) {
      form.setValue(
        "preferredLanguage",
        normalizePreferredLanguage(fullApiResponse.preferredLanguage),
        { shouldDirty: false },
      );
      if (content.headerId) {
        form.setValue("headerId", content.headerId, { shouldDirty: false });
      }
      if (content.footerId) {
        form.setValue("footerId", content.footerId, { shouldDirty: false });
      }
    }
  }, [
    fullApiResponse,
    fullApiResponse?.initiatedAs,
    fullApiResponse?.initiationType,
    fullApiResponse?.skipOneLevel,
    fullApiResponse?.preferredLanguage,
    fullApiResponse?.content,
    isEditMode,
    form,
  ]);

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewState, setPreviewState] = useState<{
    formData: unknown;
    files: File[];
    headers: unknown[];
    footers: unknown[];
    positionsData: unknown[];
    employeesData: unknown[];
  } | null>(null);
  const [commentsDialogOpen, setCommentsDialogOpen] = useState(false);
  const [selectedHeader, setSelectedHeader] = useState<string>("");
  const [selectedFooter, setSelectedFooter] = useState<string>("");
  const [refreshing, setRefreshing] = useState(false);
  const [hasSubmitted, setHasSubmitted] = useState(false);
  const initiationTypeOptions = useInitiationTypeOptions();

  const canUseAttachmentFromDMS = tenantConfig.moduleConfig?.dms ?? false;

  const [receivingOptions, setReceivingOptions] = useState<TreeViewItem[]>(
    treeOrganizationsOptions,
  );
  const [ccReceivingOptions, setCcReceivingOptions] = useState<TreeViewItem[]>(
    ccTreeOrganizationsOptions,
  );
  const [fyrReceivingOptions, setFyrReceivingOptions] = useState<
    TreeViewItem[]
  >(ccTreeOrganizationsOptions);

  const unitId = userDetails?.employee?.[0]?.unitId;

  const { data: unitConfigData, isLoading: isUnitConfigLoading } =
    useUnitConfiguration(unitId ?? "", {
      enabled: !!unitId,
    });
  const unitConfig = unitConfigData?.data?.items?.[0];

  const canAssignCustomReferenceNumber =
    unitConfig?.canAssignCustomReferenceNumber ?? false;
  const internalMemoHasReferenceNumber =
    unitConfig?.internalMemoHasReferenceNumber ?? false;
  const shouldCollaboratorAlwaysSign =
    unitConfig?.shouldCollaboratorAlwaysSign ?? false;
  const shouldIncludeForYourReferenceInCC =
    unitConfig?.shouldIncludeForYourReferenceInCC ?? false;
  const canUserSkipLevel = unitConfig?.canUserSkipLevel ?? false;
  const canCollaborationBeCreatedForAll =
    unitConfig?.canCollaborationBeCreatedForAll ?? false;

  const canCollaboratorsEditRecord =
    unitConfig?.canRecordBeEditedByCollaborators ?? false;
  const canEditWhileCollaborating =
    isFromCollaboration && canCollaboratorsEditRecord;
  const { templates, isLoading: isTemplateLoading } = useTemplate(
    unitId as string,
  );
  const {
    listAllDepartmentResponse,
    recordTypes,
    currentEmployeesResponse,
    isLoading: isSettingsLoading,
  } = useSettings();
  const { data: prefixSuffixData, isLoading: isPrefixLoading } =
    usePrefixSuffix(unitId as string, form?.watch("recordType"), false);
  const { data: ccData, isLoading: isCCLoading } = usePrefixSuffix(
    unitId as string,
    "external",
    true,
  );

  const dedupeTreeItemsById = useCallback(
    (items: TreeViewItem[] | undefined) => {
      const uniqueMap = new Map<string, TreeViewItem>();
      items?.forEach((item) => {
        if (!uniqueMap.has(item.id)) {
          uniqueMap.set(item.id, item);
        }
      });
      return Array.from(uniqueMap.values());
    },
    [],
  );
  const receiversListWatch = useWatch({
    control: form.control,
    name: "ReceiversList",
    defaultValue: [],
  });
  const forYourReferenceListsWatch = useWatch({
    control: form.control,
    name: "forYourReferenceList",
    defaultValue: [],
  });

  const ccListWatch = useWatch({
    control: form.control,
    name: "ccList",
    defaultValue: [],
  });

  const receivingUnitIdsWatch = useWatch({
    control: form.control,
    name: "receivingUnitIds",
    defaultValue: [],
  });
  const forYourReferenceUnitIdsWatch = useWatch({
    control: form.control,
    name: "forYourReferenceUnitIds",
    defaultValue: [],
  });

  const externalCCWatch = useWatch({
    control: form.control,
    name: "externalCC",
    defaultValue: [],
  });

  // Watch form values for filtering
  const recordTypeValue = form?.watch("recordType");
  const initiationType = form.watch("initiationType");
  const initiatedAsValue = form.watch("initiatedAs");
  const shouldShowReferenceNumberField =
    canAssignCustomReferenceNumber &&
    (recordTypeValue === "internal" ||
      isExternalLikeRecordType(recordTypeValue) ||
      (recordTypeValue === "internal_memo" && internalMemoHasReferenceNumber));

  useEffect(() => {
    if (!shouldShowReferenceNumberField) {
      form.setValue("referenceNumber", "", {
        shouldDirty: false,
        shouldValidate: true,
      });
    }
  }, [form, shouldShowReferenceNumberField]);

  const isDirectRecordType = (item: {
    name?: { en?: string; am?: string };
    key?: string;
  }) => {
    const key = String(item.key || "").toLowerCase();
    const rawName = [item.name?.en, item.name?.am]
      .filter(Boolean)
      .join(" ")
      .toLowerCase();
    return key.includes("direct") || rawName.includes("direct");
  };

  const isBankRecordType = (item: {
    name?: { en?: string; am?: string };
    key?: string;
  }) => {
    const key = normalizeRecordTypeKey(item.key);
    const rawName = [item.name?.en, item.name?.am]
      .filter(Boolean)
      .join(" ")
      .toLowerCase();
    return key === "bank" || rawName.includes("bank");
  };

  // Check if current record type is direct
  const isCurrentRecordDirect = useMemo(() => {
    if (String(recordTypeValue || "").toLowerCase() === "direct") return true;
    if (!recordTypeValue || !recordTypes) return false;
    const currentRecordType = recordTypes.find(
      (item: any) => item.key === recordTypeValue,
    );
    return currentRecordType ? isDirectRecordType(currentRecordType) : false;
  }, [recordTypeValue, recordTypes]);

  const canJumpOnStepUp = canJumpOnStepUpData === true;
  const shouldShowCanSkipLevel =
    initiatedAsValue === "position" && canJumpOnStepUp && canUserSkipLevel;

  useEffect(() => {
    if (initiatedAsValue !== "position") {
      if (!form.getValues("skipOneLevel")) return;
      form.setValue("skipOneLevel", false, {
        shouldDirty: false,
        shouldValidate: true,
      });
      return;
    }

    // In edit mode the saved skipOneLevel must be preserved; routing was
    // already established when the record was created so auto-clearing it
    // here would silently change the routing path on resubmit.
    if (isEditMode) return;

    const shouldClearCanSkipLevel =
      isCurrentRecordDirect || (hasLoadedCanJumpOnStepUp && !canJumpOnStepUp);

    if (shouldClearCanSkipLevel) {
      if (!form.getValues("skipOneLevel")) return;
      form.setValue("skipOneLevel", false, {
        shouldDirty: false,
        shouldValidate: true,
      });
    }
  }, [
    canJumpOnStepUp,
    form,
    hasLoadedCanJumpOnStepUp,
    initiatedAsValue,
    isCurrentRecordDirect,
    isEditMode,
    shouldShowCanSkipLevel,
  ]);

  const receivingUnitIds = useMemo(() => {
    const unitsFromGroups = receiversListWatch
      ?.flatMap((group) => group?.receivers || [])
      .filter(isUnitReceiver)
      .map((receiver) => receiverToTreeViewItem(receiver, receivingOptions))
      .filter((item): item is TreeViewItem => Boolean(item));

    return dedupeTreeItemsById(
      unitsFromGroups
        ? unitsFromGroups.length > 0
          ? unitsFromGroups
          : receivingUnitIdsWatch
        : receivingUnitIdsWatch,
    );
  }, [
    receiversListWatch,
    receivingUnitIdsWatch,
    receivingOptions,
    dedupeTreeItemsById,
  ]);
  const forYourReferenceUnitIds = useMemo(() => {
    const unitsFromGroups = forYourReferenceListsWatch // <-- fix: use forYourReferenceListsWatch, not forYourReferenceUnitIdsWatch
      ?.flatMap((group) => group?.receivers || [])
      .filter(isUnitReceiver)
      .map((receiver) => receiverToTreeViewItem(receiver, fyrReceivingOptions)) // <-- fix: use fyrReceivingOptions
      .filter((item): item is TreeViewItem => Boolean(item));

    return dedupeTreeItemsById(
      unitsFromGroups
        ? unitsFromGroups.length > 0
          ? unitsFromGroups
          : forYourReferenceUnitIdsWatch // fallback to legacy field
        : forYourReferenceUnitIdsWatch,
    );
  }, [
    forYourReferenceListsWatch, // <-- fix dependency
    forYourReferenceUnitIdsWatch,
    fyrReceivingOptions, // <-- fix dependency
    dedupeTreeItemsById,
  ]);
  const externalCC = useMemo(() => {
    const unitsFromGroups = ccListWatch
      ?.flatMap((group) => group?.receivers || [])
      .filter(isUnitReceiver)
      .map((receiver) => receiverToTreeViewItem(receiver, ccReceivingOptions))
      .filter((item): item is TreeViewItem => Boolean(item));

    return dedupeTreeItemsById(
      unitsFromGroups
        ? unitsFromGroups.length > 0
          ? unitsFromGroups
          : externalCCWatch
        : externalCCWatch,
    );
  }, [ccListWatch, externalCCWatch, ccReceivingOptions, dedupeTreeItemsById]);

  const watchedToPositions = useWatch({
    control: form.control,
    name: "toPositions",
    defaultValue: [],
  });
  const watchedToEmployees = useWatch({
    control: form.control,
    name: "toEmployees",
    defaultValue: [],
  });
  const watchedCcEmployees = useWatch({
    control: form.control,
    name: "ccEmployees",
    defaultValue: [],
  });
  const toPositions = useMemo(
    () => watchedToPositions ?? [],
    [watchedToPositions],
  );
  const toEmployees = useMemo(
    () => watchedToEmployees ?? [],
    [watchedToEmployees],
  );
  const internalCC = form?.watch("internalCC") || [];
  const forYourReference = form?.watch("forYourReference") || [];
  const recordTypeKey = form?.watch("recordType") || "";
  // Fetch position prefixes with record type and position ID from metadata
  // REMOVED: Position prefix functionality has been removed from the form
  const { data: headerFooterData } = useHeaderFooterPresigned(
    unitId!,
    currentPositionId!,
    recordTypeKey as string,
  );
  const { isLoading: isPreviewLoading } = useRecordPreview();

  const recordPrefixesResponse =
    prefixSuffixData?.items
      ?.filter((item) => item.type === "prefix" && !item.isForCC)
      .map((item) => ({
        ...item,
        name: {
          en: item.name?.en ?? "",
          am: item.name?.am ?? "",
        },
      })) || [];

  const recordSuffixesResponse =
    prefixSuffixData?.items
      ?.filter((item) => item.type === "suffix" && !item.isForCC)
      .map((item) => ({
        ...item,
        name: {
          en: item.name?.en ?? "",
          am: item.name?.am ?? "",
        },
      })) || [];

  const ccPrefixesResponse =
    ccData?.items
      ?.filter((item) => item.type === "prefix" && item.isForCC)
      .map((item) => ({
        ...item,
        name: {
          en: item.name?.en ?? "",
          am: item.name?.am ?? "",
        },
      })) || [];

  const ccSuffixesResponse =
    ccData?.items
      ?.filter((item) => item.type === "suffix" && item.isForCC)
      .map((item) => ({
        ...item,
        name: {
          en: item.name?.en ?? "",
          am: item.name?.am ?? "",
        },
      })) || [];
  // Position prefix options - REMOVED
  // const positionPrefixOptions: KeyValue[] = [];
  const headers = useMemo(
    () => headerFooterData?.headers || [],
    [headerFooterData?.headers],
  );
  const footers = useMemo(
    () => headerFooterData?.footers || [],
    [headerFooterData?.footers],
  );
  const savedRecordContent = fullApiResponse?.content?.[0];
  const mergeSavedHeaderFooterItem = useCallback(
    (
      items: Array<{
        id: string;
        name?: { am?: string; en?: string };
        presigned?: string;
      }>,
      savedId?: string | null,
      savedEntity?: {
        id?: string;
        name?: { am?: string; en?: string };
        presigned?: string;
      } | null,
    ) => {
      if (!savedId || items.some((item) => item.id === savedId)) {
        return items;
      }
      return [
        ...items,
        {
          id: savedId,
          name: savedEntity?.name ?? { am: "", en: "" },
          presigned: savedEntity?.presigned,
        },
      ];
    },
    [],
  );
  const effectiveHeaders = useMemo(
    () =>
      mergeSavedHeaderFooterItem(
        headers,
        defaultValues?.headerId ?? savedRecordContent?.headerId,
        savedRecordContent?.header,
      ),
    [
      headers,
      defaultValues?.headerId,
      mergeSavedHeaderFooterItem,
      savedRecordContent?.header,
      savedRecordContent?.headerId,
    ],
  );
  const effectiveFooters = useMemo(
    () =>
      mergeSavedHeaderFooterItem(
        footers,
        defaultValues?.footerId ?? savedRecordContent?.footerId,
        savedRecordContent?.footer,
      ),
    [
      footers,
      defaultValues?.footerId,
      mergeSavedHeaderFooterItem,
      savedRecordContent?.footer,
      savedRecordContent?.footerId,
    ],
  );

  const canCreateDirectRecord = unitConfig?.canCreateDirectRecord ?? false;
  const canCreateBankRecord = unitConfig?.canCreateBankRelatedRecords ?? false;
  const canPositionBasedRecordsBeCreated =
    unitConfig?.canPositionBasedRecordsBeCreated ?? false;
  const shouldShowHeaderFooterSelection =
    !isCurrentRecordDirect ||
    unitConfig?.shouldDirectRecordHaveHeaderAndFooter !== false;
  const isEditingExistingTeamRecord =
    Boolean(isEditMode) &&
    (defaultValues?.initiationType === "team" ||
      initiationType === "team" ||
      fullApiResponse?.initiationType === "team");
  const canShowTeamInitiation =
    canCollaborationBeCreatedForAll ||
    recordTypeValue === "direct" ||
    isEditingExistingTeamRecord;
  const filteredInitiationTypeOptions = initiationTypeOptions.filter(
    (option) => option.value !== "team" || canShowTeamInitiation,
  );

  const recordTypeOptions: KeyValue[] =
    recordTypes
      ?.filter(
        (item: { name?: { en?: string; am?: string }; key?: string }) => {
          if (!canCreateDirectRecord && isDirectRecordType(item)) return false;
          if (!canCreateBankRecord && isBankRecordType(item)) return false;
          return true;
        },
      )
      .map((item: { name: { en: string; am: string }; key: string }) => ({
        label:
          item.key == "direct"
            ? localizedName({ en: "Direct Letter", am: "ቀጥታ ደብዳቤ" })
            : localizedName(item.name),
        value: item.key,
      })) || [];

  const creationType: KeyValue[] = [
    ...(canPositionBasedRecordsBeCreated ||
    initiatedAsValue === "position" ||
    defaultValues?.initiatedAs === "position"
      ? [
          {
            label: t("addRecord.Position"),
            value: "position",
            employeePositionId: "",
          },
        ]
      : []),
    { label: t("addRecord.personal"), value: "self", employeePositionId: "" },
  ];

  const employeesList: KeyValue[] = useMemo(
    () =>
      currentEmployeesResponse?.items.map((employee: EmployeeWithUnitDto) => ({
        label: localizedFormName(employee.user.name),
        value: employee.employeePositions?.[0]?.id ?? "",
        employeePositionId: "",
      })) || [],
    [currentEmployeesResponse?.items, localizedFormName],
  );

  const employeesCCList: KeyValue[] = useMemo(
    () =>
      currentEmployeesResponse?.items.map((employee: EmployeeWithUnitDto) => ({
        label: localizedFormName(employee.user.name),
        value: employee.employeePositions?.[0]?.id ?? "",
        employeePositionId: "",
      })) || [],
    [currentEmployeesResponse?.items, localizedFormName],
  );
  const ccEmployeeOptions = useMemo(
    () =>
      employeesCCList.filter((option) => !toEmployees.includes(option.value)),
    [employeesCCList, toEmployees],
  );
  const ccEmployeesInvalidSelectionMessage = t(
    "msg.ccEmployeesInvalidSelection",
    "One or more selected CC users do not have a valid assigned position. Remove them or update their employee profile.",
  );
  const hasInvalidCcEmployeeSelection = useCallback(
    (selectedValues?: string[] | null) => {
      const selectedSet = new Set((selectedValues ?? []).filter(Boolean));
      if (selectedSet.size === 0) return false;

      return Array.from(selectedSet).some((employeePositionId) => {
        const employee = currentEmployeesResponse?.items?.find(
          (item) => item.employeePositions?.[0]?.id === employeePositionId,
        );
        const employeePosition = employee?.employeePositions?.[0];

        return (
          !employee || !employeePosition?.id || !employeePosition?.position?.id
        );
      });
    },
    [currentEmployeesResponse?.items],
  );
  const setCcEmployeesInvalidSelectionError = useCallback(() => {
    form.setError("ccEmployees", {
      type: "manual",
      message: ccEmployeesInvalidSelectionMessage,
    });
  }, [ccEmployeesInvalidSelectionMessage, form]);
  const validateCcEmployeesSelection = useCallback(
    (selectedValues?: string[] | null) => {
      if (hasInvalidCcEmployeeSelection(selectedValues)) {
        setCcEmployeesInvalidSelectionError();
        return false;
      }

      if (form.getFieldState("ccEmployees").error?.type === "manual") {
        form.clearErrors("ccEmployees");
      }
      return true;
    },
    [form, hasInvalidCcEmployeeSelection, setCcEmployeesInvalidSelectionError],
  );
  const surfaceCcEmployeesSubmitError = useCallback(
    (error: unknown) => {
      const message = error instanceof Error ? error.message : "";

      if (
        message.includes("Cannot read properties of null") &&
        message.includes("id")
      ) {
        setCcEmployeesInvalidSelectionError();
        setHasSubmitted(true);
        setShouldScrollToError(true);
        toast.error(t("addRecord.formHasErrors"));
        return true;
      }

      return false;
    },
    [setCcEmployeesInvalidSelectionError, t],
  );
  useEffect(() => {
    validateCcEmployeesSelection(watchedCcEmployees);
  }, [validateCcEmployeesSelection, watchedCcEmployees]);

  const letterTemplates = templates.map((template: LetterTemplateDto) => ({
    id: template.id,
    name: localizedName(template.name),
    subject: template.subject,
    content: template.body,
    sincerelyText: template.sincerelyText,
  }));
  const letterTemplateOptions = [
    ...letterTemplates.map((template) => ({
      label: template.name || "Template",
      value: template.id,
    })),
    {
      label: t("Cancel"),
      value: "unselect",
    },
  ];

  const shouldClearEditor = false;
  // Add these refs and state
  const editorSectionRef = useRef<HTMLDivElement>(null);
  const [lastErrorField, setLastErrorField] = useState<string | null>(null);
  const [shouldScrollToError, setShouldScrollToError] = useState(false);
  // Enhanced scroll function with multiple fallbacks
  const scrollToFirstError = useCallback((errors: Record<string, unknown>) => {
    if (!errors || Object.keys(errors).length === 0) return;

    const firstError = Object.keys(errors)[0];
    setLastErrorField(firstError);

    const findAndScrollToElement = (attempt = 0) => {
      let errorElement: HTMLElement | null = null;

      if (firstError === "body") {
        // Try multiple methods to find the body editor section
        errorElement = editorSectionRef.current;

        if (!errorElement) {
          // Try to find by data attribute
          errorElement = document.querySelector(
            '[data-field="body-section"]',
          ) as HTMLElement;
        }

        if (!errorElement) {
          // Try to find by card content
          const cards = Array.from(document.querySelectorAll(".card"));
          errorElement = cards.find(
            (card) =>
              card.textContent?.includes("Letter Content") ||
              card.textContent?.includes("Body"),
          ) as HTMLElement;
        }
      } else {
        errorElement = document.querySelector(`[data-field="${firstError}"]`);
      }

      if (errorElement) {
        // Scroll to the element
        errorElement.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });

        // Add visual highlight
        errorElement.classList.add(
          "ring-2",
          "ring-destructive",
          "ring-offset-2",
        );

        setTimeout(() => {
          errorElement?.classList.remove(
            "ring-2",
            "ring-destructive",
            "ring-offset-2",
          );
          setLastErrorField(null);
        }, 4000);

        return true;
      } else if (attempt < 5) {
        // Retry after a short delay (DOM might not be ready yet)
        setTimeout(() => findAndScrollToElement(attempt + 1), 200);
        return false;
      } else {
        return false;
      }
    };

    findAndScrollToElement();
  }, []);

  useEffect(() => {
    setReceivingOptions(treeOrganizationsOptions);
  }, [treeOrganizationsOptions]);

  useEffect(() => {
    setCcReceivingOptions(ccTreeOrganizationsOptions);
  }, [ccTreeOrganizationsOptions]);
  useEffect(() => {
    setFyrReceivingOptions(fyrTreeOrganizationsOptions);
  }, [fyrTreeOrganizationsOptions]);

  // Watch for form submission and errors
  useEffect(() => {
    if (shouldScrollToError && Object.keys(form.formState.errors).length > 0) {
      scrollToFirstError(form.formState.errors);
      setShouldScrollToError(false);
    }
  }, [form.formState.errors, shouldScrollToError, scrollToFirstError]);

  // Also add a direct effect for body errors
  useEffect(() => {
    if (form.formState.errors.body && hasSubmitted) {
      setTimeout(() => {
        if (editorSectionRef.current) {
          editorSectionRef.current.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
          editorSectionRef.current.classList.add(
            "ring-2",
            "ring-destructive",
            "ring-offset-2",
          );

          setTimeout(() => {
            editorSectionRef.current?.classList.remove(
              "ring-2",
              "ring-destructive",
              "ring-offset-2",
            );
          }, 4000);
        }
      }, 150);
    }
  }, [form.formState.errors.body, hasSubmitted]);

  const currentUserCollaborationId = useMemo(() => {
    const collaborators = fullApiResponse?.collaborators ?? [];
    const currentByUserId = collaborators.find(
      (collaborator: any) => collaborator.userId === userDetails?.id,
    );

    if (currentByUserId?.id) {
      return currentByUserId.id as string;
    }

    const currentByPositionId = collaborators.find(
      (collaborator: any) =>
        collaborator.employeePositionId === selectedPositionId,
    );

    return currentByPositionId?.id as string | undefined;
  }, [fullApiResponse?.collaborators, selectedPositionId, userDetails?.id]);
  const isTeamRejectedEdit =
    isEditMode && fullApiResponse?.statusKey === "Team Rejected";

  // Allow editing initiation type when the letter returns to initiator as "Team Adjusted"
  const isTeamAdjustedEdit =
    isEditMode && fullApiResponse?.statusKey === "Team Adjusted";

  const effectiveRecordId = recordId || fullApiResponse?.id;
  const currentContentId = fullApiResponse?.content?.[0]?.id;
  const canOpenCollaborationComments =
    Boolean(isEditMode) &&
    initiationType === "team" &&
    Boolean(effectiveRecordId);
  const selectedHeaderId = form.watch("headerId");
  const selectedFooterId = form.watch("footerId");

  useEffect(() => {
    if (!shouldShowHeaderFooterSelection) {
      if (
        isEditMode &&
        (savedRecordContent?.headerId || savedRecordContent?.footerId)
      ) {
        return;
      }
      form.setValue("headerId", DISABLED_DIRECT_HEADER_FOOTER_VALUE, {
        shouldDirty: false,
      });
      form.setValue("footerId", DISABLED_DIRECT_HEADER_FOOTER_VALUE, {
        shouldDirty: false,
      });
      setSelectedHeader("");
      setSelectedFooter("");
    }
  }, [
    isEditMode,
    savedRecordContent?.footerId,
    savedRecordContent?.headerId,
    shouldShowHeaderFooterSelection,
    form,
  ]);

  // Force isWithTeamSignature=true when shouldCollaboratorAlwaysSign is enabled
  useEffect(() => {
    if (shouldCollaboratorAlwaysSign && initiationType === "team") {
      form.setValue("isWithTeamSignature", true);
    }
  }, [shouldCollaboratorAlwaysSign, initiationType, form]);

  useEffect(() => {
    if (
      isUnitConfigLoading ||
      canShowTeamInitiation ||
      initiationType !== "team" ||
      isEditingExistingTeamRecord
    ) {
      return;
    }

    form.setValue("initiationType", "self", {
      shouldDirty: true,
      shouldValidate: true,
    });
    form.setValue("collaborators", [], {
      shouldDirty: true,
      shouldValidate: true,
    });
    form.setValue("isWithTeamSignature", false, {
      shouldDirty: true,
      shouldValidate: true,
    });
  }, [
    canShowTeamInitiation,
    form,
    initiationType,
    isEditingExistingTeamRecord,
    isUnitConfigLoading,
  ]);

  useEffect(() => {
    if (
      isUnitConfigLoading ||
      canPositionBasedRecordsBeCreated ||
      isEditMode ||
      initiatedAsValue !== "position"
    ) {
      return;
    }

    form.setValue("initiatedAs", "self", {
      shouldDirty: true,
      shouldValidate: true,
    });
  }, [
    canPositionBasedRecordsBeCreated,
    form,
    initiatedAsValue,
    isEditMode,
    isUnitConfigLoading,
  ]);

  // ✅ 1. Initialize options and sincerely text
  useEffect(() => {
    if (receivingOptions.length === 0) {
      setReceivingOptions(treeOrganizationsOptions);
    }

    if (ccReceivingOptions.length === 0) {
      setCcReceivingOptions(ccTreeOrganizationsOptions);
    }
    if (fyrReceivingOptions.length === 0) {
      setFyrReceivingOptions(fyrTreeOrganizationsOptions);
    }
  }, [
    receivingOptions.length,
    ccReceivingOptions.length,
    treeOrganizationsOptions,
    ccTreeOrganizationsOptions,
    fyrTreeOrganizationsOptions,
    t,
    form,
  ]);

  // ✅ 2. Initialize header/footer only when the current value is empty or invalid.
  // This preserves edit-mode defaults instead of forcing the first option.
  useEffect(() => {
    if (!shouldShowHeaderFooterSelection) {
      return;
    }

    const currentHeaderId = form.getValues("headerId");
    const currentFooterId = form.getValues("footerId");

    if (headers.length > 0) {
      const headerExists = headers.some(
        (header) => header.id === currentHeaderId,
      );
      // In edit mode, only auto-select when the field is empty. A non-empty
      // headerId from the saved record should never be overridden by a
      // re-fetch triggered by a recordTypeKey query key change.
      if (!currentHeaderId || (!isEditMode && !headerExists)) {
        form.setValue("headerId", headers[0].id, { shouldDirty: false });
      } else if (
        isEditMode &&
        defaultValues?.headerId &&
        currentHeaderId !== defaultValues.headerId
      ) {
        form.setValue("headerId", defaultValues.headerId, {
          shouldDirty: false,
        });
      }
    }

    if (footers.length > 0) {
      const footerExists = footers.some(
        (footer) => footer.id === currentFooterId,
      );
      if (!currentFooterId || (!isEditMode && !footerExists)) {
        form.setValue("footerId", footers[0].id, { shouldDirty: false });
      } else if (
        isEditMode &&
        defaultValues?.footerId &&
        currentFooterId !== defaultValues.footerId
      ) {
        form.setValue("footerId", defaultValues.footerId, {
          shouldDirty: false,
        });
      }
    }
  }, [
    headers,
    footers,
    form,
    isEditMode,
    defaultValues?.headerId,
    defaultValues?.footerId,
    selectedHeaderId,
    selectedFooterId,
    shouldShowHeaderFooterSelection,
  ]);

  // ✅ 3. Initialize form with default values (only once)
  useEffect(() => {
    if (
      !isLoadingRecord &&
      shouldUseProvidedDefaultValues &&
      defaultValues &&
      !initializedRef.current
    ) {
      const receiversList = normalizeReceiverGroups(
        defaultValues.ReceiversList && defaultValues.ReceiversList.length > 0
          ? defaultValues.ReceiversList
          : buildReceiverGroupsFromLegacy({
              groupedTreeItems: defaultValues.groupedTreeItems,
              groupedItems: defaultValues.groupedItems,
              prefix: defaultValues.prefix ?? "",
              suffix: defaultValues.suffix ?? "",
              fallbackUnits: defaultValues.receivingUnitIds ?? [],
              fallbackNames: defaultValues.nonSmartOfficeReceivers ?? [],
            }),
      );

      const ccListSource =
        defaultValues.ccList && defaultValues.ccList.length > 0
          ? defaultValues.ccList
          : [createEmptyReceiverGroup()];
      const ccList: ReceiverGroup[] = ccListSource.map((group) => ({
        prefix: group?.prefix ?? "",
        suffix: group?.suffix ?? "",
        receivers: Array.isArray(group?.receivers) ? group.receivers : [],
      }));

      // FIX: Initialize forYourReferenceList properly
      const forYourReferenceList = normalizeReceiverGroups(
        defaultValues.forYourReferenceList &&
          defaultValues.forYourReferenceList.length > 0
          ? defaultValues.forYourReferenceList
          : buildReceiverGroupsFromLegacy({
              groupedTreeItems: defaultValues.groupedFYRTreeItems,
              groupedItems: defaultValues.groupedFYRItems,
              prefix: defaultValues.ccPrefix ?? "",
              suffix: defaultValues.ccSuffix ?? "",
              fallbackUnits: defaultValues.forYourReferenceUnitIds ?? [],
              fallbackNames: defaultValues.nonSmartOfficeReceiverCCs ?? [],
            }),
      );

      const receiverLegacy = buildLegacyGroupedValues(
        receiversList,
        treeOrganizationsOptions,
      );
      const ccLegacy = buildLegacyGroupedValues(
        ccList,
        ccTreeOrganizationsOptions,
      );
      const fyrLegacy = buildLegacyGroupedValues(
        forYourReferenceList,
        fyrTreeOrganizationsOptions,
      );

      replaceForYourReferenceList(forYourReferenceList);

      form.reset({
        ...defaultValues,
        preferredLanguage: normalizePreferredLanguage(
          defaultValues.preferredLanguage,
          lang === "en" ? "en" : "am",
        ),
        headerId: defaultValues.headerId ?? "",
        footerId: defaultValues.footerId ?? "",
        ReceiversList: receiversList,
        ReceiverList: receiversList,
        ccList,
        forYourReferenceList,
        groupedTreeItems: receiverLegacy.groupedTreeItems,
        groupedItems: receiverLegacy.groupedItems,
        groupedCCTreeItems: ccLegacy.groupedTreeItems,
        groupedCCItems: ccLegacy.groupedItems,
        groupedFYRTreeItems: fyrLegacy.groupedTreeItems,
        groupedFYRItems: fyrLegacy.groupedItems,
        receivingUnitIds: receiverLegacy.units,
        nonSmartOfficeReceivers: receiverLegacy.names,
        externalCC: ccLegacy.units,
        nonSmartOfficeReceiverCCs: ccLegacy.names,
        forYourReferenceUnitIds: fyrLegacy.units,
        prefix: defaultValues.prefix ?? receiversList[0]?.prefix ?? "",
        suffix: defaultValues.suffix ?? receiversList[0]?.suffix ?? "",
        ccPrefix: defaultValues.ccPrefix ?? ccList[0]?.prefix ?? "",
        ccSuffix: defaultValues.ccSuffix ?? ccList[0]?.suffix ?? "",
        skipOneLevel: defaultValues.skipOneLevel ?? false,
        mode: isEditMode ? "edit" : "add",
      });

      replaceCcList(ccList);
      replaceReceiversList(receiversList);
      replaceForYourReferenceList(forYourReferenceList);

      initializedRef.current = true;
      return;
    }

    if (initializedRef.current) {
      form.setValue("mode", isEditMode ? "edit" : "add");
    }
  }, [
    isLoadingRecord,
    defaultValues,
    isEditMode,
    form,
    treeOrganizationsOptions,
    ccTreeOrganizationsOptions,
    fyrTreeOrganizationsOptions,
    replaceCcList,
    replaceReceiversList,
    replaceForYourReferenceList,
    shouldUseProvidedDefaultValues,
    lang,
  ]);

  // ✅ 4. Handle recordType change watcher (one-time setup)
  // Preserve organization fields when record type changes, only reset truly incompatible fields
  useEffect(() => {
    const sub = form.watch((v, { name }) => {
      if (name === "recordType" && initializedRef.current) {
        requestAnimationFrame(() => {
          if (isExternalLikeRecordType(v.recordType)) {
            // Only reset internal-specific fields that are incompatible with external records
            form.resetField("toPositions");
            form.resetField("toEmployees");
            form.resetField("internalCC");
            form.resetField("ccEmployees");
            // Clear prefix/suffix for internal recipients only
            form.setValue("prefix", "");
            form.setValue("suffix", "");
          } else {
            // Only reset external-specific fields that are incompatible with internal records
            form.resetField("nonSmartOfficeReceiverCCs");
            // Clear prefix/suffix for external recipients only
            form.setValue("ccPrefix", "");
            form.setValue("ccSuffix", "");
            if (v.recordType === "internal_memo" || v.recordType === "direct") {
              const emptyCcGroups = [createEmptyReceiverGroup()];
              form.setValue("ccList", emptyCcGroups, {
                shouldDirty: true,
                shouldValidate: true,
              });
              replaceCcList(emptyCcGroups);
              form.setValue("externalCC", [], {
                shouldDirty: true,
                shouldValidate: true,
              });
              form.setValue("nonSmartOfficeReceiverCCs", [], {
                shouldDirty: true,
                shouldValidate: true,
              });
              form.setValue("ccPrefix", "", {
                shouldDirty: true,
                shouldValidate: true,
              });
              form.setValue("ccSuffix", "", {
                shouldDirty: true,
                shouldValidate: true,
              });
            }
          }
          // Note: receivingUnitIds and externalCC are preserved for external records
          // Note: toPositions and toEmployees are preserved for internal records
          // This allows users to switch record types without losing their organization selections
        });
      }
    });
    return () => sub.unsubscribe();
  }, [form, replaceCcList]);

  // ✅ 5. Update header/footer previews dynamically when selected
  useEffect(() => {
    if (!shouldShowHeaderFooterSelection) {
      setSelectedHeader("");
      setSelectedFooter("");
      return;
    }

    if (effectiveHeaders.length && selectedHeaderId) {
      const h = effectiveHeaders.find((x) => x.id === selectedHeaderId);
      if (h?.presigned)
        setSelectedHeader(
          `<div class="letter-header"><img src="${h.presigned}" alt="Header" style="width: 100%; max-height: 200px;" /></div>`,
        );
    }

    if (effectiveFooters.length && selectedFooterId) {
      const f = effectiveFooters.find((x) => x.id === selectedFooterId);
      if (f?.presigned)
        setSelectedFooter(
          `<div class="letter-footer"><img src="${f.presigned}" alt="Footer" style="width: 100%; max-height: 200px;" /></div>`,
        );
    }
  }, [
    effectiveFooters,
    effectiveHeaders,
    selectedHeaderId,
    selectedFooterId,
    shouldShowHeaderFooterSelection,
  ]);

  const handleSubmit = async (values: CreateOrEditLetter) => {
    try {
      if (!validateCcEmployeesSelection(values.ccEmployees)) {
        setHasSubmitted(true);
        setShouldScrollToError(true);
        toast.error(t("addRecord.formHasErrors"));
        return;
      }

      if (shouldShowHeaderFooterSelection) {
        const missingHeader =
          !values.headerId ||
          values.headerId === DISABLED_DIRECT_HEADER_FOOTER_VALUE;
        const missingFooter =
          !values.footerId ||
          values.footerId === DISABLED_DIRECT_HEADER_FOOTER_VALUE;

        if (missingHeader || missingFooter) {
          if (missingHeader) {
            form.setError("headerId", {
              type: "manual",
              message: t("msg.headerRequired"),
            });
          }

          if (missingFooter) {
            form.setError("footerId", {
              type: "manual",
              message: t("msg.footerRequired"),
            });
          }

          setHasSubmitted(true);
          setShouldScrollToError(true);
          toast.error(t("addRecord.formHasErrors"));
          return;
        }

        form.clearErrors(["headerId", "footerId"]);
      }

      const preferredLanguage = values.preferredLanguage === "en" ? "en" : "am";
      const normalizedReceiversList = normalizeReceiverGroups(
        values.ReceiversList,
      );
      const normalizedCCList = stripEmptyReceiverGroups(
        normalizeReceiverGroups(values.ccList),
      );
      const normalizedFYRList = stripEmptyReceiverGroups(
        normalizeReceiverGroups(values.forYourReferenceList),
      );
      const localizedReceiversList = localizeReceiverGroups(
        normalizedReceiversList,
        {
          prefixOptions: recordPrefixesResponse,
          suffixOptions: recordSuffixesResponse,
          language: preferredLanguage,
        },
      );
      const localizedCCList = localizeReceiverGroups(normalizedCCList, {
        prefixOptions: ccPrefixesResponse,
        suffixOptions: ccSuffixesResponse,
        language: preferredLanguage,
      });
      const localizedFYRList = localizeReceiverGroups(normalizedFYRList, {
        prefixOptions: ccPrefixesResponse, // FYR uses CC prefix/suffix
        suffixOptions: ccSuffixesResponse,
        language: preferredLanguage,
      });

      const receiversLegacy = buildLegacyGroupedValues(
        localizedReceiversList,
        receivingOptions,
      );
      const ccLegacy = buildLegacyGroupedValues(
        localizedCCList,
        ccReceivingOptions,
      );
      const fyrLegacy = buildLegacyGroupedValues(
        localizedFYRList,
        fyrReceivingOptions,
      );

      const normalizedValues: CreateOrEditLetter = {
        ...values,
        ReceiversList: localizedReceiversList,
        ReceiverList: localizedReceiversList,
        ccList: localizedCCList,
        groupedTreeItems: receiversLegacy.groupedTreeItems,
        groupedItems: receiversLegacy.groupedItems,
        groupedCCTreeItems: ccLegacy.groupedTreeItems,
        groupedFYRTreeItems: fyrLegacy.groupedTreeItems,
        groupedCCItems: ccLegacy.groupedItems,
        forYourReferenceList: localizedFYRList,
        receivingUnitIds:
          dedupeTreeItemsById(
            receiversLegacy.units.length > 0
              ? receiversLegacy.units
              : values.receivingUnitIds || [],
          ) || [],
        externalCC:
          dedupeTreeItemsById(
            ccLegacy.units.length > 0
              ? ccLegacy.units
              : values.externalCC || [],
          ) || [],
        prefix: resolveLocalizedPrefixSuffixValue(
          values.prefix ?? localizedReceiversList?.[0]?.prefix ?? "",
          recordPrefixesResponse,
          preferredLanguage,
        ),
        suffix: resolveLocalizedPrefixSuffixValue(
          values.suffix ?? localizedReceiversList?.[0]?.suffix ?? "",
          recordSuffixesResponse,
          preferredLanguage,
        ),
        ccPrefix: resolveLocalizedPrefixSuffixValue(
          values.ccPrefix ?? localizedCCList?.[0]?.prefix ?? "",
          ccPrefixesResponse,
          preferredLanguage,
        ),
        ccSuffix: resolveLocalizedPrefixSuffixValue(
          values.ccSuffix ?? localizedCCList?.[0]?.suffix ?? "",
          ccSuffixesResponse,
          preferredLanguage,
        ),
        nonSmartOfficeReceivers:
          receiversLegacy.names ?? values.nonSmartOfficeReceivers ?? [],
        // FIX: Include FYR units
        forYourReferenceUnitIds:
          dedupeTreeItemsById(
            fyrLegacy.units.length > 0
              ? fyrLegacy.units
              : values.forYourReferenceUnitIds || [],
          ) || [],
        nonSmartOfficeReceiverCCs:
          ccLegacy.names ?? values.nonSmartOfficeReceiverCCs ?? [],
        skipOneLevel: shouldShowCanSkipLevel
          ? (values.skipOneLevel ?? false)
          : false,
      };

      await onSubmit(normalizedValues, intentRef.current);
      intentRef.current = "draft";
      setHasSubmitted(true);
      // Validate form before submission
      // After successful submit → clear editor
    } catch (error) {
      if (surfaceCcEmployeesSubmitError(error)) {
        return;
      }

      const message =
        error instanceof Error && error.message
          ? error.message
          : t("msg.genericError");
      toast.error(message);
    }
  };

  const validateReceiversBeforePreview = async () => {
    if (isExternalLikeRecordType(recordTypeValue)) {
      return form.trigger([
        "ReceiversList",
        "receivingUnitIds",
        "nonSmartOfficeReceivers",
      ]);
    }

    if (
      recordTypeValue === "internal" ||
      recordTypeValue === "internal_memo" ||
      recordTypeValue === "direct"
    ) {
      return form.trigger(["toPositions", "toEmployees"]);
    }

    return true;
  };

  const handlePreviewValidationFailure = () => {
    setHasSubmitted(true);
    setShouldScrollToError(true);
    toast.error(t("addRecord.formHasErrors"));
  };

  const handleOpenPreview = async () => {
    const receiversValid = await validateReceiversBeforePreview();
    if (!receiversValid) {
      handlePreviewValidationFailure();
      return;
    }

    const currentValues = form.getValues();
    const preferredLanguage =
      currentValues.preferredLanguage === "en" ? "en" : "am";
    const normalizedReceiversList = normalizeReceiverGroups(
      currentValues.ReceiversList,
    );
    const normalizedCCList = normalizeReceiverGroups(currentValues.ccList);
    const sanitizedCCList = stripEmptyReceiverGroups(normalizedCCList);
    const localizedReceiversList = localizeReceiverGroups(
      normalizedReceiversList,
      {
        prefixOptions: recordPrefixesResponse,
        suffixOptions: recordSuffixesResponse,
        language: preferredLanguage,
      },
    );
    const localizedCCList = localizeReceiverGroups(sanitizedCCList, {
      prefixOptions: ccPrefixesResponse,
      suffixOptions: ccSuffixesResponse,
      language: preferredLanguage,
    });
    const receiversLegacy = buildLegacyGroupedValues(
      localizedReceiversList,
      receivingOptions,
    );
    const ccLegacy = buildLegacyGroupedValues(
      localizedCCList,
      ccReceivingOptions,
    );
    const normalizedFYRList = normalizeReceiverGroups(
      currentValues.forYourReferenceList,
    );
    const sanitizedFYRList = stripEmptyReceiverGroups(normalizedFYRList);
    const localizedFYRList = localizeReceiverGroups(sanitizedFYRList, {
      prefixOptions: ccPrefixesResponse,
      suffixOptions: ccSuffixesResponse,
      language: preferredLanguage,
    });
    const fyrLegacy = buildLegacyGroupedValues(
      localizedFYRList,
      fyrReceivingOptions,
    );

    const previewFormData = {
      ...currentValues,
      ReceiversList: localizedReceiversList,
      ReceiverList: localizedReceiversList,
      ccList: localizedCCList,
      forYourReferenceList: localizedFYRList,
      groupedFYRTreeItems: fyrLegacy.groupedTreeItems,
      groupedFYRItems: fyrLegacy.groupedItems,
      groupedTreeItems: receiversLegacy.groupedTreeItems,
      groupedItems: receiversLegacy.groupedItems,
      groupedCCTreeItems: ccLegacy.groupedTreeItems,
      groupedCCItems: ccLegacy.groupedItems,
      prefix: resolveLocalizedPrefixSuffixValue(
        currentValues.prefix ?? localizedReceiversList?.[0]?.prefix ?? "",
        recordPrefixesResponse,
        preferredLanguage,
      ),
      suffix: resolveLocalizedPrefixSuffixValue(
        currentValues.suffix ?? localizedReceiversList?.[0]?.suffix ?? "",
        recordSuffixesResponse,
        preferredLanguage,
      ),
      ccPrefix: resolveLocalizedPrefixSuffixValue(
        currentValues.ccPrefix ?? localizedCCList?.[0]?.prefix ?? "",
        ccPrefixesResponse,
        preferredLanguage,
      ),
      ccSuffix: resolveLocalizedPrefixSuffixValue(
        currentValues.ccSuffix ?? localizedCCList?.[0]?.suffix ?? "",
        ccSuffixesResponse,
        preferredLanguage,
      ),
      skipOneLevel: shouldShowCanSkipLevel
        ? (currentValues.skipOneLevel ?? false)
        : false,
    };

    setPreviewState({
      formData: previewFormData,
      files,
      headers: effectiveHeaders,
      footers: effectiveFooters,
      positionsData: listAllDepartmentResponse || [],
      employeesData: currentEmployeesResponse?.items || [],
    });
    setPreviewOpen(true);
  };

  const handleInvalidSubmit = (submitErrors: typeof form.formState.errors) => {
    setHasSubmitted(true);
    setShouldScrollToError(true);
    // Surface the exact field paths and Zod messages so we can see why
    // submit was blocked. The generic toast hides this detail otherwise.
    const errors = submitErrors;
    const flat: Array<{ path: string; type?: string; message?: string }> = [];
    const walk = (obj: unknown, path: string): void => {
      if (!obj || typeof obj !== "object") return;
      const o = obj as Record<string, unknown>;
      if (o.message || o.type) {
        flat.push({
          path: path || "(root)",
          type: typeof o.type === "string" ? o.type : undefined,
          message: typeof o.message === "string" ? o.message : undefined,
        });
        return;
      }
      for (const key of Object.keys(o)) {
        walk(o[key], path ? `${path}.${key}` : key);
      }
    };
    walk(errors, "");
    console.error(
      "[RecordForm] Submit validation failed",
      "\n  errors flat:",
      flat,
      "\n  raw errors:",
      errors,
    );
    toast.error(t("addRecord.formHasErrors"));
  };

  const submitForm = form.handleSubmit(handleSubmit, handleInvalidSubmit);

  const onFormSubmit = async (e: React.BaseSyntheticEvent) => {
    if (isSubmittingRef.current) {
      e.preventDefault();
      return;
    }

    isSubmittingRef.current = true;
    try {
      await submitForm(e);
    } finally {
      isSubmittingRef.current = false;
    }
  };

  const renderSubmitLabel = (
    intent: RecordFormIntent,
    label: React.ReactNode,
  ) =>
    isLoading && intentRef.current === intent ? (
      <>
        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
        {t("userRecord.Submitting")}
      </>
    ) : (
      label
    );

  // Also add a direct error watcher as backup
  useEffect(() => {
    const subscription = form.watch(() => {
      // If we're watching for errors and an error occurs, trigger scroll
      if (shouldScrollToError && form.formState.errors) {
        const errors = form.formState.errors;
        if (Object.keys(errors).length > 0) {
          scrollToFirstError(errors);
        }
      }
    });

    return () => subscription.unsubscribe();
  }, [form, shouldScrollToError, scrollToFirstError]);
  const handleRefresh = async () => {
    try {
      setRefreshing(true);
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ["letterTemplates"] }),
        queryClient.invalidateQueries({ queryKey: ["headers-footers"] }),
        queryClient.invalidateQueries({ queryKey: ["prefixSuffix"] }),
        queryClient.invalidateQueries({ queryKey: ["settings"] }),
      ]);
      toast.success(t("msg.refreshedSuccess"));
    } catch {
      toast.error(t("msg.refreshFailed"));
    } finally {
      setRefreshing(false);
    }
  };

  const isFormLoading =
    isSettingsLoading ||
    isPrefixLoading ||
    isCCLoading ||
    isTemplateLoading ||
    refreshing ||
    isLoadingRecord;

  if (isFormLoading) {
    return <FullPageSpinner />;
  }
  return (
    <Form {...form}>
      {isLoading && (
        <div
          className="pointer-events-auto fixed inset-0 z-[100] flex items-center justify-center bg-white/80 backdrop-blur-sm dark:bg-gray-950/70"
          onClick={(e) => e.stopPropagation()}
        >
          <Card className="w-96 shadow-2xl border-0 dark:bg-gray-800 dark:border-gray-700">
            <CardContent className="p-8 flex flex-col items-center gap-4 dark:bg-gray-800">
              <div className="flex items-center gap-3">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                <span className="text-lg font-semibold dark:text-white">
                  {t("userRecord.Submitting")}
                </span>
              </div>
              <p className="text-muted-foreground dark:text-gray-400 text-center text-sm">
                {t("addRecord.processingRequest")}
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      <Button
        type="button"
        variant="default"
        onClick={handleOpenPreview}
        disabled={isLoading || isPreviewLoading}
        aria-label={t("preview.button")}
        className="fixed right-0 top-1/2 z-40 h-14 w-11 -translate-y-1/2 rounded-l-lg rounded-r-none bg-primary-700 px-0 text-white shadow-lg hover:bg-primary-800 disabled:opacity-60"
      >
        {isPreviewLoading ? (
          <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" />
        ) : (
          <div className="flex flex-col items-center gap-0.5">
            <ChevronLeft className="h-5 w-5" />
            <Eye className="h-4 w-4" />
          </div>
        )}
      </Button>

      <Sheet open={previewOpen} onOpenChange={setPreviewOpen}>
        <SheetContent
          side="right"
          className="w-[96vw] max-w-none gap-0 p-0 sm:max-w-[92vw]"
        >
          <SheetTitle className="sr-only">{t("preview.title")}</SheetTitle>
          {previewState && (
            <RecordPreviewPage
              isOpen={previewOpen}
              onClose={() => setPreviewOpen(false)}
              state={previewState}
              unitId={unitId as string}
              embedded
            />
          )}
        </SheetContent>
      </Sheet>

      <div className="min-h-screen bg-gradient-to-br from-primary-50 to-primary-50/30 dark:from-gray-900 dark:to-gray-800">
        <div className="max-w-7xl mx-auto px-4 py-8">
          {/* Header Section */}
          <Card className="mb-8 border-0 shadow-lg bg-gradient-to-r from-primary-800 to-primary-700 dark:from-primary-900 dark:to-primary-800 text-white">
            <CardContent className="p-8">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <div className="p-2 rounded-lg bg-white/10 backdrop-blur-sm">
                      <svg
                        className="w-6 h-6"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                        />
                      </svg>
                    </div>
                    <Badge
                      variant="secondary"
                      className="bg-white/20 text-white border-0"
                    >
                      {isEditMode
                        ? t("addRecord.Edit Mode")
                        : t("addRecord.Create Mode")}
                    </Badge>
                  </div>
                  <div>
                    <h1 className="text-3xl font-bold tracking-tight">
                      {isEditMode
                        ? t("addRecord.Edit Record")
                        : t("addRecord.Create New Record")}
                    </h1>
                    <p className="text-primary-300 mt-2 text-lg">
                      {t("addRecord.Fill in the details below")}
                    </p>
                  </div>
                </div>
                <div className="flex flex-wrap gap-3">
                  {canOpenCollaborationComments && (
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setCommentsDialogOpen(true)}
                      className="bg-white/10 hover:bg-white/20 border-white/20 text-white backdrop-blur-sm"
                    >
                      <MessageSquareText className="w-4 h-4 mr-2" />
                      {t("collaboration.comments", "Comments")}
                    </Button>
                  )}
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleRefresh}
                    className="bg-white/10 hover:bg-white/20 border-white/20 text-white backdrop-blur-sm"
                  >
                    <svg
                      className="w-4 h-4 mr-2"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                      />
                    </svg>
                    {t("Refresh Options")}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          <form onSubmit={onFormSubmit} className="space-y-8">
            {/* Basic Information Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Basic Information")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.enterBasicDetails")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="dark:bg-gray-800">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  <FormSelectField
                    control={form.control}
                    name="recordType"
                    label={t("addRecord.Record Type")}
                    options={recordTypeOptions}
                    placeholder={t("addRecord.Select Record Type")}
                    disabled={
                      (isFromCollaboration && !canCollaboratorsEditRecord) ||
                      isTeamRejectedEdit
                    }
                  />

                  <FormSelectField
                    control={form.control}
                    name="initiatedAs"
                    label={t("addRecord.Creation Type")}
                    options={creationType}
                    placeholder={t("addRecord.Select Creation Type")}
                    disabled={
                      (isFromCollaboration && !isTeamAdjustedEdit) ||
                      isTeamRejectedEdit
                    }
                  />

                  <FormSelectField
                    control={form.control}
                    name="initiationType"
                    label={t("addRecord.Initiation Type")}
                    options={filteredInitiationTypeOptions}
                    placeholder={t("addRecord.Select Initiation Type")}
                    disabled={
                      (isFromCollaboration && !isTeamAdjustedEdit) ||
                      isTeamRejectedEdit
                    }
                  />

                  {isEditMode && isLoadingRecord && (
                    <div className="space-y-1">
                      <FormLabel>
                        <span>
                          {t("addRecord.Preferred Language")}
                          <span className="text-destructive ml-1">*</span>
                        </span>
                      </FormLabel>
                      <Skeleton className="h-10 w-full rounded-md" />
                    </div>
                  )}
                  <div
                    className={isEditMode && isLoadingRecord ? "hidden" : ""}
                  >
                    <FormSelectField
                      control={form.control}
                      name="preferredLanguage"
                      label={t("addRecord.Preferred Language")}
                      options={[
                        { label: t("addRecord.English"), value: "en" },
                        { label: t("addRecord.Amharic"), value: "am" },
                      ]}
                      placeholder={t("Select Language")}
                      customLabel={
                        <FormLabel>
                          <span>
                            {t("addRecord.Preferred Language")}
                            <span className="text-destructive ml-1">*</span>
                          </span>
                        </FormLabel>
                      }
                    />
                  </div>

                  {(initiationType === "team" || isEditingExistingTeamRecord) &&
                    canShowTeamInitiation && (
                      <>
                        {isFromCollaboration ? (
                          <FormField
                            control={form.control}
                            name="collaborators"
                            render={({ field }) => {
                              const apiCollaborators =
                                fullApiResponse?.collaborators || [];
                              return (
                                <div className="space-y-2">
                                  <FormLabel>
                                    {t("addRecord.Collaborators")}
                                  </FormLabel>

                                  <div className="min-h-10 rounded-md border bg-muted px-3 py-2 text-sm text-muted-foreground">
                                    {apiCollaborators.length > 0
                                      ? apiCollaborators
                                          .map((collaborator: any) =>
                                            localizedFormName(
                                              collaborator.employeePosition
                                                ?.employee?.name,
                                            ),
                                          )
                                          .join(", ")
                                      : t("addRecord.No Collaborators")}
                                  </div>
                                </div>
                              );
                            }}
                          />
                        ) : (
                          <FormMultiSelectField
                            control={form.control}
                            name="collaborators"
                            label={t("addRecord.Collaborators")}
                            options={employeesList}
                            placeholder={t("addRecord.Select Collaborators")}
                            maxCount={5}
                            disabled={isTeamRejectedEdit}
                          />
                        )}
                        {!shouldCollaboratorAlwaysSign && (
                          <FormField
                            control={form.control}
                            name="isWithTeamSignature"
                            render={({ field }) => (
                              <FormItem className="flex items-center gap-4 pt-8">
                                <FormLabel className="text-sm font-medium">
                                  {t("addRecord.isTeamSig")}
                                </FormLabel>
                                <FormControl>
                                  <Switch
                                    checked={field.value}
                                    onCheckedChange={field.onChange}
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                        )}
                      </>
                    )}

                  <FormField
                    control={form.control}
                    name="subject"
                    render={({ field }) => (
                      <FormItem className="space-y-2">
                        <FormLabel>
                          <span>
                            {t("addRecord.Subject")}
                            <span className="text-destructive ml-1">*</span>
                          </span>
                        </FormLabel>
                        <FormControl>
                          <Input
                            placeholder={t("addRecord.Enter Subject")}
                            {...field}
                            className="focus:ring-2 focus:ring-primary-500"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="letterName"
                    render={({ field }) => (
                      <FormItem className="space-y-2">
                        <FormLabel>
                          <span>
                            {t("addRecord.letterName")}
                            <span className="text-destructive ml-1">*</span>
                          </span>
                        </FormLabel>
                        <FormControl>
                          <Input
                            placeholder={t("addRecord.addLetterName")}
                            {...field}
                            className="focus:ring-2 focus:ring-primary-500"
                            disabled={
                              isFromCollaboration && !canCollaboratorsEditRecord
                            }
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  {shouldShowReferenceNumberField && (
                    <FormField
                      control={form.control}
                      name="referenceNumber"
                      render={({ field }) => (
                        <FormItem className="space-y-2">
                          <FormLabel>
                            <span>{t("addRecord.Reference Number")}</span>
                          </FormLabel>
                          <FormControl>
                            <Input
                              placeholder={t(
                                "addRecord.Enter Reference Number",
                              )}
                              {...field}
                              className="focus:ring-2 focus:ring-green-500"
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Recipients Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Recipients")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.specifyRecipients")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="dark:bg-gray-800">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {isExternalLikeRecordType(recordTypeValue) ? (
                    <>
                      <div className="space-y-6 col-span-full">
                        <GroupedExternalReceiverBlock
                          form={form}
                          title={t("addRecord.Receiving Unit")}
                          fieldArrayName="ReceiversList"
                          prefixOptions={recordPrefixesResponse}
                          suffixOptions={recordSuffixesResponse}
                          treeLabel={t("addRecord.Receiving Unit")}
                          addableLabel={t("addRecord.Non Smart Receiving Unit")}
                          addablePlaceholder={t(
                            "addRecord.Enter Non Smart Receiving Organization",
                          )}
                          initialOptions={receivingOptions}
                          excludedIds={[
                            ...externalCC,
                            ...forYourReferenceUnitIds,
                          ]}
                          localizedName={localizedFormName}
                          prefixLabel={t("addRecord.Prefix")}
                          suffixLabel={t("addRecord.Suffix")}
                          prefixPlaceholder={t("addRecord.Select Prefix")}
                          suffixPlaceholder={t("addRecord.Select Suffix")}
                          addLabel={t("addRecord.Add")}
                          removeLabel={t("signatureUpload.remove")}
                        />
                      </div>
                    </>
                  ) : (
                    <>
                      <FormMultiSelectField
                        control={form.control}
                        name="toPositions"
                        label={t("addRecord.To Departments")}
                        options={listAllDepartmentResponse
                          .filter((unit) => {
                            const unitValue =
                              unit.id && unit.id.trim() !== ""
                                ? unit.id
                                : unit.key || "";
                            return !(
                              internalCC.includes(unitValue) ||
                              forYourReference.includes(unitValue)
                            );
                          })
                          .map((unit: OrganizationsPositions) => ({
                            label: localizedFormName(unit.name),
                            value:
                              unit.id && unit.id.trim() !== ""
                                ? unit.id
                                : unit.key || "",
                          }))}
                        placeholder={t("addRecord.Select Department")}
                        maxCount={5}
                      />
                      <FormMultiSelectField
                        control={form.control}
                        name="toEmployees"
                        label={t("addRecord.Receiving Users")}
                        options={employeesList}
                        placeholder={t("addRecord.Select Receiving Users")}
                        maxCount={5}
                      />
                    </>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Template & Formatting Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Template & Formatting")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.customizeAppearance")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="dark:bg-gray-800">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  <FormItem className="min-w-0 space-y-2">
                    <FormLabel>{t("addRecord.Letter Template")}</FormLabel>
                    <SingleSelect
                      onValueChange={(templateId) => {
                        if (templateId === "unselect") {
                          form.setValue("subject", "");
                          form.setValue("body", "");
                          form.setValue("sincerelyText", "", {
                            shouldDirty: true,
                            shouldValidate: true,
                          });
                          form.setValue("recordTemplateId", "", {
                            shouldDirty: true,
                            shouldValidate: true,
                          });
                        } else if (templateId && templateId.trim() !== "") {
                          const selectedTemplate = letterTemplates.find(
                            (t) => t.id === templateId,
                          );
                          if (selectedTemplate) {
                            form.setValue("subject", selectedTemplate.subject);
                            form.setValue("body", selectedTemplate.content);
                            form.setValue(
                              "sincerelyText",
                              selectedTemplate.sincerelyText ?? "",
                              {
                                shouldDirty: true,
                                shouldValidate: true,
                              },
                            );
                          }
                          form.setValue("recordTemplateId", templateId, {
                            shouldDirty: true,
                            shouldValidate: true,
                          });
                        }
                      }}
                      value={recordTemplateId || ""}
                      options={letterTemplateOptions}
                      placeholder={t("addRecord.Select Letter Template")}
                      className="focus:ring-2 focus:ring-primary-500"
                    />
                  </FormItem>

                  {shouldShowHeaderFooterSelection && (
                    <>
                      <FormSelectField
                        control={form.control}
                        name="headerId"
                        label={t("addRecord.Header")}
                        options={
                          effectiveHeaders?.length
                            ? effectiveHeaders.map((header) => ({
                                label: localizedName(header.name),
                                value: header.id,
                              }))
                            : [
                                {
                                  label: t("addRecord.No Header"),
                                  value: "none",
                                },
                              ]
                        }
                        placeholder={
                          effectiveHeaders?.length
                            ? t("addRecord.Select Header")
                            : t("addRecord.Loading Headers...")
                        }
                      />

                      <FormSelectField
                        control={form.control}
                        name="footerId"
                        label={t("addRecord.Footer")}
                        options={
                          effectiveFooters?.length
                            ? effectiveFooters.map((footer) => ({
                                label: localizedName(footer.name),
                                value: footer.id,
                              }))
                            : [
                                {
                                  label: t("addRecord.No Footer"),
                                  value: "none",
                                },
                              ]
                        }
                        placeholder={
                          effectiveFooters?.length
                            ? t("addRecord.Select Footer")
                            : t("addRecord.Loading Footers...")
                        }
                      />
                    </>
                  )}

                  <FormField
                    control={form.control}
                    name="sincerelyText"
                    render={({ field }) => (
                      <FormItem
                        className="space-y-2"
                        data-field="sincerelyText"
                      >
                        <FormLabel>{t("addRecord.Sincerely Text")}</FormLabel>
                        <FormControl>
                          <Input
                            placeholder={t("addRecord.Enter Sincerely Text")}
                            {...field}
                            className="focus:ring-2 focus:ring-primary-500"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Letter Content Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-orange-100 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Letter Content")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.writeLetterContent")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6 dark:bg-gray-800">
                {shouldShowHeaderFooterSelection && selectedHeader && (
                  <div className="bg-muted rounded-lg p-4 border-2 border-dashed border-muted-foreground/20">
                    <p className="text-sm font-medium text-muted-foreground mb-2">
                      {t("addRecord.Header Preview")}
                    </p>
                    <div dangerouslySetInnerHTML={{ __html: selectedHeader }} />
                  </div>
                )}
                <Card
                  ref={editorSectionRef}
                  className={`border-0 shadow-lg hover:shadow-xl transition-all duration-300 ${
                    lastErrorField === "body"
                      ? "ring-4 ring-destructive ring-offset-2"
                      : ""
                  }`}
                >
                  <FormField
                    control={form.control}
                    name="body"
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>
                          <span>
                            {t("addRecord.Body")}
                            <span className="text-destructive ml-1">*</span>
                          </span>
                        </FormLabel>
                        <RichTextEditor
                          value={field.value}
                          onChange={field.onChange}
                          shouldClear={shouldClearEditor}
                        />
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </Card>

                {shouldShowHeaderFooterSelection && selectedFooter && (
                  <div className="bg-muted rounded-lg p-4 border-2 border-dashed border-muted-foreground/20">
                    <p className="text-sm font-medium text-muted-foreground mb-2">
                      {t("addRecord.Footer Preview")}
                    </p>
                    <div dangerouslySetInnerHTML={{ __html: selectedFooter }} />
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Carbon Copy (CC) Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-cyan-100 dark:bg-cyan-900/30 text-cyan-600 dark:text-cyan-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Carbon Copy (CC)")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.addCCRecipients")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="dark:bg-gray-800">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  <FormMultiSelectField
                    control={form.control}
                    name="internalCC"
                    label={t("addRecord.Internal CC")}
                    options={listAllDepartmentResponse
                      .filter((unit) => {
                        const unitValue =
                          unit.id && unit.id.trim() !== ""
                            ? unit.id
                            : unit.key || "";
                        return !(
                          toPositions.includes(unitValue) ||
                          forYourReference.includes(unitValue)
                        );
                      })
                      .map((unit: OrganizationsPositions) => ({
                        label: localizedFormName(unit.name),
                        value:
                          unit.id && unit.id.trim() !== ""
                            ? unit.id
                            : unit.key || "",
                      }))}
                    placeholder={t("addRecord.Select Internal CC")}
                    maxCount={5}
                  />

                  <div data-field="ccEmployees">
                    <FormMultiSelectField
                      control={form.control}
                      name="ccEmployees"
                      label={t("addRecord.ccUsers")}
                      options={ccEmployeeOptions}
                      placeholder={t("addRecord.selectCCUsers")}
                      maxCount={5}
                      onCustomChange={validateCcEmployeesSelection}
                    />
                  </div>
                  <>
                    {" "}
                    {recordTypeValue !== "internal_memo" &&
                      recordTypeValue !== "direct" && (
                        <div className="space-y-6 col-span-full">
                          <GroupedExternalReceiverBlock
                            form={form}
                            title={t("nav.cc")}
                            fieldArrayName="ccList"
                            prefixOptions={ccPrefixesResponse}
                            suffixOptions={ccSuffixesResponse}
                            treeLabel={t("addRecord.External CC")}
                            addableLabel={t("addRecord.Non Smart CC Unit")}
                            addablePlaceholder={t(
                              "addRecord.Enter Non Smart CC Organization",
                            )}
                            initialOptions={ccReceivingOptions}
                            excludedIds={[
                              ...receivingUnitIds,
                              ...forYourReferenceUnitIds,
                            ]}
                            localizedName={localizedFormName}
                            prefixLabel={t("addRecord.Prefix")}
                            suffixLabel={t("addRecord.Suffix")}
                            prefixPlaceholder={t("addRecord.Select Prefix")}
                            suffixPlaceholder={t("addRecord.Select Suffix")}
                            addLabel={t("addRecord.Add")}
                            removeLabel={t("signatureUpload.remove")}
                          />
                        </div>
                      )}
                  </>
                  {shouldIncludeForYourReferenceInCC && (
                    <div className="space-y-6 col-span-full">
                      <GroupedExternalReceiverBlock
                        form={form}
                        title={t("addRecord.forYourReferenceExternal")}
                        fieldArrayName="forYourReferenceList"
                        prefixOptions={ccPrefixesResponse}
                        suffixOptions={ccSuffixesResponse}
                        treeLabel={t("addRecord.forYourReferenceExternal")}
                        addableLabel={t("addRecord.Non Smart FYR Unit")}
                        addablePlaceholder={t(
                          "addRecord.Enter Non Smart FYR Organization",
                        )}
                        initialOptions={fyrReceivingOptions}
                        excludedIds={[...receivingUnitIds, ...externalCC]}
                        localizedName={localizedFormName}
                        prefixLabel={t("addRecord.Prefix")}
                        suffixLabel={t("addRecord.Suffix")}
                        prefixPlaceholder={t("addRecord.Select Prefix")}
                        suffixPlaceholder={t("addRecord.Select Suffix")}
                        addLabel={t("addRecord.Add")}
                        removeLabel={t("signatureUpload.remove")}
                      />
                    </div>
                  )}
                  {/* For Your Reference (Internal) */}
                  {shouldIncludeForYourReferenceInCC && (
                    <FormMultiSelectField
                      control={form.control}
                      name="forYourReference"
                      label={t("addRecord.forYourReferenceInternal")}
                      options={listAllDepartmentResponse
                        .filter((unit) => {
                          const unitValue =
                            unit.id && unit.id.trim() !== ""
                              ? unit.id
                              : unit.key || "";
                          return !(
                            toPositions.includes(unitValue) ||
                            internalCC.includes(unitValue)
                          );
                        })
                        .map((unit: OrganizationsPositions) => ({
                          label: localizedFormName(unit.name),
                          value:
                            unit.id && unit.id.trim() !== ""
                              ? unit.id
                              : unit.key || "",
                        }))}
                      placeholder={t("addRecord.selectForYourReference")}
                      maxCount={5}
                    />
                  )}

                  {shouldShowCanSkipLevel && (
                    <FormField
                      control={form.control}
                      name="skipOneLevel"
                      render={({ field }) => (
                        <FormItem className="flex min-h-10 items-center justify-between gap-4 rounded-md border px-3 py-2 dark:border-gray-700">
                          <FormLabel className="text-sm font-medium">
                            {t(
                              "addRecord.skipOneLevel",
                              "Should Jump One Step",
                            )}
                          </FormLabel>
                          <FormControl>
                            <Switch
                              checked={field.value ?? false}
                              onCheckedChange={field.onChange}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Attachments Section */}
            <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 dark:bg-gray-800 dark:border-gray-700">
              <CardHeader className="pb-4 dark:bg-gray-800">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400">
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
                      />
                    </svg>
                  </div>
                  <div>
                    <CardTitle className="text-xl dark:text-white">
                      {t("addRecord.Attachments")}
                    </CardTitle>
                    <CardDescription className="dark:text-gray-400">
                      {t("addRecord.uploadSupportingDocuments")}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6 dark:bg-gray-800">
                <p className="text-muted-foreground text-sm">
                  {t("addRecord.attachment")}
                </p>

                {form.getValues("mode") === "edit" &&
                  existingAttachmentComponent &&
                  existingAttachmentComponent}

                {/* Action buttons row */}
                {tenantConfig?.moduleConfig?.dms && (
                  <div className="flex flex-wrap gap-4 mb-4">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleLocalUploadClick}
                      className="flex items-center gap-2 border-2 hover:bg-primary-100 dark:hover:bg-gray-700 dark:border-gray-600 dark:text-gray-200 transition-all duration-200"
                    >
                      <Upload className="h-4 w-4" />
                      {t("addRecord.uploadFromComputer") ||
                        "Upload from Computer"}
                    </Button>
                    {canUseAttachmentFromDMS && (
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => setIsDmsPickerOpen(true)}
                        className="flex items-center gap-2 border-2 hover:bg-primary-100 dark:hover:bg-gray-700 dark:border-gray-600 dark:text-gray-200 transition-all duration-200"
                      >
                        <Cloud className="h-4 w-4" />
                        {t("addRecord.addAttachmentFromDms") ||
                          "+ Add Attachment from DMS"}
                      </Button>
                    )}
                    <input
                      type="file"
                      ref={localFileInputRef}
                      className="hidden"
                      multiple
                      onChange={handleLocalFileChange}
                    />
                  </div>
                )}

                <ReusableFileUploader
                  setFiles={setFiles}
                  files={files}
                  isLoading={false}
                />

                {/* DMS attachments list */}
                {canUseAttachmentFromDMS &&
                  dmsAttachments &&
                  dmsAttachments.length > 0 && (
                    <div className="flex flex-col gap-4 mt-4 max-h-48 overflow-y-auto px-3">
                      {dmsAttachments.map((doc) => (
                        <DmsAttachmentItem
                          key={doc.id}
                          doc={doc}
                          onRemove={() => handleRemoveDmsAttachment(doc.id)}
                        />
                      ))}
                    </div>
                  )}

                {canUseAttachmentFromDMS && (
                  <DmsFilePickerModal
                    isOpen={isDmsPickerOpen}
                    onClose={() => setIsDmsPickerOpen(false)}
                    onAttach={handleAttachDmsDocs}
                  />
                )}
              </CardContent>
            </Card>

            {/* Action Buttons */}
            <Card className="border-0 shadow-lg bg-gradient-to-r from-primary-50 to-primary-50/50 dark:from-gray-800 dark:to-gray-700 dark:border-gray-700">
              <CardContent className="p-6 dark:bg-transparent">
                <div className="flex flex-col sm:flex-row gap-4 justify-end">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      const currentDefaults = getFormDefaultValues();
                      form.reset(currentDefaults);
                      if (currentDefaults.ccList) {
                        replaceCcList(currentDefaults.ccList);
                      }
                      if (currentDefaults.ReceiversList) {
                        replaceReceiversList(currentDefaults.ReceiversList);
                      }
                      if (currentDefaults.forYourReferenceList) {
                        replaceForYourReferenceList(
                          currentDefaults.forYourReferenceList,
                        );
                      }
                      if (window.history.length > 1) {
                        navigate(-1);
                      } else {
                        navigate(fallbackReturnUrl);
                      }
                    }}
                    className="px-8 border-2 hover:bg-primary-100 dark:hover:bg-gray-700 dark:border-gray-600 dark:text-gray-200 transition-all duration-200"
                  >
                    {t("common.Cancel")}
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleOpenPreview}
                    disabled={isLoading || isPreviewLoading}
                    className="px-8 border-2 border-primary-200 bg-primary-50 text-primary-700 hover:bg-primary-100 hover:text-primary-800 dark:border-primary-800 dark:bg-primary-900/40 dark:text-primary-400 dark:hover:bg-primary-900/60 dark:hover:text-primary-300 transition-all duration-200"
                  >
                    <svg
                      className="w-4 h-4 mr-2"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                      />
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                      />
                    </svg>
                    {isPreviewLoading
                      ? t("preview.generating")
                      : t("preview.button")}
                  </Button>
                  {(!isFromCollaboration || canEditWhileCollaborating) && (
                    <Button
                      type="submit"
                      disabled={isLoading}
                      onClick={() => {
                        intentRef.current = "draft";
                      }}
                      className="px-8 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white shadow-lg hover:shadow-xl dark:from-primary-700 dark:to-primary-800 dark:hover:from-primary-600 dark:hover:to-primary-700 transition-all duration-200"
                    >
                      {renderSubmitLabel("draft", t("common.saveAsDraft"))}
                    </Button>
                  )}
                  {!isCurrentRecordDirect &&
                    (!isFromCollaboration || canEditWhileCollaborating) &&
                    hasParent && (
                      <Button
                        type="submit"
                        disabled={isLoading}
                        onClick={() => {
                          intentRef.current = "forward";
                        }}
                        className="px-8 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white shadow-lg hover:shadow-xl dark:from-blue-700 dark:to-blue-800 dark:hover:from-blue-600 dark:hover:to-blue-700 transition-all duration-200"
                      >
                        {renderSubmitLabel(
                          "forward",
                          isEditMode
                            ? t("userRecord.updateAndForward")
                            : t("userRecord.createAndForward"),
                        )}
                      </Button>
                    )}
                  {!isFromCollaboration && recordTypeValue === "direct" && (
                    <Button
                      type="submit"
                      disabled={isLoading}
                      onClick={() => {
                        intentRef.current = "direct";
                      }}
                      className="px-8 bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white shadow-lg hover:shadow-xl dark:from-amber-600 dark:to-amber-700 dark:hover:from-amber-500 dark:hover:to-amber-600 transition-all duration-200"
                    >
                      {isEditMode
                        ? t("userRecord.updateAndSend")
                        : t("userRecord.createAndSend")}
                    </Button>
                  )}
                  {canApprove &&
                    isExternalLikeRecordType(recordTypeValue) &&
                    !isCurrentRecordDirect &&
                    !isFromCollaboration &&
                    !(initiationType === "team") && (
                      <Button
                        type="submit"
                        disabled={isLoading}
                        onClick={() => {
                          intentRef.current = "approve";
                        }}
                        className="px-8 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white shadow-lg hover:shadow-xl dark:from-purple-700 dark:to-purple-800 dark:hover:from-purple-600 dark:hover:to-purple-700 transition-all duration-200"
                      >
                        {renderSubmitLabel(
                          "approve",
                          isEditMode
                            ? t("userRecord.updateAndApprove")
                            : t("userRecord.createAndApprove"),
                        )}
                      </Button>
                    )}
                  {canapproveinternal &&
                    recordTypeValue === "internal" &&
                    !isCurrentRecordDirect &&
                    !isFromCollaboration &&
                    !(initiationType === "team") && (
                      <Button
                        type="submit"
                        disabled={isLoading}
                        onClick={() => {
                          intentRef.current = "approve";
                        }}
                        className="px-8 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white shadow-lg hover:shadow-xl dark:from-purple-700 dark:to-purple-800 dark:hover:from-purple-600 dark:hover:to-purple-700 transition-all duration-200"
                      >
                        {renderSubmitLabel(
                          "approve",
                          isEditMode
                            ? t("userRecord.updateAndApprove")
                            : t("userRecord.createAndApprove"),
                        )}
                      </Button>
                    )}
                  {canapproveinternalMemo &&
                    recordTypeValue === "internal_memo" &&
                    !isCurrentRecordDirect &&
                    !isFromCollaboration &&
                    !(initiationType === "team") && (
                      <Button
                        type="submit"
                        disabled={isLoading}
                        onClick={() => {
                          intentRef.current = "approve";
                        }}
                        className="px-8 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white shadow-lg hover:shadow-xl dark:from-purple-700 dark:to-purple-800 dark:hover:from-purple-600 dark:hover:to-purple-700 transition-all duration-200"
                      >
                        {renderSubmitLabel(
                          "approve",
                          isEditMode
                            ? t("userRecord.updateAndApprove")
                            : t("userRecord.createAndApprove"),
                        )}
                      </Button>
                    )}
                </div>
              </CardContent>
            </Card>
          </form>

          {canOpenCollaborationComments && effectiveRecordId && (
            <CollaborationCommentsDialog
              open={commentsDialogOpen}
              onClose={() => setCommentsDialogOpen(false)}
              recordId={effectiveRecordId}
              contentId={currentContentId}
              collaborationId={currentUserCollaborationId}
              recordStatus={""}
            />
          )}
        </div>
      </div>
    </Form>
  );
};

export default RecordForm;
