import { useForm } from "react-hook-form";
import { CreateMessagePayload, MessageFormData } from "../types/messageTypes";
import { toast } from "sonner";
import useSettings from "@/record-management/components/hooks/useSettings";
import { EmployeeWithUnitDto } from "@/user-management/dto/employees/employees";
import { KeyValue } from "@/record-management/types/recordSelectTypes";
import { useLocalizedName } from "@/shared/common/localizedName";

import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMessage } from "../hooks/useMessage";
import MessageForm from "./Form";

export const AddMessage = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<MessageFormData>({
    defaultValues: {
      messageTitleEn: "",
      messageTitleAm: "",
      messageContentAm: "",
      messageContentEn: "",
      employeeId: "",
      staffType: "",
      isActive: false,
    },
  });
  const { currentEmployeesResponse } = useSettings();
  const localizedName = useLocalizedName();
  const navigate = useNavigate();
  const { createItem } = useMessage();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const employeesList: KeyValue[] =
    currentEmployeesResponse?.items.map((employee: EmployeeWithUnitDto) => ({
      label: localizedName(employee.user.name),
      value: employee?.id ?? "",
      employeePositionId: employee.employeePositions?.[0]?.id ?? "",
    })) || [];
  const handleCreateSubmit = async (MessageFormData: MessageFormData) => {
    setIsSubmitting(true);
    try {
      const imageFile = MessageFormData.image?.[0];
      if (!imageFile) {
        throw new Error("images are required");
      }
      const payload: CreateMessagePayload = {
        messageTitle: {
          am: MessageFormData.messageTitleAm || "",
          en: MessageFormData.messageTitleEn || "",
        },
        messageContent: {
          am: MessageFormData.messageContentAm || "",
          en: MessageFormData.messageContentEn || "",
        },
        fileInfo: {
          fileName: imageFile.name,
          contentType: imageFile.type,
          size: imageFile.size,
          originalname: imageFile.name,
        },
        isActive: MessageFormData.isActive,
        staffType: MessageFormData.staffType,
        employeeId: MessageFormData.employeeId,
      };
      await createItem({
        data: payload,
        imageFile: imageFile,
      });
      toast.success(" created successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to create Message");
      console.error("Creation error:", error);
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <MessageForm
      handleSubmit={handleSubmit(handleCreateSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      employeesList={employeesList}
      label="Add Message"
    />
  );
};
