import { useFormik } from "formik";
import { FC, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import * as Yup from "yup";
import Button from "../../../components/Button";
import PageLoading from "../../../components/PageLoading";
import Select from "../../../components/Select";
import { toast } from "../../../components/Toast";
import { Pages } from "../../../config/Pages";
import { ErrorType } from "../../../helpers/types";
import { useGetAdminsListAll } from "../../users/hooks/useUserData";
import { UserItemType } from "../../users/types/UserTypes";
import { useGetMasterById, useUpdateMaster } from "../hooks/useTicketData";
import { CreateTicketMasterType } from "../types/TicketTypes";

const UpdateTicketMaster: FC = () => {
  const { t } = useTranslation("global");
  const { id } = useParams();
  const navigate = useNavigate();
  const getAdmins = useGetAdminsListAll();
  const getMaster = useGetMasterById(id ?? "");
  const updateMaster = useUpdateMaster();

  const formik = useFormik<CreateTicketMasterType>({
    initialValues: {
      userId: "",
    },
    validationSchema: Yup.object({
      userId: Yup.string().required(t("errors.required")),
    }),
    onSubmit: (values) => {
      updateMaster.mutate(
        { id: id as string, params: values },
        {
          onSuccess: () => {
            toast(t("success"), "success");
            navigate(Pages.ticket.masters);
          },
          onError: (error: ErrorType) => {
            toast(error.response?.data?.error.message[0], "error");
          },
        },
      );
    },
  });

  useEffect(() => {
    const master = getMaster.data?.data?.master ?? getMaster.data?.data?.ticketMaster;
    if (master?.userId) {
      formik.setFieldValue("userId", master.userId);
    }
  }, [getMaster.data]);

  if (getMaster.isPending) {
    return <PageLoading />;
  }

  return (
    <div className="mt-4">
      <div>{t("ticket.edit_master")}</div>

      <div className="bg-white mt-8 py-8 xl:px-10 px-4 rounded-3xl max-w-xl">
        <Select
          label={t("ticket.user")}
          placeholder={t("select")}
          className="border"
          items={getAdmins.data?.data?.map((item: UserItemType) => ({
            label: `${item.firstName} ${item.lastName}`,
            value: item.id,
          }))}
          {...formik.getFieldProps("userId")}
          error_text={formik.touched.userId && formik.errors.userId ? formik.errors.userId : ""}
        />

        <div className="mt-8 flex justify-end">
          <Button
            label={t("submit")}
            className="w-fit px-7"
            onClick={() => formik.handleSubmit()}
            isLoading={updateMaster.isPending}
          />
        </div>
      </div>
    </div>
  );
};

export default UpdateTicketMaster;
