import { useEffect, useState } from "react";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useAuth } from "@/shared/context/AuthContext";
import { TemplateSampleData } from "@/user-management/services/TemplateConfiguration/types/templateTypes";

export const useTemplateFormData = () => {
  const { listAllDepartmentResponse, currentEmployeesResponse } = useSettings();
  const { user } = useAuth();
  const [defaultFormData, setDefaultFormData] =
    useState<TemplateSampleData | null>(null);

  useEffect(() => {
    if (user && currentEmployeesResponse && listAllDepartmentResponse) {
      const currentEmployee = currentEmployeesResponse?.items?.find(
        (emp: any) => emp.user?.id === user.id,
      );

      const userPosition = currentEmployee?.employeePositions?.[0];
      const userUnit = listAllDepartmentResponse?.find(
        (dept: any) => dept.id === userPosition?.position?.id || dept.unitId === userPosition?.id,
      );

      const formData: TemplateSampleData = {
        collaborators: currentEmployee
          ? [
              {
                am: currentEmployee.user?.name?.am || "",
                en: currentEmployee.user?.name?.en || "",
              },
            ]
          : [{ am: "", en: "" }],
        preferredLanguage: "am",
        content: {
          isWithDelegateSignature: false,
          delegatorName: currentEmployee?.user?.name?.en || "",
          body: "",
          date: new Date().toISOString().split("T")[0],
          internalCC: [],
          externalCC: [],
          prefixCC: "",
          suffixCC: "",
          from: currentEmployee
            ? [
                currentEmployee.user?.name?.am ||
                  currentEmployee.user?.name?.en ||
                  "",
              ]
            : [],
          subject: "",
          sincerelyText: "Sincerely",
          to: [],
          prefix: "",
          suffix: "",
        },
        recordType: "external",
        unitId: userUnit?.id || userUnit?.unitId || "",
      };

      setDefaultFormData(formData);
    }
  }, [user, currentEmployeesResponse, listAllDepartmentResponse]);

  return {
    defaultFormData,
    departments: listAllDepartmentResponse || [],
    employees: currentEmployeesResponse?.items || [],
  };
};
