import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button, Card, Descriptions, Space, Switch, Typography } from "antd";
import {
  getAdminSettings,
  getInstallSecrets,
  patchAdminSettings,
  revealInstallSecret,
} from "../api/adminApi";

export function AdminSecurityPanel(): JSX.Element {
  const queryClient = useQueryClient();
  const { data, isLoading } = useQuery({
    queryKey: ["admin-settings"],
    queryFn: getAdminSettings
  });
  const { data: installSecrets, isLoading: installSecretsLoading } = useQuery({
    queryKey: ["install-secrets"],
    queryFn: getInstallSecrets
  });
  const mutation = useMutation({
    mutationFn: (values: Record<string, unknown>) => patchAdminSettings(values),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-settings"] });
    }
  });
  const revealMutation = useMutation({
    mutationFn: (key: "database_password" | "jwt_access_secret" | "jwt_refresh_pepper" | "s3_secret_key") =>
      revealInstallSecret(key)
  });

  if (isLoading || !data || installSecretsLoading || !installSecrets) {
    return <p className="wesp-admin-block">Loading security settings...</p>;
  }

  const values = data.values;
  const locks = data.locks;

  function toggle(key: string, checked: boolean): void {
    void mutation.mutate({ [key]: checked });
  }

  return (
    <div className="wesp-admin-grid">
      <Typography.Title level={4} style={{ margin: 0 }}>
        Security Settings
      </Typography.Title>
      <Card>
        <Space direction="vertical" size="middle">
          <Space>
            <Switch
              checked={Boolean(values.enable_rate_limit)}
              disabled={Boolean(locks.enable_rate_limit)}
              onChange={(checked) => toggle("enable_rate_limit", checked)}
            />
            <span>Enable rate limits</span>
          </Space>
          <Space>
            <Switch
              checked={Boolean(values.enable_docs)}
              disabled={Boolean(locks.enable_docs)}
              onChange={(checked) => toggle("enable_docs", checked)}
            />
            <span>Enable API docs</span>
          </Space>
          <Space>
            <Switch
              checked={Boolean(values.cookie_secure)}
              disabled={Boolean(locks.cookie_secure)}
              onChange={(checked) => toggle("cookie_secure", checked)}
            />
            <span>Secure refresh cookie</span>
          </Space>
        </Space>
      </Card>
      <Card title="Install Secrets">
        <Typography.Paragraph>
          Secrets are generated and locked on first bootstrap.
        </Typography.Paragraph>
        <Descriptions column={1} size="small">
          <Descriptions.Item label="Database">
            {installSecrets.database.user}@{installSecrets.database.host}:{installSecrets.database.port}/
            {installSecrets.database.database}
          </Descriptions.Item>
          <Descriptions.Item label="Connection">
            {installSecrets.connection_string_masked || "not configured"}
          </Descriptions.Item>
        </Descriptions>
        <Space wrap>
          <Button onClick={() => void revealMutation.mutate("database_password")}>Reveal DB password</Button>
          <Button onClick={() => void revealMutation.mutate("jwt_access_secret")}>Reveal JWT access secret</Button>
          <Button onClick={() => void revealMutation.mutate("jwt_refresh_pepper")}>Reveal JWT pepper</Button>
        </Space>
        {revealMutation.data ? (
          <Typography.Paragraph copyable={{ text: revealMutation.data.value }} style={{ marginTop: 12 }}>
            {revealMutation.data.key}: <code>{revealMutation.data.value}</code>
          </Typography.Paragraph>
        ) : null}
      </Card>
    </div>
  );
}
