import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

import DelegationForm from "@/record-management/components/delegation/delegationForm";
import { delegationFormSchema } from "../../../components/delegation/delegationFormSchema";

import { useLocation, useNavigate } from "react-router-dom";
import { useDelegations } from "@/record-management/components/hooks/useDelegations";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import useSettings from "@/record-management/components/hooks/useSettings";

type DelegationFormValues = z.infer<typeof delegationFormSchema>;

const AddDelegationPage = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { delegatePosition } = useDelegations();
  const { t } = useTranslation();
  const routeState = (location.state as {
    employeeId?: string;
    positionId?: string;
  } | null) ?? { employeeId: "", positionId: "" };
  const form = useForm<DelegationFormValues>({
    resolver: zodResolver(delegationFormSchema),
    defaultValues: {
      positionId: routeState.positionId || "",
      employeeId: "",
      startDate: new Date(),
      endDate: new Date(),
      internalCC: [],
      signatureId: "",
      stampId: "",
      language: "am",
      locale: "am",
    },
  });
  const { allDepartmentUnits } = useSettings();
  const handleCreateDelegation = (values: DelegationFormValues) => {
    const departmentUnitByValue = new Map(
      allDepartmentUnits.map((unit) => [
        unit.id && unit.id.trim() !== "" ? unit.id : unit.key || "",
        unit,
      ]),
    );
    const internalCCValues =
      values.internalCC
        ?.map((selectedId) => departmentUnitByValue.get(selectedId))
        .filter((unit): unit is (typeof allDepartmentUnits)[number] =>
          Boolean(unit),
        ) ?? [];
    delegatePosition(
      {
        delegationDto: {
          employeePositionId: values.employeeId as string,
          from: new Date(values.startDate).toISOString() as unknown as Date,
          to: new Date(values.endDate).toISOString() as unknown as Date,
        },
        stampId: values.stampId || "",
        signatureId: values.signatureId || "",
        locale: values.language ?? values.locale ?? "am",
        // Reverse so the BE's render-time reversal lands back on selection
        // order — mirrors the workaround applied in add/edit user records.
        cc: [
          ...(internalCCValues?.slice().map((c) => ({
            unitId: c.unitId!,
            positionId: c.id!,
            type: "internal" as const,
          })) ?? []),
        ],
      },
      {
        onSuccess: () => {
          toast.success(t("delegation.createdSuccess"));
          navigate("/record-management/delegation");
        },
      },
    );
  };
  return (
    <DelegationForm
      formInstance={form}
      onSubmit={handleCreateDelegation}
      isEditing={false}
      selectedPositionId={routeState.positionId || ""}
      selectedEmployeeId={routeState.employeeId || ""}
    />
  );
};

export default AddDelegationPage;
