"use client";

import { useState } from "react";
import { useSettings } from "@/app/lib/settings";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "./ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Copy } from "lucide-react";
import { toast } from "sonner";
import CodeBlock from "./ui/code-block";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  clientName: string | null;
};

export default function ConnectionModal({
  open,
  onOpenChange,
  clientName,
}: Props) {
  const { baseUrl, apiKey } = useSettings();
  const [tab, setTab] = useState("mcp");

  const copy = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success("Copied to clipboard");
  };

  const mcpConfig = `{
  "mcpServers": {
    "athena": {
      "command": "npx",
      "args": [
        "@anthropic/mcp-client",
        "--url",
        "${baseUrl}"
      ],
      "env": {
        "ATHENA_API_KEY": "${apiKey || "<your-api-key>"}",
        "ATHENA_CLIENT": "${clientName || "<client-name>"}"
      }
    }
  }
}`;

  const jsExample = `import { AthenaClient } from "@xylex-group/athena";

const client = new AthenaClient({
  baseUrl: "${baseUrl}",
  apiKey: "${apiKey || "<your-api-key>"}",
  clientName: "${clientName || "<client-name>"}",
});

const rows = await client.fetch("users");
console.log(rows);`;

  const rustExample = `use athena_rs::AthenaClient;

let client = AthenaClient::builder()
    .base_url("${baseUrl}")
    .api_key("${apiKey || "<your-api-key>"}")
    .client_name("${clientName || "<client-name>"}")
    .build()?;

let rows = client.fetch("users").await?;
println!("{:?}", rows);`;

  const curlExample = `curl -X POST "${baseUrl}/gateway/fetch" \\
  -H "Content-Type: application/json" \\
  -H "apikey: ${apiKey || "<your-api-key>"}" \\
  -H "X-Athena-Client: ${clientName || "<client-name>"}" \\
  -d '{"table_name": "users", "columns": ["*"]}'`;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[85vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="break-words">
            Connect to your project
          </DialogTitle>
          <DialogDescription className="break-words whitespace-normal">
            Get the connection strings and environment variables for your
            project.
          </DialogDescription>
        </DialogHeader>

        <Tabs
          value={tab}
          onValueChange={setTab}
          className="flex-1 min-h-0 flex flex-col"
        >
          <TabsList className="w-full justify-start flex-wrap">
            <TabsTrigger value="mcp">MCP</TabsTrigger>
            <TabsTrigger value="js" className="text-body-sm">
              @xylex-group/athena
            </TabsTrigger>
            <TabsTrigger value="rust">athena_rs</TabsTrigger>
            <TabsTrigger value="curl">cURL</TabsTrigger>
            <TabsTrigger value="env">API Keys</TabsTrigger>
          </TabsList>

          <div className="flex-1 overflow-auto min-h-0 mt-2">
            <TabsContent value="mcp" className="space-y-3 m-0">
              <p className="text-body-sm text-muted-foreground break-words">
                Add to your MCP client configuration:
              </p>
              <CodeBlock code={mcpConfig} language="json" showCopy />
            </TabsContent>

            <TabsContent value="js" className="space-y-3 m-0">
              <div className="flex flex-wrap items-center gap-2">
                <p className="text-body-sm text-muted-foreground">Install:</p>
                <code className="text-body-sm font-mono bg-muted px-2 py-0.5 rounded break-all">
                  npm install @xylex-group/athena
                </code>
              </div>
              <CodeBlock code={jsExample} language="javascript" showCopy />
            </TabsContent>

            <TabsContent value="rust" className="space-y-3 m-0">
              <div className="flex flex-wrap items-center gap-2">
                <p className="text-body-sm text-muted-foreground">
                  Add to Cargo.toml:
                </p>
                <code className="text-body-sm font-mono bg-muted px-2 py-0.5 rounded break-all">
                  athena_rs = &quot;*&quot;
                </code>
              </div>
              <CodeBlock code={rustExample} language="rust" showCopy />
            </TabsContent>

            <TabsContent value="curl" className="space-y-3 m-0">
              <p className="text-body-sm text-muted-foreground">
                Direct API access:
              </p>
              <CodeBlock code={curlExample} language="bash" showCopy />
            </TabsContent>

            <TabsContent value="env" className="space-y-4 m-0">
              <div className="space-y-3">
                <div className="flex items-center justify-between rounded border border-border bg-card px-4 py-3 gap-3">
                  <div className="min-w-0 flex-1">
                    <p className="text-body-sm text-muted-foreground">
                      Project URL
                    </p>
                    <code className="text-body-sm font-mono text-foreground break-all">
                      {baseUrl}
                    </code>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => copy(baseUrl)}
                    className="h-7 shrink-0"
                  >
                    <Copy className="h-3 w-3" /> Copy
                  </Button>
                </div>

                <div className="flex items-center justify-between rounded border border-border bg-card px-4 py-3 gap-3">
                  <div className="min-w-0 flex-1">
                    <p className="text-body-sm text-muted-foreground">
                      API Key
                    </p>
                    <code className="text-body-sm font-mono text-foreground break-all">
                      {apiKey ? `${apiKey.slice(0, 20)}...` : "Not configured"}
                    </code>
                  </div>
                  {apiKey && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => copy(apiKey)}
                      className="h-7 shrink-0"
                    >
                      <Copy className="h-3 w-3" /> Copy
                    </Button>
                  )}
                </div>

                {clientName && (
                  <div className="flex items-center justify-between rounded border border-border bg-card px-4 py-3 gap-3">
                    <div className="min-w-0 flex-1">
                      <p className="text-body-sm text-muted-foreground">
                        Client
                      </p>
                      <code className="text-body-sm font-mono text-foreground break-all">
                        {clientName}
                      </code>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => copy(clientName)}
                      className="h-7 shrink-0"
                    >
                      <Copy className="h-3 w-3" /> Copy
                    </Button>
                  </div>
                )}
              </div>
              <p className="text-body-sm text-muted-foreground break-words">
                For secret keys, see API settings.
              </p>
            </TabsContent>
          </div>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
