import { type Dispatch, type SetStateAction } from "react";
import { ATHENA_MIRRORS } from "@/app/lib/settings";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { ScrollArea } from "../ui/scroll-area";
import {
  CheckCircle2,
  Clock,
  Eye,
  EyeOff,
  Globe,
  HardDrive,
  Key,
  Loader2,
  RefreshCw,
  Server,
  Shield,
  XCircle,
} from "lucide-react";

type ConnectionStatus = {
  testing: boolean;
  ok: boolean | null;
  latencyMs: number | null;
  version: string | null;
  error: string | null;
};

type ConnectionSettingsTabProps = {
  baseUrl: string;
  apiKey: string;
  localBackupApiKey: string;
  pgDumpPath: string;
  pgRestorePath: string;
  isLocalBuild: boolean;
  isDesktopRuntime: boolean;
  isDesktopLocalTarget: boolean;
  localUrl: string;
  setLocalUrl: Dispatch<SetStateAction<string>>;
  localKey: string;
  setLocalKey: Dispatch<SetStateAction<string>>;
  localPgDumpPath: string;
  setLocalPgDumpPath: Dispatch<SetStateAction<string>>;
  localPgRestorePath: string;
  setLocalPgRestorePath: Dispatch<SetStateAction<string>>;
  showKey: boolean;
  setShowKey: Dispatch<SetStateAction<boolean>>;
  connStatus: ConnectionStatus;
  clients: string[];
  clientsLoading: boolean;
  clientsError: string | null;
  bootstrappingKey: boolean;
  onSaveUrl: () => void;
  onSaveKey: () => void;
  onClearKey: () => void;
  onBootstrapLocalKey: () => void;
  onSavePgTools: () => void;
  onTestConnection: (url: string) => void;
  onSetBaseUrl: (url: string) => void;
};

