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 Button from "../../../components/Button";
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 {
  useGetWorkspaceDetail,
  useUpdateWorkspace,
} from "./hooks/useWorkspaceData";
import { UpdateWorkspaceType, WorkspaceDetailType } from "./types/WorkspaceTypes";
import CreateWorkspaceSidebar, {
  SelectedUser,
} from "./components/CreateWorkspaceSidebar";

const UpdateWorkspace: FC = () => {
  const { t } = useTranslation("global");
  const { id } = useParams();
  const navigate = useNavigate();
  const getWorkspaceDetail = useGetWorkspaceDetail(id || "");
  const updateWorkspace = useUpdateWorkspace();

  const [isActive, setIsActive] = useState(true);
  const [selectedColor, setSelectedColor] = useState("#A8E6CF");
  const [selectedUsers, setSelectedUsers] = useState<SelectedUser[]>([]);

  const workspace: WorkspaceDetailType | undefined =
    getWorkspaceDetail.data?.data?.workspace ??
    getWorkspaceDetail.data?.data;

  const handleUpdateWorkspace = (values: UpdateWorkspaceType) => {
    if (!id) return;

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

  const formik = useFormik<Pick<UpdateWorkspaceType, "name" | "description">>({
    initialValues: {
      name: "",
      description: "",
    },
    validationSchema: Yup.object({
      name: Yup.string().required(t("errors.required")),
      description: Yup.string(),
    }),
    onSubmit: (values) => {
      handleUpdateWorkspace({
        ...values,
        color: selectedColor,
        isActive,
        userIds: selectedUsers.map((user) => user.id),
      });
    },
  });

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

    formik.setValues({
      name: workspace.name,
      description: workspace.description ?? "",
    });
    setIsActive(workspace.isActive);
    setSelectedColor(workspace.color);

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

  if (getWorkspaceDetail.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={updateWorkspace.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.workspace_info")}</div>

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

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

        <CreateWorkspaceSidebar
          isActive={isActive}
          onIsActiveChange={setIsActive}
          selectedColor={selectedColor}
          onColorChange={setSelectedColor}
          selectedUsers={selectedUsers}
          onSelectedUsersChange={setSelectedUsers}
        />
      </div>
    </div>
  );
};

export default UpdateWorkspace;
