import { useEffect, useState } from "react";
import type { ApiSettings } from "../../types";
import { fetchGroups, fetchUsers } from "../../api/admin";
import type { MailProfileScope } from "@govoplan/mail-webui";
import { MailProfileScopeManager, type MailProfileTargetOption } from "@govoplan/mail-webui";
import AdminPageLayout from "./components/AdminPageLayout";
import { adminErrorMessage } from "./adminUtils";

type Props = {
  settings: ApiSettings;
  scopeType: Extract<MailProfileScope, "system" | "tenant" | "user" | "group">;
  canWriteProfiles: boolean;
  canManageCredentials: boolean;
  canWritePolicy: boolean;
};

const copy: Record<Props["scopeType"], { title: string; description: string; targetLabel?: string; profileTitle: string; policyTitle: string }> = {
  system: {
    title: "System mail profiles",
    description: "Instance-level mail server profiles and policy limits inherited by every tenant.",
    profileTitle: "System profiles",
    policyTitle: "System mail profile policy"
  },
  tenant: {
    title: "Tenant mail profiles",
    description: "Tenant-level mail server profiles and policy limits for the active tenant.",
    profileTitle: "Tenant profiles",
    policyTitle: "Tenant mail profile policy"
  },
  user: {
    title: "User mail profiles",
    description: "User-scoped profiles and policy limits for campaign owners in the active tenant.",
    targetLabel: "User",
    profileTitle: "User profiles",
    policyTitle: "User mail profile policy"
  },
  group: {
    title: "Group mail profiles",
    description: "Group-scoped profiles and policy limits for group-owned campaigns in the active tenant.",
    targetLabel: "Group",
    profileTitle: "Group profiles",
    policyTitle: "Group mail profile policy"
  }
};

export default function MailProfilesPanel({ settings, scopeType, canWriteProfiles, canManageCredentials, canWritePolicy }: Props) {
  const [targets, setTargets] = useState<MailProfileTargetOption[]>([]);
  const [loadingTargets, setLoadingTargets] = useState(scopeType === "user" || scopeType === "group");
  const [targetError, setTargetError] = useState("");

  useEffect(() => { void loadTargets(); }, [settings.accessToken, settings.apiBaseUrl, settings.apiKey, scopeType]);

  async function loadTargets() {
    if (scopeType !== "user" && scopeType !== "group") {
      setTargets([]);
      setLoadingTargets(false);
      setTargetError("");
      return;
    }
    setLoadingTargets(true);
    setTargetError("");
    try {
      if (scopeType === "user") {
        const users = await fetchUsers(settings);
        setTargets(users.map((user) => ({
          id: user.id,
          label: user.display_name || user.email,
          secondary: user.display_name ? user.email : null
        })));
      } else {
        const groups = await fetchGroups(settings);
        setTargets(groups.map((group) => ({
          id: group.id,
          label: group.name,
          secondary: group.slug
        })));
      }
    } catch (err) {
      setTargets([]);
      setTargetError(adminErrorMessage(err));
    } finally {
      setLoadingTargets(false);
    }
  }

  const labels = copy[scopeType];

  return (
    <AdminPageLayout title={labels.title} description={labels.description} loading={loadingTargets} error={targetError}>
      <MailProfileScopeManager
        settings={settings}
        scopeType={scopeType}
        targetOptions={targets}
        targetLabel={labels.targetLabel}
        profileTitle={labels.profileTitle}
        policyTitle={labels.policyTitle}
        canWriteProfiles={canWriteProfiles}
        canManageCredentials={canManageCredentials}
        canWritePolicy={canWritePolicy}
      />
    </AdminPageLayout>
  );
}
