"use client";

import { useEffect, useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { FileText, Hash, User, Building2, Upload, Cloud } from "lucide-react";
import { DmsFilePickerModal } from "@/record-management/components/userRecords/common/DmsFilePickerModal";
import { DmsAttachmentItem } from "@/record-management/components/userRecords/common/DmsAttachmentItem";

import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import {
  sendLetterSchema,
  defaultSendLetterValues,
  type SendLetterFormValues,
} from "./Form-Schema";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/shared/common/ui/form";
import { ReusableFileUploader } from "@/shared/common/ui/fileUploader/reusableFileUploader";
import {
  useIncomings,
  useUpdateIncoming,
} from "@/record-management/components/hooks/useIncomingRecords";

import { toast } from "sonner";
import { t } from "i18next";
import { useQueryClient } from "@tanstack/react-query";
import { RadioGroup, RadioGroupItem } from "@/shared/common/ui/radio-group";
import { Label } from "@/shared/common/ui/label";

import {
  STORAGE_UPLOAD_ERROR_CODE,
  STORAGE_UPLOAD_TOO_LARGE,
  UploadKeyResponse,
  uploadMultiple,
  uploadSingle,
} from "@/record-management/services/api/newFileService";

import {
  AttachmentInfo,
  FileInfo as RecordFileInfo,
  RecordAttachmentDto,
} from "@/record-management/dto/userRecords/userRecordsDto";
import { fetchRecordById } from "@/record-management/services/api/userRecordService";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { Spinner } from "@/shared/common/ui/sppiner";
import { useNonSmartRecordPdfAssign } from "@/record-management/components/hooks/useNonSmartRecordPdfAssign";
import AssignIncomingRecordModal from "./AssignIncomingRecordModal";

interface AddIncomingRecordFormProps {
  editingId?: string;
  onSuccess?: () => void;
  onCancel?: (error: unknown) => void;
}

const AddIncomingRecordForm = ({
  editingId,
  onSuccess,
  onCancel,
}: AddIncomingRecordFormProps) => {
  const form = useForm<SendLetterFormValues>({
    resolver: zodResolver(sendLetterSchema),
    defaultValues: {
      ...defaultSendLetterValues,
      receiverPositions: [],
      receiverEmployeePositions: [],
    },
  });

  const queryClient = useQueryClient();
  const [files, setFiles] = useState<File[]>([]);
  const [dmsAttachments, setDmsAttachments] = useState<any[]>([]);
  const [isDmsPickerOpen, setIsDmsPickerOpen] = useState(false);
  const localFileInputRef = useRef<HTMLInputElement>(null);

  const handleLocalUploadClick = () => {
    localFileInputRef.current?.click();
  };

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

  const handleAttachDmsDocs = (docs: any[]) => {
    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) => {
    setDmsAttachments((prev) => prev.filter((x) => x.id !== id));
  };

  const { sendLetterAndUploadFile, isSending, isUploading } = useIncomings();
  const { updateIncomingRecord, isUpdating } = useUpdateIncoming();
  const { handleError } = useErrorHandler(t);
  const [mainFileIndex, setMainFileIndex] = useState<number | null>(null);
  const [mainFileError, setMainFileError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [existingFileInfo, setExistingFileInfo] =
    useState<RecordFileInfo | null>(null);
  const [existingAttachments, setExistingAttachments] = useState<
    AttachmentInfo[]
  >([]);
  const [replaceMainFile, setReplaceMainFile] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [pendingFormData, setPendingFormData] =
    useState<SendLetterFormValues | null>(null);
  const [isCreateAndAssign, setIsCreateAndAssign] = useState(false);
  const lang = localStorage.getItem("i18nextLng") || "am"; // Default to Amharic if not set
  const {
    createAndAssign,
    isCreating,
    updateAndAssign,
    isUpdating: isAssigning,
  } = useNonSmartRecordPdfAssign();
  const isLoading =
    isSending ||
    isUploading ||
    isUpdating ||
    isSubmitting ||
    isCreating ||
    isAssigning;

  useEffect(() => {
    if (files.length > 0 && mainFileIndex === null && !editingId) {
      setMainFileIndex(0); // Set first file as default main file
      setMainFileError("");
    }
  }, [files, mainFileIndex, editingId]);

  useEffect(() => {
    if (!editingId) return;

    const loadExistingRecord = async () => {
      try {
        const record = await fetchRecordById(editingId);
        const content = record.content?.[0];

        setExistingFileInfo(record.fileInfo ?? null);
        setExistingAttachments(
          (content?.recordAttachments ?? []).map(
            (attachment: RecordAttachmentDto) => ({
              fileInfo: {
                fileName: attachment.fileInfo.fileName,
                contentType: attachment.fileInfo.contentType,
                originalname: attachment.fileInfo.originalname,
                size: attachment.fileInfo.size ?? 0,
                bucket: attachment.fileInfo.bucket ?? "",
              },
              name: {
                am:
                  attachment.fileInfo.originalname ||
                  attachment.fileInfo.fileName,
                en:
                  attachment.fileInfo.originalname ||
                  attachment.fileInfo.fileName,
              },
            }),
          ),
        );
      } catch (error) {
        await handleError(error);
      }
    };

    loadExistingRecord();
  }, [editingId, handleError]);

  useEffect(() => {
    if (!editingId || !replaceMainFile) {
      setMainFileError("");
      return;
    }

    if (files.length === 0) {
      setReplaceMainFile(false);
      setMainFileIndex(null);
      return;
    }

    if (mainFileIndex === null) {
      setMainFileIndex(0);
    }
  }, [editingId, replaceMainFile, files, mainFileIndex]);

  const handleAssignmentSuccess = async (assignmentData: any) => {
    if (!pendingFormData) return;

    try {
      const selectedMainFile =
        mainFileIndex !== null ? files[mainFileIndex] : null;

      // Upload files
      let fileInfos: UploadKeyResponse["fileInfo"][] = [];
      try {
        if (files.length > 1) {
          fileInfos = await uploadMultiple(files);
        } else if (files.length === 1) {
          const fileInfo = await uploadSingle(files[0]);
          fileInfos = [fileInfo];
        }
      } catch (uploadError) {
        if (
          uploadError instanceof Error &&
          uploadError.message === STORAGE_UPLOAD_TOO_LARGE
        ) {
          toast.error(t("userRecord.storageUploadFailed"), {
            description: t("msg.fileTooLarge"),
          });
        } else if (
          uploadError instanceof Error &&
          uploadError.message === STORAGE_UPLOAD_ERROR_CODE
        ) {
          toast.error(t("userRecord.storageUploadFailed"));
        } else {
          await handleError(uploadError);
        }
        return;
      }
      const uploadedFiles: AttachmentInfo[] = fileInfos.map((f) => ({
        fileInfo: {
          bucket: f.bucket,
          fileName: f.fileName,
          contentType: f.contentType,
          originalname: f.originalname,
          size: f.size,
        },
        name: {
          am: f.originalname,
          en: f.originalname,
        },
      }));

      const newMainFile =
        replaceMainFile && mainFileIndex !== null
          ? (uploadedFiles[mainFileIndex]?.fileInfo ?? null)
          : null;
      const newUploadedAttachments = uploadedFiles.filter((_, index) =>
        editingId
          ? !replaceMainFile || index !== mainFileIndex
          : index !== mainFileIndex,
      );
      // convert DMS documents → AttachmentInfo
      const dmsUploadedFiles: AttachmentInfo[] = dmsAttachments.map((doc) => ({
        fileInfo: {
          bucket: doc.fileInfo?.bucket || "",
          fileName: doc.fileInfo?.fileName || "",
          contentType: doc.fileInfo?.contentType || "",
          size: doc.fileInfo?.size || 0,
          originalname:
            doc.fileInfo?.originalname ||
            (typeof doc.name === "object"
              ? doc.name?.en || doc.name?.am
              : doc.name) ||
            "document",
        },
        name: {
          am:
            (typeof doc.name === "object"
              ? doc.name?.am || doc.name?.en
              : doc.name) || "document",
          en:
            (typeof doc.name === "object"
              ? doc.name?.en || doc.name?.am
              : doc.name) || "document",
        },
      }));

      const finalFileInfo =
        newMainFile ??
        (editingId
          ? existingFileInfo
          : uploadedFiles[mainFileIndex ?? 0]?.fileInfo);
      const finalAttachments = editingId
        ? [
            ...existingAttachments,
            ...newUploadedAttachments,
            ...dmsUploadedFiles,
          ]
        : [...newUploadedAttachments, ...dmsUploadedFiles];

      if (!finalFileInfo) {
        throw new Error("Main file information is required");
      }

      // Build payload for API
      const selectedEmployees = assignmentData.assignedEmployees;
      const employeePositionIds = selectedEmployees;

      const payload = {
        uploadDto: {
          fileInfo: {
            fileName: finalFileInfo.fileName,
            contentType: finalFileInfo.contentType,
            size: finalFileInfo.size ?? 0,
            originalname: finalFileInfo.originalname,
            bucket: finalFileInfo.bucket ?? "",
          },
          subject: pendingFormData.subject,
          receiverPositions: assignmentData.receivingDepartments,
          receiverEmployeePositions: employeePositionIds,
          letterNumber: pendingFormData.letterNumber,
          organizationName: pendingFormData.organizationName,
          deliveredBy: pendingFormData.deliveredBy,
          preferredLanguage: pendingFormData.preferredLanguage || lang || "am",
          letterName: pendingFormData.letterName,
          attachments: finalAttachments.map((att) => ({
            fileInfo: {
              fileName: att.fileInfo.fileName,
              contentType: att.fileInfo.contentType,
              size: att.fileInfo.size,
              originalname: att.fileInfo.originalname,
            },
            name: att.name,
          })),
        },
        assignDto: {
          recordBoxId: null,
          recordId: editingId || null,
          employeePositionIds,
          positionIds: assignmentData.receivingDepartments,
          comment: assignmentData.remarks,
        },
      };

      if (isCreateAndAssign) {
        try {
          await createAndAssign(payload);
          form.reset({
            ...defaultSendLetterValues,
            receiverPositions: [],
            receiverEmployeePositions: [],
          });
          setFiles([]);
          setDmsAttachments([]);
          setMainFileIndex(null);
          setShowAssignModal(false);
          setPendingFormData(null);
          setIsCreateAndAssign(false);

          queryClient.invalidateQueries({
            queryKey: ["external-record-incoming"],
          });

          toast.success(t("incomingRecord.createdAndAssignedSuccess"));
          onSuccess?.();
        } catch (error) {
          await handleError(error);
        }
      } else if (editingId) {
        try {
          await updateAndAssign({ id: editingId, payload });
          form.reset({
            ...defaultSendLetterValues,
            receiverPositions: [],
            receiverEmployeePositions: [],
          });
          setFiles([]);
          setDmsAttachments([]);
          setMainFileIndex(null);
          setShowAssignModal(false);
          setPendingFormData(null);

          queryClient.invalidateQueries({
            queryKey: ["external-record-incoming"],
          });

          toast.success(t("incomingRecord.updatedAndAssignedSuccess"));
          onSuccess?.();
        } catch (error) {
          await handleError(error);
        }
      }
    } catch (error) {
      console.error("Error during assignment:", error);
      await handleError(error);
    }
  };

  const onSubmit = async (values: SendLetterFormValues) => {
    if (!editingId && files.length === 0) {
      toast.error(t("userRecord.Please select file"));
      return;
    }

    if (!editingId && mainFileIndex === null) {
      toast.error(t("userRecord.Please select a main file"));
      setMainFileError(t("userRecord.Please select a main file"));
      return;
    }

    if (editingId && replaceMainFile && mainFileIndex === null) {
      toast.error(t("userRecord.Please select a main file"));
      setMainFileError(t("userRecord.Please select a main file"));
      return;
    }
    setMainFileError("");

    setIsSubmitting(true);

    try {
      const selectedMainFile =
        mainFileIndex !== null ? files[mainFileIndex] : null;

      // Check if replacement main file is PDF
      if (
        selectedMainFile &&
        (!editingId || replaceMainFile) &&
        selectedMainFile.type !== "application/pdf"
      ) {
        toast.error(t("userRecord.The main file must be a PDF document"));
        setMainFileError(t("userRecord.The main file must be a PDF document"));
        return;
      }

      // =========================
      // 1. UPLOAD FILES (NEW LOGIC)
      // =========================
      let fileInfos: UploadKeyResponse["fileInfo"][] = [];

      try {
        if (files.length > 1) {
          fileInfos = await uploadMultiple(files);
        } else if (files.length === 1) {
          const fileInfo = await uploadSingle(files[0]);
          fileInfos = [fileInfo];
        }
      } catch (uploadError) {
        if (
          uploadError instanceof Error &&
          uploadError.message === STORAGE_UPLOAD_TOO_LARGE
        ) {
          toast.error(t("userRecord.storageUploadFailed"), {
            description: t("msg.fileTooLarge"),
          });
        } else if (
          uploadError instanceof Error &&
          uploadError.message === STORAGE_UPLOAD_ERROR_CODE
        ) {
          toast.error(t("userRecord.storageUploadFailed"));
        } else {
          await handleError(uploadError);
        }
        setIsSubmitting(false);
        return; // Exit early but keep form intact
      }

      // Convert fileInfo → AttachmentInfo
      const uploadedFiles: AttachmentInfo[] = fileInfos.map((f) => ({
        fileInfo: {
          bucket: f.bucket,
          fileName: f.fileName,
          contentType: f.contentType,
          originalname: f.originalname,
          size: f.size,
        },
        name: {
          am: f.originalname,
          en: f.originalname,
        },
      }));
      const newMainFile =
        replaceMainFile && mainFileIndex !== null
          ? (uploadedFiles[mainFileIndex]?.fileInfo ?? null)
          : null;
      const newUploadedAttachments = uploadedFiles.filter((_, index) =>
        editingId
          ? !replaceMainFile || index !== mainFileIndex
          : index !== mainFileIndex,
      );
      // convert DMS documents → AttachmentInfo
      const dmsUploadedFiles: AttachmentInfo[] = dmsAttachments.map((doc) => ({
        fileInfo: {
          bucket: doc.fileInfo?.bucket || "",
          fileName: doc.fileInfo?.fileName || "",
          contentType: doc.fileInfo?.contentType || "",
          size: doc.fileInfo?.size || 0,
          originalname:
            doc.fileInfo?.originalname ||
            (typeof doc.name === "object"
              ? doc.name?.en || doc.name?.am
              : doc.name) ||
            "document",
        },
        name: {
          am:
            (typeof doc.name === "object"
              ? doc.name?.am || doc.name?.en
              : doc.name) || "document",
          en:
            (typeof doc.name === "object"
              ? doc.name?.en || doc.name?.am
              : doc.name) || "document",
        },
      }));

      const finalFileInfo =
        newMainFile ??
        (editingId
          ? existingFileInfo
          : uploadedFiles[mainFileIndex ?? 0]?.fileInfo);
      const finalAttachments = editingId
        ? [
            ...existingAttachments,
            ...newUploadedAttachments,
            ...dmsUploadedFiles,
          ]
        : [...newUploadedAttachments, ...dmsUploadedFiles];

      if (!finalFileInfo) {
        throw new Error("Main file information is required");
      }

      // =========================
      // 2. BUILD PAYLOAD
      // =========================
      const payload = {
        ...values,
        fileInfo: finalFileInfo,
        attachments: finalAttachments,
        receiverPositions: [],
        receiverEmployeePositions: [],
      };

      // =========================
      // 3. CREATE RECORD
      // =========================

      try {
        if (editingId) {
          await updateIncomingRecord(payload, editingId);
        } else {
          if (!selectedMainFile) {
            throw new Error("Main file is required");
          }
          await sendLetterAndUploadFile(
            {
              ...payload,
              fileInfo: {
                fileName: finalFileInfo.fileName,
                contentType: finalFileInfo.contentType,
                originalname: finalFileInfo.originalname,
                size: finalFileInfo.size ?? 0,
              },
            },
            selectedMainFile,
          );
        }
      } catch (recordError) {
        await handleError(recordError);
        setIsSubmitting(false);
        return; // Exit early but keep form intact
      }

      form.reset({
        ...defaultSendLetterValues,
        receiverPositions: [],
        receiverEmployeePositions: [],
      });

      setFiles([]);
      setDmsAttachments([]);
      setMainFileIndex(null);
      await queryClient.invalidateQueries({
        queryKey: ["external-record-incoming"],
      });

      toast.success(
        editingId
          ? t("incomingRecord.updatedSuccess")
          : t("incomingRecord.createdSuccess"),
      );
      onSuccess?.();
    } catch (error) {
      console.error("Unexpected error in form submission:", error);

      const handledMessage = await handleError(error);
      if (!handledMessage?.trim()) {
        toast.error(t("userRecord.An unexpected error occurred"));
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  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()}>
          <div className="flex flex-col items-center gap-3 rounded-xl bg-white p-6 shadow-lg dark:bg-gray-900 dark:shadow-2xl dark:shadow-black/40">
            <Spinner size="large" />
            <p className="text-sm text-gray-600 dark:text-gray-300">
              {t("userIncoming.Processing...")}
            </p>
          </div>
        </div>
      )}
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="mx-auto max-w-2xl space-y-8 rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-900"
        aria-labelledby="form-title">
        <div className="border-b border-gray-200 pb-4 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-primary-50 p-2 dark:bg-primary-900/30">
              <FileText className="h-6 w-6 text-primary-600 dark:text-primary-400" />
            </div>
            <div>
              <h2
                id="form-title"
                className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                {editingId
                  ? t("userRecord.Edit Record")
                  : t("userRecord.Add Record")}
              </h2>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                {editingId
                  ? t("msg.updateRecordMsg")
                  : t("msg.createRecordMsg")}
              </p>
            </div>
          </div>
        </div>

        <div className="space-y-6">
          <div className="space-y-4">
            <h3 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-gray-700 dark:text-gray-200">
              <FileText className="h-4 w-4 text-primary-600 dark:text-primary-400" />
              {t("addRecord.letterInformation")}
            </h3>

            <FormField
              control={form.control}
              name="subject"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-700 dark:text-gray-200">
                    {t("userIncoming.Subject")}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t("userIncoming.Subject")}
                      {...field}
                      disabled={isLoading}
                      className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="letterNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex items-center gap-1 text-gray-700 dark:text-gray-200">
                      <Hash className="h-3 w-3" />
                      {t("userRecord.Letter Number")}
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("userRecord.Letter Number")}
                        {...field}
                        disabled={isLoading}
                        className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="letterName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-gray-700 dark:text-gray-200">
                      {t("viewDetail.fileName1")}
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("viewDetail.fileName1")}
                        {...field}
                        disabled={isLoading}
                        className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="deliveredBy"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1 text-gray-700 dark:text-gray-200">
                    <User className="h-3 w-3" />
                    {t("userRecord.Delivered By")}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t("userRecord.Delivered By")}
                      {...field}
                      disabled={isLoading}
                      className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="space-y-4 border-t border-gray-200 pt-4 dark:border-gray-700">
            <h3 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-gray-700 dark:text-gray-200">
              <Building2 className="h-4 w-4 text-primary-600 dark:text-primary-400" />
              {t("addRecord.organizationInformation")}
            </h3>

            <FormField
              control={form.control}
              name="organizationName.am"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-700 dark:text-gray-200">
                    {t("userIncoming.Sending Organization (Amharic)")}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t(
                        "userIncoming.Sending Organization (Amharic)",
                      )}
                      {...field}
                      disabled={isLoading}
                      className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="organizationName.en"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-gray-700 dark:text-gray-200">
                    {t("userIncoming.Sending Organization (English)")}
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t(
                        "userIncoming.Sending Organization (English)",
                      )}
                      {...field}
                      disabled={isLoading}
                      className="border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:placeholder:text-gray-400 dark:focus:border-primary-400 dark:focus:ring-primary-400"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="space-y-4 border-t border-gray-200 pt-4 dark:border-gray-700">
            <h3 className="text-sm font-semibold uppercase tracking-wide text-gray-700 dark:text-gray-200">
              {t("Document Attachments")}
            </h3>
            {editingId && existingFileInfo && (
              <div className="rounded-lg border border-primary-200 bg-primary-50 p-4 text-sm text-gray-700 dark:border-primary-700/40 dark:bg-primary-900/20 dark:text-gray-200">
                <p className="font-medium text-gray-900 dark:text-gray-100">
                  {t("viewDetail.letter")}:
                </p>
                <p>
                  {existingFileInfo.originalname || existingFileInfo.fileName}
                </p>
                {existingAttachments.length > 0 && (
                  <p className="mt-2 text-gray-600 dark:text-gray-400">
                    {existingAttachments.length} existing attachment
                    {existingAttachments.length > 1 ? "s" : ""} will be kept
                    unless removed separately.
                  </p>
                )}
              </div>
            )}
            <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/60">
              {/* Action buttons row */}
              <div className="flex flex-wrap gap-4 mb-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleLocalUploadClick}
                  className="flex items-center gap-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">
                  <Upload className="h-4 w-4" />
                  {t("addRecord.uploadFromComputer") || "Upload from Computer"}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsDmsPickerOpen(true)}
                  className="flex items-center gap-2 border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">
                  <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
                files={files}
                setFiles={setFiles}
                isLoading={isLoading}
              />

              {/* DMS attachments list */}
              {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>
              )}

              <DmsFilePickerModal
                isOpen={isDmsPickerOpen}
                onClose={() => setIsDmsPickerOpen(false)}
                onAttach={handleAttachDmsDocs}
              />
            </div>
          </div>

          {editingId && files.length > 0 && (
            <div className="space-y-3 rounded-lg border border-primary-200 bg-primary-50 p-4 dark:border-primary-700/40 dark:bg-primary-900/20">
              <Label className="text-sm font-semibold text-gray-900 dark:text-gray-100">
                Main file behavior
              </Label>
              <div className="space-y-2">
                <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-200">
                  <input
                    type="radio"
                    checked={!replaceMainFile}
                    onChange={() => {
                      setReplaceMainFile(false);
                      setMainFileIndex(null);
                    }}
                    disabled={isLoading}
                    className="accent-primary"
                  />
                  Keep existing main file and add new uploads as attachments
                </label>
                <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-200">
                  <input
                    type="radio"
                    checked={replaceMainFile}
                    onChange={() => setReplaceMainFile(true)}
                    disabled={isLoading}
                    className="accent-primary"
                  />
                  Replace the main file with one of the new uploads
                </label>
              </div>
            </div>
          )}

          {(files.length > 1 ||
            (editingId && replaceMainFile && files.length > 0)) && (
            <div className="rounded-lg border border-primary-200 bg-primary-50 p-4 dark:border-primary-700/40 dark:bg-primary-900/20">
              <h3 className="mb-3 text-sm font-semibold text-gray-900 dark:text-gray-100">
                {t("Select the main file for the record")}
              </h3>
              <RadioGroup
                value={mainFileIndex?.toString()}
                onValueChange={(value) => {
                  setMainFileIndex(Number(value));
                  setMainFileError("");
                }}
                className="space-y-2">
                {files.map((file, index) => (
                  <div
                    key={file.name}
                    className="flex items-center space-x-3 rounded-md p-2 transition-colors hover:bg-primary-100 dark:hover:bg-primary-900/40">
                    <RadioGroupItem
                      value={index.toString()}
                      id={`main-file-${index}`}
                      className="border-primary-600 text-primary-600 dark:border-primary-400 dark:text-primary-400"
                    />
                    <Label
                      htmlFor={`main-file-${index}`}
                      className="flex-1 cursor-pointer text-sm text-gray-700 dark:text-gray-200">
                      {file.name}
                    </Label>
                  </div>
                ))}
              </RadioGroup>
              {mainFileError && (
                <p className="mt-2 flex items-center gap-1 text-sm text-red-600 dark:text-red-400">
                  <span className="font-medium">!</span> {mainFileError}
                </p>
              )}
            </div>
          )}
        </div>

        <div className="border-t border-gray-200 pt-4 dark:border-gray-700">
          <div className="space-y-3">
            <Button
              type="submit"
              disabled={isLoading}
              className="w-full rounded-lg bg-primary-600 py-3 font-medium text-white shadow-sm transition-all duration-200 hover:bg-primary-700 hover:shadow-md disabled:cursor-not-allowed disabled:opacity-50 dark:bg-primary-500 dark:hover:bg-primary-600">
              {isLoading
                ? t("userIncoming.Processing...")
                : editingId
                  ? t("userRecord.Update")
                  : t("common.create")}
            </Button>

            <Button
              type="button"
              disabled={isLoading}
              onClick={async () => {
                const isValid = await form.trigger();
                if (!isValid) {
                  toast.error(
                    t("userRecord.Please fill in all required fields"),
                  );
                  return;
                }

                if (!editingId && files.length === 0) {
                  toast.error(t("userRecord.Please select file"));
                  return;
                }

                if (!editingId && mainFileIndex === null) {
                  toast.error(t("userRecord.Please select a main file"));
                  setMainFileError(t("userRecord.Please select a main file"));
                  return;
                }

                if (editingId && replaceMainFile && mainFileIndex === null) {
                  toast.error(t("userRecord.Please select a main file"));
                  setMainFileError(t("userRecord.Please select a main file"));
                  return;
                }

                const selectedMainFile =
                  mainFileIndex !== null ? files[mainFileIndex] : null;

                if (
                  selectedMainFile &&
                  (!editingId || replaceMainFile) &&
                  selectedMainFile.type !== "application/pdf"
                ) {
                  toast.error(
                    t("userRecord.The main file must be a PDF document"),
                  );
                  setMainFileError(
                    t("userRecord.The main file must be a PDF document"),
                  );
                  return;
                }

                setPendingFormData(form.getValues());
                setIsCreateAndAssign(!editingId);
                setShowAssignModal(true);
              }}
              className="w-full rounded-lg bg-blue-600 py-3 font-medium text-white shadow-sm transition-all duration-200 hover:bg-blue-700 hover:shadow-md disabled:cursor-not-allowed disabled:opacity-50 dark:bg-blue-500 dark:hover:bg-blue-600">
              {editingId
                ? t("userIncoming.Update and Assign")
                : t("userIncoming.Create and Assign")}
            </Button>
          </div>
        </div>
      </form>

      <AssignIncomingRecordModal
        isOpen={showAssignModal}
        onSuccess={handleAssignmentSuccess}
        onClose={() => {
          setShowAssignModal(false);
          setPendingFormData(null);
          setIsCreateAndAssign(false);
        }}
      />
    </Form>
  );
};

export default AddIncomingRecordForm;
