/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useState } from "react";
import { observer } from "mobx-react";
import { Controller, useForm } from "react-hook-form";
// constants
import { ORGANIZATION_SIZE, RESTRICTED_URLS } from "@pi-dash/constants";
// types
import { useTranslation } from "@pi-dash/i18n";
import { Button } from "@pi-dash/propel/button";
import { TOAST_TYPE, setToast } from "@pi-dash/propel/toast";
import type { IUser, IWorkspace, TOnboardingSteps } from "@pi-dash/types";
// ui
import { CustomSelect, Input, Spinner } from "@pi-dash/ui";
import { validateWorkspaceName, validateSlug } from "@pi-dash/utils";
// hooks
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUserProfile, useUserSettings } from "@/hooks/store/user";
// services
import { WorkspaceService } from "@/services/workspace.service";

type Props = {
  stepChange: (steps: Partial<TOnboardingSteps>) => Promise<void>;
  user: IUser | undefined;
  invitedWorkspaces: number;
  handleCurrentViewChange: () => void;
};

// services
const workspaceService = new WorkspaceService();

export const CreateWorkspace = observer(function CreateWorkspace(props: Props) {
  const { stepChange, user, invitedWorkspaces, handleCurrentViewChange } = props;
  // states
  const [slugError, setSlugError] = useState(false);
  const [invalidSlug, setInvalidSlug] = useState(false);
  // pi dash hooks
  const { t } = useTranslation();
  // store hooks
  const { updateUserProfile } = useUserProfile();
  const { fetchCurrentUserSettings } = useUserSettings();
  const { createWorkspace, fetchWorkspaces } = useWorkspace();
  // form info
  const {
    handleSubmit,
    control,
    setValue,
    formState: { errors, isSubmitting, isValid },
  } = useForm<IWorkspace>({
    defaultValues: {
      name: "",
      slug: "",
      organization_size: "",
    },
    mode: "onChange",
  });

  const handleCreateWorkspace = async (formData: IWorkspace) => {
    if (isSubmitting) return;

    try {
      const res = await workspaceService.workspaceSlugCheck(formData.slug);
      if (res?.status === true && !RESTRICTED_URLS.includes(formData.slug)) {
        setSlugError(false);
        const workspaceResponse = await createWorkspace(formData);
        setToast({
          type: TOAST_TYPE.SUCCESS,
          title: t("Success"),
          message: t("Workspace created successfully"),
        });
        await fetchWorkspaces();
        await completeStep(workspaceResponse.id);
      } else setSlugError(true);
    } catch (_error) {
      setToast({
        type: TOAST_TYPE.ERROR,
        title: t("Error"),
        message: t("Workspace could not be created. Please try again."),
      });
    }
  };

  const completeStep = async (workspaceId: string) => {
    if (!user) return;
    const payload: Partial<TOnboardingSteps> = {
      workspace_create: true,
      workspace_join: true,
    };

    await stepChange(payload);
    await updateUserProfile({
      last_workspace_id: workspaceId,
    });
    await fetchCurrentUserSettings();
  };

  const isButtonDisabled = !isValid || invalidSlug || isSubmitting;

  return (
    <div className="space-y-4">
      {!!invitedWorkspaces && (
        <>
          <Button
            variant="ghost"
            size="xl"
            className="flex w-full items-center gap-2 bg-surface-2 text-14"
            onClick={handleCurrentViewChange}
          >
            I want to join invited workspaces{" "}
            <span className="flex h-4 w-4 items-center justify-center rounded-xs bg-accent-primary/80 text-11 font-medium text-on-color">
              {invitedWorkspaces}
            </span>
          </Button>
          <div className="mx-auto mt-4 flex items-center sm:w-96">
            <hr className="w-full border-strong" />
            <p className="mx-3 flex-shrink-0 text-center text-13 text-placeholder">or</p>
            <hr className="w-full border-strong" />
          </div>
        </>
      )}
      <div className="mx-auto space-y-1 py-4 text-center">
        <h3 className="text-24 font-bold text-primary">{t("Create your workspace")}</h3>
        <p className="font-medium text-placeholder">{t("To start using Pi Dash, you need to create or join a workspace.")}</p>
      </div>
      <form className="mx-auto mt-2 w-full space-y-4" onSubmit={handleSubmit(handleCreateWorkspace)}>
        <div className="space-y-1">
          <label
            className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
            htmlFor="name"
          >
            {t("Name your workspace")}
          </label>
          <Controller
            control={control}
            name="name"
            rules={{
              required: t("This field is required"),
              validate: (value) => validateWorkspaceName(value, true),
              maxLength: {
                value: 80,
                message: t("Limit your name to 80 characters."),
              },
            }}
            render={({ field: { value, ref, onChange } }) => (
              <div className="relative flex items-center rounded-md">
                <Input
                  id="name"
                  name="name"
                  type="text"
                  value={value}
                  onChange={(event) => {
                    onChange(event.target.value);
                    setValue("name", event.target.value);
                    setValue("slug", event.target.value.toLocaleLowerCase().trim().replace(/ /g, "-"), {
                      shouldValidate: true,
                    });
                  }}
                  placeholder={t("Something familiar and recognizable is always best.")}
                  ref={ref}
                  hasError={Boolean(errors.name)}
                  className="w-full border-strong placeholder:text-placeholder"
                  autoFocus
                />
              </div>
            )}
          />
          {errors.name && <span className="text-13 text-danger-primary">{errors.name.message}</span>}
        </div>
        <div className="space-y-1">
          <label
            className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
            htmlFor="slug"
          >
            {t("Set your workspace's URL")}
          </label>
          <Controller
            control={control}
            name="slug"
            rules={{
              required: t("This field is required"),
              maxLength: {
                value: 48,
                message: t("Limit your URL to 48 characters."),
              },
            }}
            render={({ field: { value, ref, onChange } }) => (
              <div
                className={`relative flex items-center rounded-md border-[0.5px] px-3 ${
                  invalidSlug ? "border-danger-strong" : "border-strong"
                }`}
              >
                <span className="text-13 whitespace-nowrap">{window && window.location.host}/</span>
                <Input
                  id="slug"
                  name="slug"
                  type="text"
                  value={value.toLocaleLowerCase().trim().replace(/ /g, "-")}
                  onChange={(e) => {
                    const validation = validateSlug(e.target.value);
                    if (validation === true) setInvalidSlug(false);
                    else setInvalidSlug(true);
                    onChange(e.target.value.toLowerCase());
                  }}
                  ref={ref}
                  hasError={Boolean(errors.slug)}
                  placeholder={t("Type or paste a URL")}
                  className="w-full border-none !px-0"
                />
              </div>
            )}
          />
          <p className="text-13 text-tertiary">{t("You can only edit the slug of the URL")}</p>
          {slugError && (
            <p className="-mt-3 text-13 text-danger-primary">
              {t("Workspace URL is already taken!")}
            </p>
          )}
          {invalidSlug && (
            <p className="text-13 text-danger-primary">{t("URLs can contain only ('-') and alphanumeric characters.")}</p>
          )}
          {errors.slug && <span className="text-13 text-danger-primary">{errors.slug.message}</span>}
        </div>
        <hr className="w-full border-strong" />
        <div className="space-y-1">
          <label
            className="text-13 font-medium text-tertiary after:ml-0.5 after:text-danger-primary after:content-['*']"
            htmlFor="organization_size"
          >
            {t("How many people will use this workspace?")}
          </label>
          <div className="w-full">
            <Controller
              name="organization_size"
              control={control}
              rules={{ required: t("This field is required") }}
              render={({ field: { value, onChange } }) => (
                <CustomSelect
                  value={value}
                  onChange={onChange}
                  label={
                    ORGANIZATION_SIZE.find((c) => c === value) ?? (
                      <span className="text-placeholder">
                        {t("Select a range")}
                      </span>
                    )
                  }
                  buttonClassName="border border-subtle bg-layer-2 !shadow-none !rounded-md"
                  input
                >
                  {ORGANIZATION_SIZE.map((item) => (
                    <CustomSelect.Option key={item} value={item}>
                      {item}
                    </CustomSelect.Option>
                  ))}
                </CustomSelect>
              )}
            />
            {errors.organization_size && (
              <span className="text-13 text-danger-primary">{errors.organization_size.message}</span>
            )}
          </div>
        </div>
        <Button variant="primary" type="submit" size="xl" className="w-full" disabled={isButtonDisabled}>
          {isSubmitting ? <Spinner height="20px" width="20px" /> : t("Create workspace")}
        </Button>
      </form>
    </div>
  );
});
