'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/input';
import { CodeBlock } from '@/components/code-block';

interface PromptData {
  builtin: string;
  override: string | null;
  updatedAt: string | null;
}

export default function AdminPromptPage() {
  const [data, setData] = useState<PromptData | null>(null);
  const [draft, setDraft] = useState('');
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  async function reload() {
    const r = await apiFetch<PromptData>('/v1/admin/prompt');
    setData(r);
    setDraft(r.override ?? r.builtin);
  }

  useEffect(() => {
    reload();
  }, []);

  async function save() {
    if (!data) return;
    setSaving(true);
    setMessage(null);
    try {
      // Only persist as override if it differs from built-in
      const value = draft === data.builtin ? null : draft;
      await apiFetch('/v1/admin/prompt', {
        method: 'PATCH',
        body: JSON.stringify({ value }),
      });
      setMessage(value === null ? 'Reverted to built-in prompt.' : 'Override saved.');
      await reload();
    } catch (e) {
      setMessage(`Failed: ${(e as Error).message}`);
    } finally {
      setSaving(false);
    }
  }

  async function revert() {
    if (!data) return;
    if (!confirm('Drop the override and use the built-in prompt?')) return;
    await apiFetch('/v1/admin/prompt', { method: 'PATCH', body: JSON.stringify({ value: null }) });
    await reload();
    setMessage('Reverted to built-in.');
  }

  if (!data) return <div className="px-8 py-8 mono text-[12px] text-[--color-fg-muted]">Loading…</div>;

  const dirty = draft !== (data.override ?? data.builtin);
  const isOverridden = data.override !== null;

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">AI prompt</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          The system prompt the generator hands to Claude when parsing user requests. Override at
          your own risk — bad prompts cause low-quality builds.
        </p>
      </header>

      <div className="grid gap-4 md:grid-cols-[1fr_280px]">
        <div>
          <div className="flex items-baseline justify-between">
            <h2 className="text-[14px] font-semibold tracking-tight">Live prompt</h2>
            <span className="mono text-[10.5px] uppercase tracking-wider text-[--color-fg-subtle]">
              {draft.length} chars
            </span>
          </div>
          <Textarea
            rows={28}
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            className="mt-3 mono text-[12px]"
            spellCheck={false}
          />
          {message && (
            <p className="mt-2 text-[12px] text-[--color-fg-muted]">{message}</p>
          )}
          <div className="mt-4 flex justify-end gap-2">
            {isOverridden && (
              <Button variant="ghost" size="md" onClick={revert} disabled={saving}>
                Drop override
              </Button>
            )}
            <Button variant="primary" size="md" onClick={save} disabled={!dirty || saving}>
              {saving ? 'Saving…' : isOverridden ? 'Save override' : 'Save as override'}
            </Button>
          </div>
        </div>
        <aside className="space-y-3">
          <div className="panel p-3">
            <div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">
              Status
            </div>
            <div className="mt-2 text-[13px]">
              {isOverridden ? (
                <>
                  <span className="text-amber-300">Override active</span>
                  {data.updatedAt && (
                    <div className="mono text-[11px] text-[--color-fg-subtle]">
                      since {new Date(data.updatedAt).toLocaleString()}
                    </div>
                  )}
                </>
              ) : (
                <span className="text-emerald-300">Using built-in</span>
              )}
            </div>
          </div>
          <div className="panel p-3">
            <div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">
              Built-in baseline
            </div>
            <p className="mt-2 text-[12px] text-[--color-fg-muted]">
              Shipped with <span className="mono">@bmm/llm</span>. Restored if you drop the
              override.
            </p>
          </div>
          <div className="panel p-3">
            <div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">
              Warning
            </div>
            <p className="mt-2 text-[12px] text-[--color-fg-muted]">
              Prompt changes apply to <em>new builds only</em>. Existing servers run their
              generated code as-is and aren&apos;t affected until iterated.
            </p>
          </div>
        </aside>
      </div>

      {dirty && (
        <div className="mt-6">
          <h3 className="text-[13px] font-semibold tracking-tight">Diff preview</h3>
          <CodeBlock
            label="proposed → builtin"
            code={`+ ${draft.length} chars\n- ${(data.override ?? data.builtin).length} chars\n→ ${
              draft.length - (data.override ?? data.builtin).length > 0 ? '+' : ''
            }${draft.length - (data.override ?? data.builtin).length} chars`}
          />
        </div>
      )}
    </div>
  );
}
