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

import { observer } from "mobx-react";
import { EUserPermissions, EUserPermissionsLevel } from "@pi-dash/constants";
import { useTranslation } from "@pi-dash/i18n";
import { setPromiseToast } from "@pi-dash/propel/toast";
import { ToggleSwitch } from "@pi-dash/ui";
// components
import { NotAuthorizedView } from "@/components/auth-screens/not-authorized-view";
import { PageHead } from "@/components/core/page-title";
import { ProjectStateRoot } from "@/components/project-states";
import { SettingsContentWrapper } from "@/components/settings/content-wrapper";
import { SettingsBoxedControlItem } from "@/components/settings/boxed-control-item";
import { SettingsHeading } from "@/components/settings/heading";
// hook
import { useProject } from "@/hooks/store/use-project";
import { useUserPermissions } from "@/hooks/store/user";
// local imports
import type { Route } from "./+types/page";
import { StatesProjectSettingsHeader } from "./header";

function StatesSettingsPage({ params }: Route.ComponentProps) {
  const { workspaceSlug, projectId } = params;
  // store
  const { currentProjectDetails, getProjectById, updateProject } = useProject();
  const { workspaceUserInfo, allowPermissions } = useUserPermissions();

  const { t } = useTranslation();

  // derived values
  const pageTitle = currentProjectDetails?.name ? `${currentProjectDetails?.name} - States` : undefined;
  const canPerformProjectMemberActions = allowPermissions(
    [EUserPermissions.ADMIN, EUserPermissions.MEMBER],
    EUserPermissionsLevel.PROJECT
  );
  const isAdmin = allowPermissions([EUserPermissions.ADMIN], EUserPermissionsLevel.PROJECT, workspaceSlug, projectId);
  const membersCanEditStates = getProjectById(projectId)?.members_can_edit_states ?? true;

  const handleMembersCanEditStatesToggle = () => {
    if (!workspaceSlug || !projectId) return;
    const promise = updateProject(workspaceSlug, projectId, {
      members_can_edit_states: !membersCanEditStates,
    });
    setPromiseToast(promise, {
      loading: t("Updating project setting..."),
      success: {
        title: t("Success!"),
        message: () => t("Project setting updated."),
      },
      error: {
        title: t("Error!"),
        message: () => t("Something went wrong while updating the project setting. Please try again."),
      },
    });
  };

  if (workspaceUserInfo && !canPerformProjectMemberActions) {
    return <NotAuthorizedView section="settings" isProjectView className="h-auto" />;
  }

  return (
    <SettingsContentWrapper header={<StatesProjectSettingsHeader />}>
      <PageHead title={pageTitle} />
      <div className="w-full">
        <SettingsHeading
          title={t("States")}
          description={t("Define and customize workflow states to track the progress of your work items.")}
        />
        {isAdmin && (
          <div className="mt-6">
            <SettingsBoxedControlItem
              title={t("Let members edit states")}
              description={t("When enabled, project members can add, edit, reorder, and delete workflow states. When disabled, only admins can manage states.")}
              control={
                <ToggleSwitch value={membersCanEditStates} onChange={handleMembersCanEditStatesToggle} size="sm" />
              }
            />
          </div>
        )}
        <div className="mt-6">
          <ProjectStateRoot workspaceSlug={workspaceSlug} projectId={projectId} />
        </div>
      </div>
    </SettingsContentWrapper>
  );
}

export default observer(StatesSettingsPage);
