import { FC, useState } from "react";
import { TickCircle } from "iconsax-react";
import { useFormik } from "formik";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } 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 Textarea from "../../../components/Textarea";
import { Pages } from "../../../config/Pages";
import { ErrorType } from "../../../helpers/types";
import { useSingleUpload } from "../../service/hooks/useServiceData";
import CreateProjectSidebar, {
  SelectedUser,
} from "./components/CreateProjectSidebar";
import { useCreateProject } from "./hooks/useProjectData";
import { CreateProjectType } from "./types/ProjectTypes";

const CreateProject: FC = () => {
  const { t } = useTranslation("global");
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const createProject = useCreateProject();
  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(searchParams.get("workspaceId") ?? "");

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

  const formik = useFormik<
    Pick<CreateProjectType, "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 = "";

      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;
        }
      }

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

  return (
    <div className="w-full mt-4">
      <div className="flex w-full justify-between items-center">
        <div>{t("taskmanager.new_project")}</div>
        <div>
          <Button
            className="px-5"
            isLoading={createProject.isPending || singleUpload.isPending}
            onClick={() => formik.handleSubmit()}
          >
            <div className="flex gap-2">
              <TickCircle className="size-5" color="#fff" />
              <div>{t("taskmanager.submit_project")}</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")}
                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 CreateProject;
