import { useState } from "react";
import {
  ApiKeyClientConfig,
  ApiKeyRecord,
  ApiKeyRightRecord,
  createApiKey,
  createApiKeyRight,
  deleteApiKey,
  deleteApiKeyRight,
  deleteClientApiKeyConfig,
  listApiKeyRights,
  listApiKeys,
  loadApiKeyConfig,
  setClientApiKeyConfig,
  setGlobalApiKeyConfig,
  updateApiKey,
} from "@/app/lib/api";
import { RunAction } from "@/app/hooks/useActionFeedback";

type UseApiKeysAdminProps = {
  adminApiKey: string;
  runAction: RunAction;
};

export function useApiKeysAdmin({
  adminApiKey,
  runAction,
}: UseApiKeysAdminProps) {
  const [apiKeys, setApiKeys] = useState<ApiKeyRecord[]>([]);
  const [rights, setRights] = useState<ApiKeyRightRecord[]>([]);
  const [apiKeyClientsConfig, setApiKeyClientsConfig] = useState<ApiKeyClientConfig[]>([]);
  const [globalApiKeyEnforced, setGlobalApiKeyEnforced] = useState(false);
  const [createdApiKeySecret, setCreatedApiKeySecret] = useState("");
  const [newApiKeyJson, setNewApiKeyJson] = useState(
    JSON.stringify(
      {
        name: "studio-key",
        description: "Generated in Athena Studio",
        client_name: null,
        rights: ["management.read"],
      },
      null,
      2,
    ),
  );
  const [patchApiKeyId, setPatchApiKeyId] = useState("");
  const [patchApiKeyJson, setPatchApiKeyJson] = useState(
    JSON.stringify(
      {
        is_active: true,
        rights: ["management.read"],
      },
      null,
      2,
    ),
  );
  const [deleteApiKeyId, setDeleteApiKeyId] = useState("");
  const [newRightName, setNewRightName] = useState("management.read");
  const [newRightDescription, setNewRightDescription] = useState("");
  const [deleteRightId, setDeleteRightId] = useState("");
  const [clientOverrideName, setClientOverrideName] = useState("");
  const [clientOverrideEnforced, setClientOverrideEnforced] = useState(true);
  const [deleteClientOverrideName, setDeleteClientOverrideName] = useState("");

  const reloadApiKeys = async () => {
    if (!adminApiKey.trim()) return;
    const [apiKeysData, rightsData, configData] = await Promise.all([
      listApiKeys(adminApiKey.trim()),
      listApiKeyRights(adminApiKey.trim()),
      loadApiKeyConfig(adminApiKey.trim()),
    ]);
    setApiKeys(apiKeysData);
    setRights(rightsData);
    setApiKeyClientsConfig(configData.clients);
    setGlobalApiKeyEnforced(configData.global?.enforce_api_keys ?? false);
  };

  const handleOpen = () => runAction("Loaded API keys", reloadApiKeys);
  const handleReload = () => runAction("Reloaded API keys", reloadApiKeys);

  const handleCreateApiKey = () =>
    runAction("Created API key", async () => {
      const result = await createApiKey(
        JSON.parse(newApiKeyJson) as {
          name: string;
          description?: string;
          client_name?: string;
          expires_at?: string;
          rights?: string[];
        },
        adminApiKey.trim(),
      );
      setCreatedApiKeySecret(result.api_key ?? "");
      await reloadApiKeys();
    });

  const handleUpdateApiKey = () =>
    runAction("Updated API key", async () => {
      await updateApiKey(
        patchApiKeyId.trim(),
        JSON.parse(patchApiKeyJson) as {
          name?: string;
          description?: string | null;
          client_name?: string | null;
          expires_at?: string | null;
          is_active?: boolean;
          rights?: string[];
        },
        adminApiKey.trim(),
      );
      await reloadApiKeys();
    });

  const handleDeleteApiKey = () =>
    runAction("Deleted API key", async () => {
      await deleteApiKey(deleteApiKeyId.trim(), adminApiKey.trim());
      await reloadApiKeys();
    });

  const handleCreateRight = () =>
    runAction("Created API key right", async () => {
      await createApiKeyRight(
        newRightName.trim(),
        newRightDescription.trim(),
        adminApiKey.trim(),
      );
      await reloadApiKeys();
    });

  const handleDeleteRight = () =>
    runAction("Deleted API key right", async () => {
      await deleteApiKeyRight(deleteRightId.trim(), adminApiKey.trim());
      await reloadApiKeys();
    });

  const handleSaveGlobalConfig = () =>
    runAction("Updated global API key config", async () => {
      await setGlobalApiKeyConfig(globalApiKeyEnforced, adminApiKey.trim());
      await reloadApiKeys();
    });

  const handleSaveClientOverride = () =>
    runAction("Updated client override", async () => {
      await setClientApiKeyConfig(
        clientOverrideName.trim(),
        clientOverrideEnforced,
        adminApiKey.trim(),
      );
      await reloadApiKeys();
    });

  const handleDeleteClientOverride = () =>
    runAction("Deleted client override", async () => {
      await deleteClientApiKeyConfig(deleteClientOverrideName.trim(), adminApiKey.trim());
      await reloadApiKeys();
    });

  return {
    apiKeys,
    rights,
    apiKeyClientsConfig,
    globalApiKeyEnforced,
    setGlobalApiKeyEnforced,
    createdApiKeySecret,
    newApiKeyJson,
    setNewApiKeyJson,
    patchApiKeyId,
    setPatchApiKeyId,
    patchApiKeyJson,
    setPatchApiKeyJson,
    deleteApiKeyId,
    setDeleteApiKeyId,
    newRightName,
    setNewRightName,
    newRightDescription,
    setNewRightDescription,
    deleteRightId,
    setDeleteRightId,
    clientOverrideName,
    setClientOverrideName,
    clientOverrideEnforced,
    setClientOverrideEnforced,
    deleteClientOverrideName,
    setDeleteClientOverrideName,
    handleOpen,
    handleReload,
    handleCreateApiKey,
    handleUpdateApiKey,
    handleDeleteApiKey,
    handleCreateRight,
    handleDeleteRight,
    handleSaveGlobalConfig,
    handleSaveClientOverride,
    handleDeleteClientOverride,
  };
}
