import { FC, useState } from "react";
import { TickCircle } from "iconsax-react";
import { useFormik } from "formik";
import { useTranslation } from "react-i18next";
import { useNavigate } 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 Textarea from "../../../components/Textarea";
import { Pages } from "../../../config/Pages";
import { ErrorType } from "../../../helpers/types";
import { useCreateWorkspace } from "./hooks/useWorkspaceData";
import { CreateWorkspaceType } from "./types/WorkspaceTypes";
import CreateWorkspaceSidebar, {
  SelectedUser,
} from "./components/CreateWorkspaceSidebar";

const CreateWorkspace: FC = () => {
  const { t } = useTranslation("global");
  const navigate = useNavigate();
  const createWorkspace = useCreateWorkspace();

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

  const handleCreateWorkspace = (values: CreateWorkspaceType) => {
    createWorkspace.mutate(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<CreateWorkspaceType, "name" | "description">>({
    initialValues: {
      name: "",
      description: "",
    },
    validationSchema: Yup.object({
      name: Yup.string().required(t("errors.required")),
      description: Yup.string(),
    }),
    onSubmit: (values) => {
      handleCreateWorkspace({
        ...values,
        color: selectedColor,
        isActive,
        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_workspace")}</div>
        <div>
          <Button
            className="px-5"
            isLoading={createWorkspace.isPending}
            onClick={() => formik.handleSubmit()}
          >
            <div className="flex gap-2">
              <TickCircle className="size-5" color="#fff" />
              <div>{t("taskmanager.submit_workspace")}</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 CreateWorkspace;
