import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useEffect, useMemo, useState } from "react";
import { EmployeeWithUnitDto } from "@/user-management/dto/employees/employees";
import { KeyValue } from "@/record-management/types/recordSelectTypes";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  CreateMessagePayload,
  MessageFormData,
  MessageItem,
} from "../types/messageTypes";
import { useNavigate, useParams } from "react-router-dom";
import { useMessage } from "../hooks/useMessage";
import { toast } from "sonner";
import MessageForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<MessageFormData>;
  control: Control<MessageFormData>;
  setValue: UseFormSetValue<MessageFormData>;
  register: UseFormRegister<MessageFormData>;
  errors: FieldErrors<MessageFormData>;
  reset?: UseFormReset<MessageFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  employeesList: KeyValue[];
  item?: MessageItem;
  label: string;
}
export const EditMessage = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useMessage(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      messageTitleEn: item?.messageTitle?.en || "",
      messageTitleAm: item?.messageTitle?.am || "",
      messageContentAm: item?.messageContent?.am || "",
      messageContentEn: item?.messageContent?.en || "",
      employeeId: item?.employeeId || "",
      isActive: item?.isActive ?? true,
      staffType: item?.staffType || "",
      image: undefined,
    }),
    [item] // 👈 recompute only when item changes
  );

  const {
    register,
    handleSubmit,
    watch,
    control,
    setValue,
    reset,
    formState: { errors },
  } = useForm<MessageFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);

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

  const handleEditSubmit = async (MessageFormData: MessageFormData) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const imageFile = MessageFormData.image?.[0];
      const payload: CreateMessagePayload = {
        messageTitle: {
          am: MessageFormData.messageTitleAm || "",
          en: MessageFormData.messageTitleEn || "",
        },
        messageContent: {
          am: MessageFormData.messageContentAm || "",
          en: MessageFormData.messageContentEn || "",
        },
        fileInfo: imageFile
          ? {
              fileName: imageFile.name,
              contentType: imageFile.type,
              size: imageFile.size,
              originalname: imageFile.name,
            }
          : undefined,
        isActive: MessageFormData.isActive,
        staffType: MessageFormData.staffType,
        employeeId: MessageFormData.employeeId,
      };

      await updateItem({
        id: item?.id,
        data: payload,
        ...(imageFile && { imageFile }),
      });

      toast.success("message updated successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to update about us");
      console.error("Update error:", error);
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <MessageForm
      handleSubmit={handleSubmit(handleEditSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      employeesList={employeesList}
      reset={reset}
      item={item}
      label="Edit Message"
    />
  );
};
