// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotMcp.tsx
// @Desc: Admin UI for the UptimeRobot MCP (Model Context Protocol)
//        integration. Shows the ready-to-paste ``claude_desktop_config.json``
//        block, lists supported capabilities + sample prompts, and runs a
//        one-click connectivity probe against mcp.uptimerobot.com.
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Loader2,
  Copy,
  CheckCircle2,
  AlertCircle,
  ExternalLink,
  Bot,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";

import {
  urAdminGetMcpConfig,
  urAdminTestMcpEndpoint,
  type UptimeMcpConfig,
  type UptimeMcpProbeResult,
} from "@/lib/uptimerobotMcpApi";

export default function CmsUptimeRobotMcp() {
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [config, setConfig] = useState<UptimeMcpConfig | null>(null);
  const [probe, setProbe] = useState<UptimeMcpProbeResult | null>(null);
  const [probing, setProbing] = useState(false);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const data = await urAdminGetMcpConfig();
        if (mounted) setConfig(data);
      } catch (err) {
        if (mounted)
          setError(err instanceof Error ? err.message : "Failed to load MCP config.");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  const onCopy = async (text: string, label: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast({ title: "Copied", description: `${label} copied to clipboard.` });
    } catch {
      toast({
        title: "Copy failed",
        description: "Select the text and copy it manually.",
        variant: "destructive",
      });
    }
  };

  const onTest = async () => {
    setProbing(true);
    setProbe(null);
    try {
      const res = await urAdminTestMcpEndpoint();
      setProbe(res);
    } catch (err) {
      setProbe({
        ok: false,
        http_status: null,
        error_class: "RequestFailed",
        error_message: err instanceof Error ? err.message : "Probe failed.",
      });
    } finally {
      setProbing(false);
    }
  };

  if (loading) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );
  }

  if (error || !config) {
    return (
      <div className="max-w-3xl">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Unable to load MCP settings</AlertTitle>
          <AlertDescription>{error ?? "Unknown error."}</AlertDescription>
        </Alert>
      </div>
    );
  }

  const keyBadge = config.api_key_present ? (
    <Badge className="bg-emerald-100 text-emerald-800 hover:bg-emerald-100">
      API key: {config.api_key_masked ?? "••••"} ({config.api_key_source})
    </Badge>
  ) : (
    <Badge variant="destructive">No API key configured</Badge>
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-start gap-3">
          <div className="rounded-lg bg-primary/10 p-2 text-primary">
            <Bot className="h-5 w-5" />
          </div>
          <div>
            <h2 className="text-xl font-semibold tracking-tight">
              MCP integration
            </h2>
            <p className="text-sm text-muted-foreground">
              Let AI assistants like Claude, Cursor, or ChatGPT control UptimeRobot
              using natural language through the Model Context Protocol.
            </p>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {keyBadge}
          <Button asChild variant="outline" size="sm">
            <a href={config.doc_url} target="_blank" rel="noreferrer">
              <ExternalLink className="mr-1 h-3.5 w-3.5" /> Docs
            </a>
          </Button>
        </div>
      </div>

      {!config.api_key_present ? (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Master API key missing</AlertTitle>
          <AlertDescription className="space-y-1">
            <p>
              The MCP bridge forwards your UptimeRobot API key in the
              <code className="mx-1 rounded bg-muted px-1 py-0.5 text-xs">Authorization</code>
              header. Save the master key first so the copied config is ready to
              paste.
            </p>
            <Link
              to="/admin/cms/uptimerobot/api-settings"
              className="font-medium underline"
            >
              Open API Settings →
            </Link>
          </AlertDescription>
        </Alert>
      ) : null}

      {/* Endpoint summary */}
      <Card>
        <CardHeader>
          <CardTitle>Endpoint</CardTitle>
          <CardDescription>
            Remote MCP server hosted by UptimeRobot. LLM clients connect via an
            <code className="mx-1 rounded bg-muted px-1 py-0.5 text-xs">mcp-remote</code>
            bridge.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex flex-col gap-2 rounded-md border border-border/60 bg-muted/30 p-3 text-sm sm:flex-row sm:items-center sm:justify-between">
            <code className="break-all font-mono text-xs sm:text-sm">
              {config.endpoint}
            </code>
            <Button
              size="sm"
              variant="outline"
              onClick={() => void onCopy(config.endpoint, "Endpoint URL")}
            >
              <Copy className="mr-1 h-3.5 w-3.5" /> Copy
            </Button>
          </div>
          <div className="grid gap-2 text-xs text-muted-foreground sm:grid-cols-2">
            <p>
              <span className="font-medium text-foreground">Auth scheme:</span>{" "}
              {config.auth_scheme}
            </p>
            <p>
              <span className="font-medium text-foreground">Static headers:</span>{" "}
              {Object.entries(config.static_headers)
                .map(([k, v]) => `${k}: ${v}`)
                .join(", ")}
            </p>
          </div>

          <Separator />

          <div className="flex flex-wrap items-center gap-2">
            <Button onClick={onTest} disabled={probing}>
              {probing ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Testing…
                </>
              ) : (
                "Test connection"
              )}
            </Button>
            {probe ? (
              probe.ok ? (
                <span className="flex items-center gap-1 text-sm text-emerald-700">
                  <CheckCircle2 className="h-4 w-4" /> Reachable (HTTP{" "}
                  {probe.http_status ?? "?"})
                </span>
              ) : (
                <span className="flex items-center gap-1 text-sm text-destructive">
                  <AlertCircle className="h-4 w-4" />
                  {probe.error_class ?? "Error"}: {probe.error_message ?? "Unknown"}
                </span>
              )
            ) : null}
          </div>
        </CardContent>
      </Card>

      {/* Config JSON */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between gap-3">
            <div>
              <CardTitle>Claude Desktop / Cursor config</CardTitle>
              <CardDescription>
                Paste this block into your MCP client config file and restart the
                client.
              </CardDescription>
            </div>
            <Button
              size="sm"
              variant="outline"
              onClick={() => void onCopy(config.config_json, "MCP config JSON")}
            >
              <Copy className="mr-1 h-3.5 w-3.5" /> Copy JSON
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <pre className="overflow-auto rounded-lg border border-border/60 bg-zinc-950 p-4 text-xs leading-relaxed text-zinc-100">
            <code>{config.config_json}</code>
          </pre>
          {!config.api_key_present ? (
            <p className="mt-2 text-xs text-muted-foreground">
              The placeholder <code>&lt;your-uptimerobot-api-key&gt;</code> will be
              replaced automatically once you save the master API key.
            </p>
          ) : null}
        </CardContent>
      </Card>

      {/* Capabilities + sample prompts */}
      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>What the AI can do</CardTitle>
            <CardDescription>
              Exposed through the official UptimeRobot MCP server.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {config.capabilities.map((cap) => (
              <div key={cap.id} className="rounded-lg border border-border/50 p-3">
                <p className="text-sm font-medium">{cap.title}</p>
                <p className="mt-1 text-xs text-muted-foreground">
                  {cap.description}
                </p>
              </div>
            ))}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Sample prompts</CardTitle>
            <CardDescription>
              Try these natural-language questions in your AI client.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            {config.sample_prompts.map((prompt) => (
              <div
                key={prompt}
                className="flex items-center justify-between gap-2 rounded-md border border-border/50 bg-muted/30 px-3 py-2 text-sm"
              >
                <span className="flex-1 text-sm">{prompt}</span>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => void onCopy(prompt, "Prompt")}
                >
                  <Copy className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}