export function ConnectionSettingsTab(props: ConnectionSettingsTabProps) {
  const {
    baseUrl,
    apiKey,
    localBackupApiKey,
    pgDumpPath,
    pgRestorePath,
    isLocalBuild,
    isDesktopRuntime,
    isDesktopLocalTarget,
    localUrl,
    setLocalUrl,
    localKey,
    setLocalKey,
    localPgDumpPath,
    setLocalPgDumpPath,
    localPgRestorePath,
    setLocalPgRestorePath,
    showKey,
    setShowKey,
    connStatus,
    clients,
    clientsLoading,
    clientsError,
    bootstrappingKey,
    onSaveUrl,
    onSaveKey,
    onClearKey,
    onBootstrapLocalKey,
    onSavePgTools,
    onTestConnection,
    onSetBaseUrl,
  } = props;

  return (
    <div className="flex-1 m-0 overflow-hidden">
      <ScrollArea className="h-full">
        <div className="mx-auto max-w-2xl space-y-6 p-6">
          <section className="rounded border border-border bg-card overflow-hidden">
            <div className="border-b border-border px-5 py-4">
              <div className="flex items-center gap-2">
                <Globe className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold">Connection</h3>
              </div>
              <p className="mt-1 text-body-sm text-muted-foreground">
                Select the Athena server instance to connect to.
              </p>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="text-body-sm font-medium text-muted-foreground">
                  Base URL
                </label>
                <div className="mt-1.5 flex gap-2">
                  <Input
                    value={localUrl}
                    onChange={(e) => setLocalUrl(e.target.value)}
                    placeholder="https://athena-db.com"
                    className="flex-1 font-mono text-body-sm"
                  />
                  <Button
                    size="sm"
                    onClick={onSaveUrl}
                    disabled={localUrl === baseUrl}
                    className="h-8"
                  >
                    Save
                  </Button>
                </div>
                <div className="flex flex-wrap gap-1.5 mt-2">
                  {ATHENA_MIRRORS.map((m) => (
                    <button
                      key={m.url}
                      onClick={() => {
                        setLocalUrl(m.url);
                        onSetBaseUrl(m.url);
                        onTestConnection(m.url);
                      }}
                      className={`rounded border px-2 py-1 text-caption transition-colors ${
                        baseUrl === m.url
                          ? "border-primary bg-primary-muted text-primary"
                          : "border-border text-muted-foreground hover:border-foreground-border hover:text-foreground"
                      }`}
                    >
                      {m.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="flex items-center gap-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => onTestConnection(baseUrl)}
                  disabled={connStatus.testing}
                >
                  {connStatus.testing ? (
                    <Loader2 className="h-3 w-3 animate-spin" />
                  ) : (
                    <RefreshCw className="h-3 w-3" />
                  )}
                  Test connection
                </Button>

                {connStatus.ok === true && (
                  <div className="flex items-center gap-2">
                    <Badge variant="success">
                      <CheckCircle2 className="mr-1 h-3 w-3" /> Connected
                    </Badge>
                    {connStatus.version && (
                      <Badge variant="secondary" className="text-caption">
                        v{connStatus.version}
                      </Badge>
                    )}
                    {connStatus.latencyMs !== null && (
                      <span className="flex items-center gap-1 text-caption text-muted-foreground">
                        <Clock className="h-3 w-3" />
                        {connStatus.latencyMs}ms
                      </span>
                    )}
                  </div>
                )}
                {connStatus.ok === false && (
                  <Badge variant="destructive">
                    <XCircle className="mr-1 h-3 w-3" /> Unreachable
                  </Badge>
                )}
              </div>
            </div>
          </section>

          <section className="rounded border border-border bg-card overflow-hidden">
            <div className="border-b border-border px-5 py-4">
              <div className="flex items-center gap-2">
                <Shield className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold">Authentication</h3>
              </div>
              <p className="mt-1 text-body-sm text-muted-foreground">
                Your Athena P12 API key. Stored only in your browser&apos;s
                localStorage.
              </p>
            </div>
            <div className="p-5 space-y-4">
              {isDesktopRuntime && !localBackupApiKey && (
                <div className="rounded border border-primary-border bg-primary-subtle px-3 py-2.5">
                  <p className="text-body-sm text-foreground">
                    Generate a local backup API key for the bundled desktop API
                    (used only for backup and restore proxy calls).
                  </p>
                  <Button
                    variant="outline"
                    size="sm"
                    className="mt-2 h-7"
                    onClick={onBootstrapLocalKey}
                    disabled={bootstrappingKey}
                  >
                    {bootstrappingKey ? (
                      <Loader2 className="h-3 w-3 animate-spin" />
                    ) : (
                      <Shield className="h-3 w-3" />
                    )}
                    Generate local API key
                  </Button>
                </div>
              )}

              {isDesktopRuntime && localBackupApiKey && (
                <div className="rounded border border-success-border bg-success-subtle px-3 py-2 text-body-sm text-success">
                  Local backup API key configured ({localBackupApiKey.length}{" "}
                  chars).
                </div>
              )}

              {isDesktopRuntime &&
                !isDesktopLocalTarget &&
                localBackupApiKey && (
                  <p className="text-body-sm text-muted-foreground">
                    Primary API key below is still used for normal traffic.
                    Backup and restore requests are routed with the local backup
                    key.
                  </p>
                )}

              <div>
                <label className="text-body-sm font-medium text-muted-foreground">
                  API Key
                </label>
                <div className="mt-1.5 flex gap-2">
                  <div className="relative flex-1">
                    <Key className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      type={showKey ? "text" : "password"}
                      value={localKey}
                      onChange={(e) => setLocalKey(e.target.value)}
                      placeholder="ath_xxxx.xxxxx..."
                      className="pl-8 pr-9 font-mono text-body-sm"
                    />
                    <button
                      type="button"
                      onClick={() => setShowKey(!showKey)}
                      className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showKey ? (
                        <EyeOff className="h-3.5 w-3.5" />
                      ) : (
                        <Eye className="h-3.5 w-3.5" />
                      )}
                    </button>
                  </div>
                  <Button
                    size="sm"
                    onClick={onSaveKey}
                    disabled={localKey === apiKey}
                    className="h-8"
                  >
                    Save
                  </Button>
                  {apiKey && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={onClearKey}
                      className="h-8"
                    >
                      Clear
                    </Button>
                  )}
                </div>
              </div>
              {apiKey && (
                <div className="flex items-center gap-2">
                  <CheckCircle2 className="h-3.5 w-3.5 text-success" />
                  <span className="text-body-sm text-success">
                    API key configured ({apiKey.length} chars)
                  </span>
                </div>
              )}
            </div>
          </section>

          <section className="rounded border border-border bg-card overflow-hidden">
            <div className="border-b border-border px-5 py-4">
              <div className="flex items-center gap-2">
                <Server className="h-4 w-4 text-primary" />
                <h3 className="text-sm font-semibold">Client Discovery</h3>
              </div>
              <p className="mt-1 text-body-sm text-muted-foreground">
                Available Postgres clients discovered via your API key.
              </p>
            </div>
            <div className="p-5 space-y-4">
              {clientsLoading && (
                <div className="flex items-center gap-2 text-body-sm text-muted-foreground">
                  <Loader2 className="h-3.5 w-3.5 animate-spin" /> Discovering
                  clients...
                </div>
              )}

              {clientsError && (
                <div className="rounded border border-destructive-border bg-destructive-subtle px-3 py-2 text-body-sm text-destructive">
                  {clientsError}
                </div>
              )}

              {!clientsLoading && !apiKey && (
                <p className="text-body-sm text-muted-foreground">
                  Set your API key above to discover clients automatically.
                </p>
              )}

              {clients.length > 0 && (
                <div className="rounded border border-border overflow-hidden">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border bg-muted-panel">
                        <th className="px-4 py-2 text-left text-body-sm font-medium text-muted-foreground">
                          #
                        </th>
                        <th className="px-4 py-2 text-left text-body-sm font-medium text-muted-foreground">
                          Client name
                        </th>
                        <th className="px-4 py-2 text-right text-body-sm font-medium text-muted-foreground">
                          Status
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border-muted">
                      {clients.map((client, i) => (
                        <tr key={client} className="hover:bg-accent-muted">
                          <td className="px-4 py-2 text-body-sm text-muted-foreground tabular-nums">
                            {i + 1}
                          </td>
                          <td className="px-4 py-2 text-body-sm font-medium text-foreground font-mono">
                            {client}
                          </td>
                          <td className="px-4 py-2 text-right">
                            <Badge variant="success" className="text-caption">
                              available
                            </Badge>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {!clientsLoading &&
                apiKey &&
                clients.length === 0 &&
                !clientsError && (
                  <p className="text-body-sm text-muted-foreground">
                    No clients found.
                  </p>
                )}
            </div>
          </section>

          {isLocalBuild && (
            <section className="rounded border border-border bg-card overflow-hidden">
              <div className="border-b border-border px-5 py-4">
                <div className="flex items-center gap-2">
                  <HardDrive className="h-4 w-4 text-primary" />
                  <h3 className="text-sm font-semibold">Local Backup Tools</h3>
                </div>
                <p className="mt-1 text-body-sm text-muted-foreground">
                  Override pg_dump and pg_restore path hints for local backup
                  and restore operations.
                </p>
              </div>
              <div className="p-5 space-y-4">
                <div>
                  <label className="text-body-sm font-medium text-muted-foreground">
                    pg_dump path
                  </label>
                  <Input
                    value={localPgDumpPath}
                    onChange={(e) => setLocalPgDumpPath(e.target.value)}
                    placeholder="C:\\Program Files\\PostgreSQL\\18\\bin\\pg_dump.exe"
                    className="mt-1.5 font-mono text-body-sm"
                  />
                </div>
                <div>
                  <label className="text-body-sm font-medium text-muted-foreground">
                    pg_restore path
                  </label>
                  <Input
                    value={localPgRestorePath}
                    onChange={(e) => setLocalPgRestorePath(e.target.value)}
                    placeholder="C:\\Program Files\\PostgreSQL\\18\\bin\\pg_restore.exe"
                    className="mt-1.5 font-mono text-body-sm"
                  />
                </div>
                <div className="flex items-center justify-end">
                  <Button
                    size="sm"
                    onClick={onSavePgTools}
                    disabled={
                      localPgDumpPath.trim() === pgDumpPath.trim() &&
                      localPgRestorePath.trim() === pgRestorePath.trim()
                    }
                  >
                    Save tool paths
                  </Button>
                </div>
              </div>
            </section>
          )}
        </div>
      </ScrollArea>
    </div>
  );
}
