import type { ReactNode } from "react";

export const INPUT_CLASS = "app-input";
export const LABEL_CLASS = "app-label";
export const PANEL_CLASS = "app-surface p-6 space-y-5";
export const PANEL_STRONG_CLASS = "app-surface-strong p-6 space-y-6";
export const PRIMARY_BUTTON_CLASS =
  "rounded-xl bg-brand-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-700 disabled:opacity-50";
export const SECONDARY_BUTTON_CLASS =
  "rounded-xl border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50 disabled:opacity-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-800";
export const CHECKBOX_ROW_CLASS =
  "flex items-center gap-2 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700 dark:border-gray-700 dark:bg-gray-900/70 dark:text-gray-300";

export type Provider = "openai" | "azure";
export type ImageProvider = "dalle" | "gemini";
export type RuntimeSecretSource = "environment" | "database" | "none";
export type UrlParsedType = "completions" | "responses" | null;

export type RuntimeSecretStatus = {
  configured: boolean;
  activeSource: RuntimeSecretSource;
  hasStoredValue: boolean;
  envVarNames: string[];
};

export type RuntimeSecrets = {
  azureOpenAiApiKey: RuntimeSecretStatus;
  azureDalleApiKey: RuntimeSecretStatus;
  geminiApiKey: RuntimeSecretStatus;
  smtpPassword: RuntimeSecretStatus;
  anonymizationSeed: RuntimeSecretStatus;
};

export type ParsedAzureUrl = {
  endpoint: string;
  apiVersion: string;
  deployment: string | null;
  urlType: "completions" | "responses";
};

export type SaveResult = {
  ok: boolean;
  error?: string;
};

export type GeminiTestResult = {
  ok: boolean;
  model?: string;
  error?: string;
};

export const ALL_ROLES = ["ADMIN", "MANAGER", "CONTROLLER", "USER", "VIEWER"] as const;
export type SystemRole = (typeof ALL_ROLES)[number];

export interface ScoreWeights {
  skillDepth: number;
  skillBreadth: number;
  costEfficiency: number;
  chargeability: number;
  experience: number;
}

export function parseAzureUrl(raw: string): ParsedAzureUrl | null {
  try {
    const url = new URL(raw);
    const endpoint = `${url.protocol}//${url.host}`;
    const apiVersion = url.searchParams.get("api-version") ?? "2025-01-01-preview";
    const completionsMatch = url.pathname.match(/\/openai\/deployments\/([^/]+)\//);

    if (completionsMatch) {
      return { endpoint, apiVersion, deployment: completionsMatch[1]!, urlType: "completions" };
    }

    if (url.pathname.includes("/openai/responses")) {
      return { endpoint, apiVersion, deployment: null, urlType: "responses" };
    }

    return null;
  } catch {
    return null;
  }
}

function getSecretStatusTone(source: RuntimeSecretSource): string {
  if (source === "environment") {
    return "border-green-200 bg-green-50 text-green-800 dark:border-green-800 dark:bg-green-950/30 dark:text-green-300";
  }
  if (source === "database") {
    return "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-300";
  }
  return "border-gray-200 bg-gray-50 text-gray-700 dark:border-gray-700 dark:bg-gray-900/60 dark:text-gray-300";
}

function getSecretStatusLabel(source: RuntimeSecretSource): string {
  if (source === "environment") return "Environment";
  if (source === "database") return "Legacy DB";
  return "Missing";
}

export function RuntimeSecretCard({
  title,
  description,
  secret,
  optionalNote,
}: {
  title: string;
  description: ReactNode;
  secret: RuntimeSecretStatus;
  optionalNote?: ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-gray-200 bg-gray-50/80 p-4 dark:border-gray-700 dark:bg-gray-900/50">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100">{title}</h3>
          <p className="mt-1 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
            {description}
          </p>
        </div>
        <span
          className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] ${getSecretStatusTone(secret.activeSource)}`}
        >
          {getSecretStatusLabel(secret.activeSource)}
        </span>
      </div>

      <div className="mt-3 space-y-2 text-xs text-gray-600 dark:text-gray-300">
        <p>
          Runtime status:{" "}
          <span className="font-medium">
            {secret.configured ? "configured" : "not configured"}
          </span>
        </p>
        <p>
          Provision via{" "}
          {secret.envVarNames.map((name) => (
            <code key={name} className="mr-1 font-mono">
              {name}
            </code>
          ))}
        </p>
        {optionalNote ? <p>{optionalNote}</p> : null}
        {secret.activeSource === "environment" && secret.hasStoredValue ? (
          <p className="text-amber-700 dark:text-amber-400">
            An older database value still exists, but the environment value currently overrides it.
          </p>
        ) : null}
        {secret.activeSource === "database" ? (
          <p className="text-amber-700 dark:text-amber-400">
            Runtime currently still depends on a legacy database secret. Migrate it to deployment
            secrets and clear the stored value afterwards.
          </p>
        ) : null}
        {secret.activeSource === "none" ? (
          <p className="text-gray-500 dark:text-gray-400">
            No runtime secret is available yet. The related integration will stay disabled or fail
            connectivity checks until the deployment secret is set.
          </p>
        ) : null}
      </div>
    </div>
  );
}
