"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Check, Copy, KeyRound, Loader2, Plus, Trash2, TriangleAlert } from "lucide-react"
import { createApiKey, revokeApiKey } from "@/app/actions/api-keys"

export type ApiKeyRow = {
  id: string
  name: string
  key_prefix: string
  created_at: string
  last_used_at: string | null
  revoked_at: string | null
}

const inputClass =
  "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-white/30 outline-none ring-indigo-500 transition focus:border-indigo-500/50 focus:ring-1"

function formatDate(value: string | null): string {
  if (!value) return "Never"
  const d = new Date(value)
  return Number.isNaN(d.getTime())
    ? "—"
    : d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })
}

export function ApiKeyManager({ initialKeys }: { initialKeys: ApiKeyRow[] }) {
  const router = useRouter()
  const [name, setName] = useState("")
  const [creating, setCreating] = useState(false)
  const [busyId, setBusyId] = useState<string | null>(null)
  const [newKey, setNewKey] = useState<{ plaintext: string; prefix: string } | null>(null)
  const [copied, setCopied] = useState(false)

  async function handleCreate(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const trimmed = name.trim()
    if (!trimmed) return
    setCreating(true)
    try {
      const result = await createApiKey(trimmed)
      setNewKey(result)
      setName("")
      setCopied(false)
      toast.success("API key created")
      router.refresh()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to create API key")
    } finally {
      setCreating(false)
    }
  }

  async function handleCopy() {
    if (!newKey) return
    try {
      await navigator.clipboard.writeText(newKey.plaintext)
      setCopied(true)
      toast.success("Copied to clipboard")
      setTimeout(() => setCopied(false), 2000)
    } catch {
      toast.error("Copy failed — select and copy the key manually")
    }
  }

  async function handleRevoke(key: ApiKeyRow) {
    setBusyId(key.id)
    try {
      await revokeApiKey(key.id)
      toast.success(`Revoked "${key.name}"`)
      router.refresh()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to revoke key")
    } finally {
      setBusyId(null)
    }
  }

  return (
    <div className="space-y-6">
      {/* One-time plaintext reveal */}
      {newKey && (
        <div className="rounded-xl border border-amber-500/25 bg-amber-500/[0.06] p-6">
          <div className="flex items-start gap-3">
            <div className="rounded-lg bg-amber-500/10 p-2">
              <TriangleAlert className="h-5 w-5 text-amber-400" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-sm font-semibold text-white">Copy your new API key now</p>
              <p className="mt-0.5 text-xs text-amber-200/70">
                This is the only time it will be shown. Store it somewhere safe — you will not see it again.
              </p>
              <div className="mt-3 flex items-center gap-2">
                <code className="min-w-0 flex-1 overflow-x-auto rounded-lg border border-white/10 bg-[#0a0a12] px-3 py-2.5 font-mono text-xs text-emerald-300">
                  {newKey.plaintext}
                </code>
                <button
                  type="button"
                  onClick={handleCopy}
                  className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2.5 text-xs font-medium text-white/70 transition hover:bg-white/5"
                >
                  {copied ? (
                    <Check className="h-3.5 w-3.5 text-emerald-400" />
                  ) : (
                    <Copy className="h-3.5 w-3.5" />
                  )}
                  {copied ? "Copied" : "Copy"}
                </button>
              </div>
              <button
                type="button"
                onClick={() => setNewKey(null)}
                className="mt-3 text-xs font-medium text-white/40 transition hover:text-white/70"
              >
                I&apos;ve saved it — dismiss
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Create form */}
      <form
        onSubmit={handleCreate}
        className="space-y-4 rounded-xl border border-white/[0.06] bg-[#16161f] p-6"
      >
        <div>
          <h3 className="text-sm font-semibold text-white">Create an API key</h3>
          <p className="mt-0.5 text-xs text-white/40">
            Use API keys to authenticate requests to the public REST API.
          </p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row">
          <input
            type="text"
            required
            maxLength={100}
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="e.g. Production integration"
            className={inputClass + " sm:flex-1"}
          />
          <button
            type="submit"
            disabled={creating || !name.trim()}
            className="inline-flex items-center justify-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500 disabled:opacity-50 sm:w-auto"
          >
            {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
            Create key
          </button>
        </div>
      </form>

      {/* Keys list */}
      <div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
        <div className="border-b border-white/[0.06] px-6 py-4">
          <h3 className="text-sm font-semibold text-white">
            Your API keys <span className="text-white/30">({initialKeys.length})</span>
          </h3>
        </div>

        {initialKeys.length === 0 ? (
          <div className="px-6 py-10 text-center text-sm text-white/40">
            No API keys yet. Create one above to start using the REST API.
          </div>
        ) : (
          <ul className="divide-y divide-white/[0.06]">
            {initialKeys.map((key) => {
              const busy = busyId === key.id
              const revoked = !!key.revoked_at
              return (
                <li
                  key={key.id}
                  className="flex flex-wrap items-center justify-between gap-3 px-6 py-4"
                >
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <KeyRound className="h-4 w-4 shrink-0 text-white/30" />
                      <p className="truncate text-sm font-medium text-white">{key.name}</p>
                      {revoked && (
                        <span className="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-white/40">
                          Revoked
                        </span>
                      )}
                    </div>
                    <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 pl-6 text-xs text-white/40">
                      <code className="font-mono text-white/60">{key.key_prefix}</code>
                      <span>Created {formatDate(key.created_at)}</span>
                      <span>Last used {formatDate(key.last_used_at)}</span>
                    </div>
                  </div>

                  {!revoked && (
                    <button
                      type="button"
                      onClick={() => handleRevoke(key)}
                      disabled={busy}
                      className="inline-flex items-center gap-1.5 rounded-lg border border-red-500/20 px-3 py-1.5 text-xs font-medium text-red-400 transition hover:bg-red-500/10 disabled:opacity-50"
                    >
                      {busy ? (
                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                      ) : (
                        <Trash2 className="h-3.5 w-3.5" />
                      )}
                      Revoke
                    </button>
                  )}
                </li>
              )
            })}
          </ul>
        )}
      </div>
    </div>
  )
}
