import React, { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate, useParams } from "react-router-dom";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { t } from "i18next";
import { FileText, Hash, User, Building2 } from "lucide-react";

import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import {
  defaultSendLetterValues,
  EditLetterFormValues,
  editLetterSchema,
} from "./AddIncoming/Form-Schema";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/shared/common/ui/form";
import { ReusableFileUploader } from "@/shared/common/ui/fileUploader/reusableFileUploader";
import { RadioGroup, RadioGroupItem } from "@/shared/common/ui/radio-group";
import { Label } from "@/shared/common/ui/label";
import { Spinner } from "@/shared/common/ui/sppiner";
import { useUpdateIncoming } from "@/record-management/components/hooks/useIncomingRecords";
import {
  STORAGE_UPLOAD_ERROR_CODE,
  STORAGE_UPLOAD_TOO_LARGE,
  UploadKeyResponse,
  uploadMultiple,
  uploadSingle,
} from "@/record-management/services/api/newFileService";
import { AttachmentInfo } from "@/record-management/dto/userRecords/userRecordsDto";
import {
  deleteAttachmentsById,
  fetchRecordById,
} from "@/record-management/services/api/userRecordService";
import FileList, {
  IAttachmentInfoWithId,
} from "@/record-management/common/fileListComponent";
import AssignCCRecord from "@/record-management/components/userIncoming/ccIncomingRecords/AssignCCRecord";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useNonSmartRecordPdfAssign } from "@/record-management/components/hooks/useNonSmartRecordPdfAssign";
import AssignIncomingRecordModal from "./AddIncoming/AssignIncomingRecordModal";

interface EditIncomingRecordFormProps {
  onSuccess?: () => void;
  onCancel?: (error: unknown) => void;
}

