/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useAppDispatch } from "../../../store/hooks";
import { useSelector } from "react-redux";
import { RootState } from "../../../store/store";
import {
  createAttendanceLog,
  fetchAttendanceLogWithPagination,
  updateAttendanceLog,
} from "../../../store/Slice/attendanceLogSlice";

import { fetchPersonnelWithPagination } from "../../../store/Slice/personnelSlice";
import { AttendanceLogTypes } from "../../../types/attendanceLog.types";
import { useModalContext } from "../../../components/Modal/context/ModalContext";
import CreateAttendanceLogPres from "../Presentation/AttendanceLogPres";
import { useSnackbar } from "notistack";
import LocalStorageService from "../../../utils/local-storage";

interface ContainerProps {
  existingData?: AttendanceLogTypes;
}

const CreateAttendanceLogContainer: React.FC<ContainerProps> = ({ existingData }) => {
  const dispatch = useAppDispatch();
  const { closeModal } = useModalContext();
  const { enqueueSnackbar } = useSnackbar();

  const userId = LocalStorageService.getAccount().id;

  const { control, handleSubmit, reset, setValue } = useForm<AttendanceLogTypes>({
    mode: "all",
    defaultValues: existingData || { isActive: true },
  });

  // ✅ FIX: handle populated or id both
  const [selectedPersonnel, setSelectedPersonnel] = useState<any>(
    existingData?.personnelId && typeof existingData.personnelId === "object"
      ? existingData.personnelId
      : null
  );

  const [searchQuery, setSearchQuery] = useState("");

  const { personnels, loading } = useSelector(
    (state: RootState) => state.personnel
  );

  // ✅ Fetch Personnel
  useEffect(() => {
    if (searchQuery.trim()) {
      dispatch(
        fetchPersonnelWithPagination({
          page: 1,
          limit: 10,
          search: searchQuery,
        })
      );
    }
  }, [dispatch, searchQuery]);

  // ✅ SET DEFAULT personnelId for edit
  useEffect(() => {
    if (existingData?.personnelId) {
      const id =
        typeof existingData.personnelId === "object"
          ? existingData.personnelId._id
          : existingData.personnelId;

      setValue("personnelId", id);
    }
  }, [existingData, setValue]);

  const onSubmit = async (data: AttendanceLogTypes) => {
    try {
      let result;

      // ✅ CLEAN PAYLOAD (MOST IMPORTANT FIX)
      const payload: any = {
        ...data,
        personnelId: selectedPersonnel?._id || data.personnelId,
      };

      // 🔥 FIX createdBy / updatedBy issue
      if (payload.createdBy && typeof payload.createdBy === "object") {
        payload.createdBy = payload.createdBy._id || payload.createdBy.id;
      }

      if (payload.updatedBy && typeof payload.updatedBy === "object") {
        payload.updatedBy = payload.updatedBy._id || payload.updatedBy.id;
      }

      if (existingData) {
        payload.updatedBy = userId;

        result = await dispatch(
          updateAttendanceLog({
            ...existingData,
            ...payload,
          })
        ).unwrap();
      } else {
        payload.createdBy = userId;
        result = await dispatch(createAttendanceLog(payload)).unwrap();
      }

      enqueueSnackbar(
        result.message ||
          (existingData
            ? "AttendanceLog updated successfully"
            : "AttendanceLog created successfully"),
        { variant: "success", anchorOrigin: { vertical: "top", horizontal: "center" } }
      );

      reset();

      dispatch(
        fetchAttendanceLogWithPagination({
          page: 1,
          limit: 10,
          search: "",
          createdBy: userId,
        })
      );

      closeModal();
    } catch (error: any) {
      console.error("Submission error:", error);

      enqueueSnackbar(error.message || "Something went wrong", {
        variant: "error",
        anchorOrigin: { vertical: "top", horizontal: "center" },
      });

      closeModal();
    }
  };

  return (
    <CreateAttendanceLogPres
      control={control}
      onSubmit={handleSubmit(onSubmit)}
      personnels={personnels}
      loading={loading}
      searchQuery={searchQuery}
      selectedPersonnel={selectedPersonnel}
      setSelectedPersonnel={setSelectedPersonnel}
      onSearchChange={setSearchQuery}
      setValue={setValue}
    />
  );
};

export default CreateAttendanceLogContainer;