"use client";

import { useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { useAuth } from "@/hooks/useAuth";
import { formatDate } from "@/lib/utils";
import { Copy, Check, KeyRound, Plus, Trash2, ShieldAlert } from "lucide-react";

interface PermissionDef {
  key: string;
  label: string;
  group: string;
}

interface ApiKey {
  id: string;
  name: string;
  prefix: string;
  permissions: string[];
  createdByPubkey: string;
  lastUsedAt: string | null;
  revokedAt: string | null;
  createdAt: string;
}

export default function ApiKeysPage() {
  const { can } = useAuth();
  const allowed = can("api_keys.manage");

  const [permissions, setPermissions] = useState<PermissionDef[]>([]);
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const [name, setName] = useState("");
  const [selected, setSelected] = useState<Record<string, boolean>>({});
  const [creating, setCreating] = useState(false);
  const [revealedKey, setRevealedKey] = useState<{ name: string; key: string } | null>(null);
  const [copied, setCopied] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const [registry, list] = await Promise.all([
        api.getPermissionRegistry(),
        api.getApiKeys(),
      ]);
      setPermissions(registry.permissions);
      setKeys(list);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (allowed) load();
    else setLoading(false);
  }, [allowed]);

  const groups = useMemo(() => {
    const order: string[] = [];
    const byGroup: Record<string, PermissionDef[]> = {};
    for (const perm of permissions) {
      if (!byGroup[perm.group]) {
        byGroup[perm.group] = [];
        order.push(perm.group);
      }
      byGroup[perm.group].push(perm);
    }
    return order.map((group) => ({ group, perms: byGroup[group] }));
  }, [permissions]);

  const selectedKeys = useMemo(
    () => Object.entries(selected).filter(([, v]) => v).map(([k]) => k),
    [selected]
  );

  const toggle = (key: string) => {
    setSelected((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const handleCreate = async () => {
    if (!name.trim() || selectedKeys.length === 0) return;
    setCreating(true);
    setError("");
    try {
      const created = await api.createApiKey({ name: name.trim(), permissions: selectedKeys });
      setRevealedKey({ name: created.name, key: created.key });
      setCopied(false);
      setName("");
      setSelected({});
      await load();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setCreating(false);
    }
  };

  const handleRevoke = async (id: string) => {
    setError("");
    try {
      await api.revokeApiKey(id);
      await load();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleCopy = async () => {
    if (!revealedKey) return;
    try {
      await navigator.clipboard.writeText(revealedKey.key);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      // ignore
    }
  };

  if (!allowed) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">
          You do not have permission to manage API keys.
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading API keys...</div>
      </div>
    );
  }

  const labelFor = (key: string) => permissions.find((p) => p.key === key)?.label ?? key;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-on-surface">API Keys</h1>
        <p className="text-on-surface/60 text-sm mt-1">
          Create scoped API keys for programmatic access. A key is shown in full
          only once, right after you create it, so copy it immediately.
        </p>
      </div>

      {error && <p className="text-error text-sm">{error}</p>}

      {revealedKey && (
        <div className="bg-primary-container/10 border border-primary/30 rounded-xl p-6 space-y-3">
          <div className="flex items-center gap-2 text-primary font-semibold">
            <ShieldAlert size={18} />
            Copy your new key now — it won&apos;t be shown again
          </div>
          <p className="text-on-surface/70 text-sm">
            Key for <span className="font-semibold">{revealedKey.name}</span>:
          </p>
          <div className="flex items-center gap-2">
            <code className="flex-1 bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 font-mono text-sm break-all">
              {revealedKey.key}
            </code>
            <button
              onClick={handleCopy}
              className="flex items-center gap-2 px-4 py-3 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity whitespace-nowrap"
            >
              {copied ? <Check size={16} /> : <Copy size={16} />}
              {copied ? "Copied" : "Copy"}
            </button>
          </div>
          <button
            onClick={() => setRevealedKey(null)}
            className="text-on-surface/50 text-sm hover:text-on-surface transition-colors"
          >
            I&apos;ve saved it, dismiss
          </button>
        </div>
      )}

      {/* Create form */}
      <div className="bg-surface-container-low rounded-xl p-6 space-y-5">
        <h2 className="text-sm font-semibold text-on-surface/70">Create API Key</h2>

        <div>
          <label className="block text-xs font-bold uppercase tracking-widest text-on-surface-variant mb-2">
            Name
          </label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="e.g. Blog publishing bot"
            maxLength={100}
            className="w-full bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-1 focus:ring-primary/40"
          />
        </div>

        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-on-surface-variant mb-3">
            Permissions
          </p>
          <div className="space-y-4">
            {groups.map(({ group, perms }) => (
              <div key={group}>
                <p className="text-xs font-bold uppercase tracking-wide text-on-surface/40 mb-2">
                  {group}
                </p>
                <div className="grid sm:grid-cols-2 gap-2">
                  {perms.map((perm) => (
                    <label
                      key={perm.key}
                      className="flex items-start gap-2 cursor-pointer text-sm text-on-surface"
                    >
                      <input
                        type="checkbox"
                        checked={!!selected[perm.key]}
                        onChange={() => toggle(perm.key)}
                        className="mt-0.5 h-4 w-4 accent-primary cursor-pointer"
                      />
                      <span>
                        {perm.label}
                        <span className="block text-on-surface/40 text-xs font-mono">
                          {perm.key}
                        </span>
                      </span>
                    </label>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        <button
          onClick={handleCreate}
          disabled={!name.trim() || selectedKeys.length === 0 || creating}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50"
        >
          <Plus size={16} />
          {creating ? "Creating..." : "Create API Key"}
        </button>
      </div>

      {/* Existing keys */}
      <div className="space-y-3">
        <h2 className="text-sm font-semibold text-on-surface/70">Existing Keys</h2>
        {keys.length === 0 ? (
          <div className="bg-surface-container-low rounded-xl p-8 text-center">
            <KeyRound size={32} className="text-on-surface-variant/30 mx-auto mb-3" />
            <p className="text-on-surface-variant/60 text-sm">No API keys yet.</p>
          </div>
        ) : (
          keys.map((key) => (
            <div
              key={key.id}
              className={`bg-surface-container-low rounded-xl p-6 ${key.revokedAt ? "opacity-60" : ""}`}
            >
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <h3 className="font-semibold text-on-surface">{key.name}</h3>
                    {key.revokedAt && (
                      <span className="text-xs font-bold text-error bg-error/10 px-2 py-0.5 rounded-full">
                        Revoked
                      </span>
                    )}
                  </div>
                  <p className="font-mono text-sm text-on-surface/60 mt-1">{key.prefix}…</p>
                  <p className="text-on-surface/40 text-xs mt-1">
                    Created {formatDate(key.createdAt)}
                    {key.lastUsedAt ? ` · Last used ${formatDate(key.lastUsedAt)}` : " · Never used"}
                  </p>
                  <div className="flex flex-wrap gap-1.5 mt-3">
                    {key.permissions.map((p) => (
                      <span
                        key={p}
                        className="text-xs font-semibold text-primary bg-primary/10 px-2 py-0.5 rounded-full"
                        title={p}
                      >
                        {labelFor(p)}
                      </span>
                    ))}
                  </div>
                </div>
                {!key.revokedAt && (
                  <button
                    onClick={() => handleRevoke(key.id)}
                    className="text-on-surface-variant/50 hover:text-error transition-colors p-2 rounded-lg hover:bg-error/10 shrink-0"
                    title="Revoke key"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