const EditIncomingRecordForm = ({
  onSuccess,
  onCancel,
}: EditIncomingRecordFormProps) => {
  const form = useForm<EditLetterFormValues>({
    resolver: zodResolver(editLetterSchema),
    defaultValues: {
      ...defaultSendLetterValues,
      receiverPositions: [],
      receiverEmployeePositions: [],
      preferredLanguage: "am", //
    },
  });
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { id: recordId } = useParams<{ id: string }>();

  const [files, setFiles] = useState<File[]>([]);
  const [mainFileIndex, setMainFileIndex] = useState<number | null>(null);
  const [mainFileError, setMainFileError] = useState("");
  const [existingFileInfo, setExistingFileInfo] = useState<
    AttachmentInfo["fileInfo"] | null
  >(null);
  const [existingAttachments, setExistingAttachments] = useState<
    IAttachmentInfoWithId[]
  >([]);
  // Attachment ids the user has clicked "delete" on but not yet committed
  // by submitting the form. Empty array means nothing is staged.
  const [pendingDeletionIds, setPendingDeletionIds] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showCCAssignModal, setShowCCAssignModal] = useState(false);
  const [hasCCAssigned, setHasCCAssigned] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [pendingFormData, setPendingFormData] =
    useState<EditLetterFormValues | null>(null);
  const [pendingUploadedFiles, setPendingUploadedFiles] = useState<
    AttachmentInfo[]
  >([]);
  const [pendingFinalFileInfo, setPendingFinalFileInfo] = useState<any>(null);
  const {
    updateIncomingRecord,
    isUpdating: isUpdatingRecord,
    isUploading: isUploadingRecord,
  } = useUpdateIncoming();
  const { handleError } = useErrorHandler(t);
  const { updateAndAssign, isUpdating: isAssigning } =
    useNonSmartRecordPdfAssign();

  const {
    data: record,
    isLoading,
    error: recordFetchError,
  } = useQuery({
    queryKey: ["record", recordId],
    queryFn: async () => {
      try {
        const result = await fetchRecordById(recordId!);

        return result;
      } catch (error) {
        console.error("❌ editIncoming: Failed to fetch record:", error);
        throw error;
      }
    },
    enabled: !!recordId,
  });

  // Surface main-record fetch failures via the centralized error handler.
  // record-pdf failure stays silent — it's a sidecar preview.
  const prevRecordErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (recordFetchError && recordFetchError !== prevRecordErrorRef.current) {
      prevRecordErrorRef.current = recordFetchError;
      handleError(recordFetchError);
    }
  }, [recordFetchError, handleError]);



  useEffect(() => {
    if (record) {
      const content = record.content?.[0];
      const preferredLanguage: "am" | "en" =
        record.preferredLanguage === "en" ? "en" : "am";

      form.reset({
        fileInfo: record.fileInfo ?? undefined,
        subject: content?.subject ?? "",
        letterNumber: record.letterNumber ?? "",
        deliveredBy:
          record.metadata.deliveredBy.am ||
          record.metadata.deliveredBy.en ||
          "",
        organizationName: {
          am: record.metadata.organizationName?.am ?? "",
          en: record.metadata.organizationName?.en ?? "",
        },
        receiverPositions: [],
        receiverEmployeePositions: [],
        preferredLanguage,
        letterName: record.letterName || "",
      });

      setExistingFileInfo(record.fileInfo ?? null);
      setExistingAttachments(
        (content?.recordAttachments ?? []).map((attachment: any) => ({
          id: attachment.id,
          presigned: attachment.presigned,
          fileInfo: {
            fileName: attachment.fileInfo.fileName,
            contentType: attachment.fileInfo.contentType,
            originalname:
              attachment.fileInfo.originalname || attachment.fileInfo.fileName,
            size: attachment.fileInfo.size ?? 0,
          },
        })),
      );

      // Check if CC is already assigned
      const ccContent = content?.ccs;
      setHasCCAssigned(ccContent && ccContent.length > 0);
    } else {
    }
  }, [record, form]);

  // === Form Submit ===
  const onSubmit = async (values: EditLetterFormValues) => {
    try {
      setIsSubmitting(true);
      if (!existingFileInfo && files.length === 0) {
        toast.error(t("userRecord.Please select a main file"));
        setMainFileError(t("userRecord.Please select a main file"));
        return;
      }

      // =========================
      // 1. UPLOAD NEW FILES (if any)
      // =========================
      let uploadedFiles: AttachmentInfo[] = [];
      if (files.length > 0) {
        if (!existingFileInfo && mainFileIndex === null) {
          toast.error(t("userRecord.Please select a main file"));
          setMainFileError(t("userRecord.Please select a main file"));
          return;
        } else {
          setMainFileError("");
        }

        // Upload all new files
        let fileInfos: UploadKeyResponse["fileInfo"][] = [];

        if (files.length > 1) {
          fileInfos = await uploadMultiple(files);
        } else if (files.length === 1) {
          const fileInfo = await uploadSingle(files[0]);
          fileInfos = [fileInfo];
        }

        // Convert fileInfo → AttachmentInfo
        uploadedFiles = 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 finalFileInfo =
        mainFileIndex !== null
          ? (uploadedFiles[mainFileIndex]?.fileInfo ?? existingFileInfo)
          : existingFileInfo;

      if (!finalFileInfo) {
        toast.error(t("userRecord.Please select a main file"));
        setMainFileError(t("userRecord.Please select a main file"));
        return;
      }

      // Exclude attachments the user staged for deletion — otherwise the
      // update payload re-sends them and the backend keeps/re-creates them,
      // making the deletion appear to revert after editing again.
      const finalAttachments = [
        ...existingAttachments
          .filter(
            (attachment) =>
              !attachment.id || !pendingDeletionIds.includes(attachment.id),
          )
          .map((attachment) => ({
            fileInfo: {
              bucket: "",
              fileName: attachment.fileInfo.fileName,
              contentType:
                attachment.fileInfo.contentType || "application/octet-stream",
              originalname:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
              size: attachment.fileInfo.size || 0,
            },
            name: {
              am:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
              en:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
            },
          })),
        ...uploadedFiles.filter((_, index) => index !== mainFileIndex),
      ];

      // =========================
      // 2. BUILD PAYLOAD
      // =========================
      const payload = {
        ...values,
        fileInfo: finalFileInfo,
        subject: values.subject || "",
        letterNumber: values.letterNumber || "",
        deliveredBy: values.deliveredBy || "",
        receiverPositions: values.receiverPositions ?? [],
        receiverEmployeePositions: values.receiverEmployeePositions ?? [],
        preferredLanguage: values.preferredLanguage || "am",
        organizationName: {
          am: values.organizationName?.am || "",
          en: values.organizationName?.en || "",
        },
        letterName: values.letterName || "",
        attachments: finalAttachments,
      };

      // =========================
      // 3. UPDATE RECORD
      // =========================

      await updateIncomingRecord(payload, recordId as string);

      // Commit staged attachment deletions now that the record update succeeded.
      if (pendingDeletionIds.length > 0) {
        const deletionResults = await Promise.allSettled(
          pendingDeletionIds.map((id) => deleteAttachmentsById(id)),
        );
        const firstFailure = deletionResults.find(
          (r): r is PromiseRejectedResult => r.status === "rejected",
        );
        if (firstFailure) {
          await handleError(firstFailure.reason);
        }
        setPendingDeletionIds([]);
      }

      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ["record-incoming"] }),
        queryClient.invalidateQueries({
          queryKey: ["external-record-incoming"],
        }),
        // Force the detail-page record + PDF queries to refetch so a replaced
        // main file shows up instead of the stale cached version.
        queryClient.invalidateQueries({ queryKey: ["record"] }),
        queryClient.invalidateQueries({ queryKey: ["record-pdf"] }),
        queryClient.invalidateQueries({ queryKey: ["record-attachment"] }),
      ]);

      // If there are new files, prepare for assignment modal
      if (uploadedFiles.length > 0) {
        // Store uploaded files (raw) and final attachments for assignment
        // uploadedFiles contains newly uploaded files, finalAttachments includes existing + new
        setPendingUploadedFiles(finalAttachments);
        setPendingFinalFileInfo(finalFileInfo);
        setPendingFormData(values);
        setShowAssignModal(true);
        return;
      }

      toast.success(
        t(
          "userRecord.incomingRecordUpdated",
          "Incoming record changes have been saved.",
        ),
      );
      onSuccess?.();
      navigate("/record-management/recordOfficer/incoming");
    } catch (error) {
      if (
        error instanceof Error &&
        error.message === STORAGE_UPLOAD_TOO_LARGE
      ) {
        toast.error(t("userRecord.storageUploadFailed"), {
          description: t("msg.fileTooLarge"),
        });
      } else if (
        error instanceof Error &&
        error.message === STORAGE_UPLOAD_ERROR_CODE
      ) {
        toast.error(t("userRecord.storageUploadFailed"));
      } else {
        await handleError(error);
      }
      onCancel?.(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleAssignmentSuccess = async (assignmentData: any) => {
    if (!pendingFormData || !recordId) return;
    if (!existingFileInfo && files.length === 0) {
      toast.error(t("userRecord.Please select a main file"));
      setMainFileError(t("userRecord.Please select a main file"));
      return;
    }
    try {
      // Refetch the record to get the latest file information after update
      let uploadedFiles: AttachmentInfo[] = [];
      if (files.length > 0) {
        if (!existingFileInfo && mainFileIndex === null) {
          toast.error(t("userRecord.Please select a main file"));
          setMainFileError(t("userRecord.Please select a main file"));
          return;
        } else {
          setMainFileError("");
        }

        // Upload all new files
        let fileInfos: UploadKeyResponse["fileInfo"][] = [];

        if (files.length > 1) {
          fileInfos = await uploadMultiple(files);
        } else if (files.length === 1) {
          const fileInfo = await uploadSingle(files[0]);
          fileInfos = [fileInfo];
        }

        // Convert fileInfo → AttachmentInfo
        uploadedFiles = 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,
          },
        }));
      }
      // Get latest attachments from the record
      const finalFileInfo =
        mainFileIndex !== null
          ? (uploadedFiles[mainFileIndex]?.fileInfo ?? existingFileInfo)
          : existingFileInfo;
      const finalAttachments = [
        ...existingAttachments
          .filter(
            (attachment) =>
              !attachment.id || !pendingDeletionIds.includes(attachment.id),
          )
          .map((attachment) => ({
            fileInfo: {
              bucket: "",
              fileName: attachment.fileInfo.fileName,
              contentType:
                attachment.fileInfo.contentType || "application/octet-stream",
              originalname:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
              size: attachment.fileInfo.size || 0,
            },
            name: {
              am:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
              en:
                attachment.fileInfo.originalname ||
                attachment.fileInfo.fileName,
            },
          })),
        ...uploadedFiles.filter((_, index) => index !== mainFileIndex),
      ];
      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: assignmentData.assignedEmployees,
          letterNumber: pendingFormData.letterNumber,
          organizationName: pendingFormData.organizationName,
          deliveredBy: pendingFormData.deliveredBy,
          preferredLanguage: pendingFormData.preferredLanguage || "am",
          letterName: pendingFormData.letterName,
          // Use latest attachments from record (includes newly uploaded files)
          attachments: finalAttachments.map((att: any) => ({
            fileInfo: {
              fileName: att.fileInfo?.fileName || att.fileName,
              contentType:
                att.fileInfo?.contentType ||
                att.contentType ||
                "application/octet-stream",
              size: att.fileInfo?.size || att.size || 0,
              originalname:
                att.fileInfo?.originalname || att.originalname || att.fileName,
              bucket: att.fileInfo?.bucket || "",
            },
            name: {
              am:
                att.fileInfo?.originalname || att.originalname || att.fileName,
              en:
                att.fileInfo?.originalname || att.originalname || att.fileName,
            },
          })),
        },
        assignDto: {
          recordBoxId: null,
          recordId: recordId || null,
          employeePositionIds: assignmentData.assignedEmployees,
          positionIds: assignmentData.receivingDepartments,
          comment: assignmentData.remarks,
        },
      };

      await updateAndAssign({ id: recordId, payload });

      setShowAssignModal(false);
      setPendingFormData(null);
      setPendingUploadedFiles([]);
      setPendingFinalFileInfo(null);
      setPendingDeletionIds([]);

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

      toast.success(
        t(
          "incomingRecord.updatedAndAssignedSuccess",
          "Record updated and assigned successfully",
        ),
      );
      onSuccess?.();
      navigate("/record-management/recordOfficer/incoming");
    } catch (error) {
      await handleError(error);
    }
  };

  const isLoadingAny =
    isLoading ||
    isSubmitting ||
    isUpdatingRecord ||
    isUploadingRecord ||
    isAssigning;

  return (
    <Form {...form}>
      {isLoadingAny && (
        <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="edit-form-title"
      >
        {/* Header */}
        <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="edit-form-title"
                className="text-2xl font-bold text-gray-900 dark:text-gray-100"
              >
                {t("addRecord.editIncomingRecord")}
              </h2>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                {t("msg.updateRecordMsg")}
              </p>
            </div>
          </div>
        </div>

        <div className="space-y-6">
          {/* Letter Information Section */}
          <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>

            {/* Subject */}
            <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>
              )}
            />

            {/* Letter Number + File Name in grid */}
            <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>

            {/* Delivered By */}
            <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>

          {/* Organization Information Section */}
          <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>

          {/* Document Attachments Section */}
          <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>

            {/* Existing Main Letter */}
            {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>
                <div className="mt-1 flex items-center justify-between">
                  <p>
                    {existingFileInfo.originalname || existingFileInfo.fileName}
                  </p>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setExistingFileInfo(null);
                      setMainFileError(
                        t("userRecord.Please select a main file"),
                      );
                    }}
                    className="text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:text-red-300"
                  >
                    {t("common.delete", "Remove")}
                  </Button>
                </div>
                {existingAttachments.filter(
                  (attachment) =>
                    !attachment.id ||
                    !pendingDeletionIds.includes(attachment.id),
                ).length > 0 && (
                  <p className="mt-2 text-gray-600 dark:text-gray-400">
                    {
                      existingAttachments.filter(
                        (attachment) =>
                          !attachment.id ||
                          !pendingDeletionIds.includes(attachment.id),
                      ).length
                    }{" "}
                    existing attachment
                    {existingAttachments.filter(
                      (attachment) =>
                        !attachment.id ||
                        !pendingDeletionIds.includes(attachment.id),
                    ).length > 1
                      ? "s"
                      : ""}
                  </p>
                )}
              </div>
            )}

            {/* Existing Attachments List */}
            {existingAttachments.filter(
              (attachment) =>
                !attachment.id || !pendingDeletionIds.includes(attachment.id),
            ).length > 0 && (
              <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/60">
                <h4 className="mb-2 text-sm font-medium text-gray-700 dark:text-gray-200">
                  {t("viewDetail.attachments")}
                </h4>
                <FileList
                  attachments={existingAttachments.filter(
                    (attachment) =>
                      !attachment.id ||
                      !pendingDeletionIds.includes(attachment.id),
                  )}
                  showDelete
                  onDelete={(fileId: string) => {
                    setPendingDeletionIds((prev) =>
                      prev.includes(fileId) ? prev : [...prev, fileId],
                    );
                  }}
                />
              </div>
            )}

            {/* File Uploader */}
            <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/60">
              <ReusableFileUploader
                files={files}
                setFiles={setFiles}
                isLoading={isUploadingRecord}
              />
            </div>
          </div>

          {/* Main file selection for new uploads */}
          {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={`edit-main-file-${index}`}
                      className="border-primary-600 text-primary-600 dark:border-primary-400 dark:text-primary-400"
                    />
                    <Label
                      htmlFor={`edit-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>
          )}

          {/* CC Assignment Section */}
          {hasCCAssigned && (
            <div className="rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-700/40 dark:bg-blue-900/20">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-blue-800 dark:text-blue-200">
                    {t("userIncoming.CC Assignment")}
                  </h3>
                  <p className="text-sm text-blue-600 dark:text-blue-400">
                    {t("userIncoming.This record has CC assignments")}
                  </p>
                </div>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setShowCCAssignModal(true)}
                  className="border-blue-300 text-blue-700 hover:bg-blue-100 dark:border-blue-600 dark:text-blue-300 dark:hover:bg-blue-900/40"
                >
                  {t("userIncoming.Manage CC")}
                </Button>
              </div>
            </div>
          )}
        </div>

        {/* Action Buttons */}
        <div className="border-t border-gray-200 pt-4 dark:border-gray-700">
          <div className="space-y-3">
            <Button
              type="submit"
              disabled={isLoadingAny}
              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"
            >
              {isLoadingAny
                ? t("userIncoming.Processing...")
                : t("userIncoming.update", "Update")}
            </Button>

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

                setPendingFormData(form.getValues());
                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"
            >
              {isAssigning
                ? t("userIncoming.Assigning...")
                : t("userIncoming.Update and Assign")}
            </Button>
          </div>
        </div>
      </form>

      {/* CC Assignment Modal */}
      {record && showCCAssignModal && (
        <AssignCCRecord
          open={showCCAssignModal}
          onClose={() => setShowCCAssignModal(false)}
          record={{
            id: record.id,
            createdAt: record.createdAt,
            referenceNumber: record.referenceNumber,
            dispatchedDate: record.dispatchedDate,
            amharicDispatchedDate: record.amharicDispatchedDate,
            amharicCreatedAt: record.amharicCreatedAt,
            initiationType: record.initiationType,
            recordTypeKey: record.recordTypeKey,
            content: record.content.map((content: any) => ({
              id: content.id,
              subject: content.subject,
              ccs:
                content.ccs?.map((cc: any, index: number) => ({
                  id: `cc-${content.id}-${index}`,
                  hasSeen: false,
                  seenAt: null,
                  seenByEmployeePosition: null,
                })) || [],
            })),
            initiator: record.initiator,
            initiatedAs: record.initiatedAs,
            status: record.statusKey,
          }}
          refetch={() => {
            queryClient.invalidateQueries({ queryKey: ["record", recordId] });
            setHasCCAssigned(true);
          }}
        />
      )}

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

export default EditIncomingRecordForm;
