import { FC, useEffect, useState } from "react";
import { TickCircle } from "iconsax-react";
import { useFormik } from "formik";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from '../../../components/Toast';
import * as Yup from "yup";
import moment from "moment-jalaali";
import Button from "../../../components/Button";
import DatePickerComponent from "../../../components/DatePicker";
import Input from "../../../components/Input";
import PageLoading from "../../../components/PageLoading";
import Textarea from "../../../components/Textarea";
import { Pages } from "../../../config/Pages";
import { ErrorType } from "../../../helpers/types";
import { useSingleUpload } from "../../service/hooks/useServiceData";
import CreateProjectSidebar, {
  findMatchingBackgroundPreset,
  SelectedUser,
} from "./components/CreateProjectSidebar";
import { useGetProjectDetail, useUpdateProject } from "./hooks/useProjectData";
import { ProjectDetailType, UpdateProjectType } from "./types/ProjectTypes";

const UpdateProject: FC = () => {
  const { t } = useTranslation("global");
  const { id = "" } = useParams();
  const navigate = useNavigate();
  const getProjectDetail = useGetProjectDetail(id);
  const updateProject = useUpdateProject();
  const singleUpload = useSingleUpload();

  const [isActive, setIsActive] = useState(true);
  const [selectedColor, setSelectedColor] = useState("#A8E6CF");
  const [selectedUsers, setSelectedUsers] = useState<SelectedUser[]>([]);
  const [selectedBackground, setSelectedBackground] = useState<string | null>(null);
  const [backgroundImage, setBackgroundImage] = useState<File | null>(null);
  const [workspaceId, setWorkspaceId] = useState("");
  const [existingBackgroundPicture, setExistingBackgroundPicture] = useState("");
  const [startDateDefault, setStartDateDefault] = useState("");

  const project: ProjectDetailType | undefined =
    getProjectDetail.data?.data?.project ?? getProjectDetail.data?.data;

  const handleUpdateProject = (values: UpdateProjectType) => {
    if (!id) return;

    updateProject.mutate(
      { id, params: values },
      {
        onSuccess: () => {
          toast(t("success"), 'success');
          navigate(`${Pages.taskmanager.projectList}${values.workspaceId}`);
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], 'error');
        },
      },
    );
  };

  const formik = useFormik<
    Pick<UpdateProjectType, "name" | "ownerName" | "description" | "startDate">
  >({
    initialValues: {
      name: "",
      ownerName: "",
      description: "",
      startDate: "",
    },
    validationSchema: Yup.object({
      name: Yup.string().required(t("errors.required")),
      ownerName: Yup.string().required(t("errors.required")),
      description: Yup.string(),
      startDate: Yup.string().required(t("errors.required")),
    }),
    onSubmit: async (values) => {
      if (!workspaceId) {
        toast(t("taskmanager.select_workspace"), 'error');
        return;
      }

      let backgroundPicture = existingBackgroundPicture;

      if (backgroundImage) {
        const formData = new FormData();
        formData.append("file", backgroundImage);

        try {
          const uploadResult = await singleUpload.mutateAsync(formData);
          backgroundPicture = uploadResult?.data?.url ?? "";
        } catch (error) {
          const uploadError = error as ErrorType;
          toast(uploadError.response?.data?.error.message[0], 'error');
          return;
        }
      }

      handleUpdateProject({
        ...values,
        startDate: moment(values.startDate, "jYYYY/jMM/jDD").format("YYYY-MM-DD"),
        backgroundPicture,
        backgroundColor: selectedColor,
        isActive,
        workspaceId,
        userIds: selectedUsers.map((user) => user.id),
      });
    },
  });

  useEffect(() => {
    if (!project) return;

    formik.setValues({
      name: project.name,
      ownerName: project.ownerName,
      description: project.description ?? "",
      startDate: project.startDate
        ? moment(project.startDate, "YYYY-MM-DD").format("jYYYY/jMM/jDD")
        : "",
    });
    setIsActive(project.isActive);
    const backgroundColor = project.backgroundColor ?? "#A8E6CF";
    setSelectedBackground(findMatchingBackgroundPreset(backgroundColor));
    setSelectedColor(backgroundColor);
    setWorkspaceId(project.workspaceId);
    setExistingBackgroundPicture(project.backgroundPicture ?? "");
    setStartDateDefault(
      project.startDate
        ? moment(project.startDate, "YYYY-MM-DD").format("jYYYY/jMM/jDD")
        : "",
    );

    if (project.users?.length) {
      setSelectedUsers(
        project.users.map((user) => ({
          id: user.id,
          name: `${user.firstName} ${user.lastName}`,
          profilePic: user.profilePic,
        })),
      );
    } else if (project.userIds?.length) {
      setSelectedUsers(
        project.userIds.map((userId) => ({
          id: userId,
          name: userId,
        })),
      );
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [project]);

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

  return (
    <div className="w-full mt-4">
      <div className="flex w-full justify-between items-center">
        <div>{t("edit")}</div>
        <div>
          <Button
            className="px-5"
            isLoading={updateProject.isPending || singleUpload.isPending}
            onClick={() => formik.handleSubmit()}
          >
            <div className="flex gap-2">
              <TickCircle className="size-5" color="#fff" />
              <div>{t("submit")}</div>
            </div>
          </Button>
        </div>
      </div>

      <div className="flex gap-6">
        <div className="flex-1">
          <div className="flex-1 mt-10 bg-white py-8 xl:px-10 px-4 rounded-3xl">
            <div className="text-sm font-bold">{t("taskmanager.project_info")}</div>

            <div className="mt-8">
              <Input
                label={t("taskmanager.project_name")}
                {...formik.getFieldProps("name")}
                error_text={
                  formik.touched.name && formik.errors.name ? formik.errors.name : ""
                }
              />
            </div>

            <div className="mt-8 rowTwoInput">
              <DatePickerComponent
                label={t("taskmanager.project_start_date")}
                placeholder={t("taskmanager.select_date")}
                defaulValue={startDateDefault}
                onChange={(value) => formik.setFieldValue("startDate", value)}
                error_text={
                  formik.touched.startDate && formik.errors.startDate
                    ? formik.errors.startDate
                    : ""
                }
              />
              <Input
                label={t("taskmanager.employer_name")}
                {...formik.getFieldProps("ownerName")}
                error_text={
                  formik.touched.ownerName && formik.errors.ownerName
                    ? formik.errors.ownerName
                    : ""
                }
              />
            </div>

            <div className="mt-8">
              <Textarea
                label={t("description")}
                {...formik.getFieldProps("description")}
                error_text={
                  formik.touched.description && formik.errors.description
                    ? formik.errors.description
                    : ""
                }
              />
            </div>
          </div>
        </div>

        <CreateProjectSidebar
          isActive={isActive}
          onIsActiveChange={setIsActive}
          selectedColor={selectedColor}
          onColorChange={setSelectedColor}
          selectedUsers={selectedUsers}
          onSelectedUsersChange={setSelectedUsers}
          selectedBackground={selectedBackground}
          onBackgroundChange={setSelectedBackground}
          backgroundImage={backgroundImage}
          onBackgroundImageChange={setBackgroundImage}
          workspaceId={workspaceId}
          onWorkspaceIdChange={setWorkspaceId}
        />
      </div>
    </div>
  );
};

export default UpdateProject;
