import { useCallback, useEffect, useState } from "react";
import {
  AlertCircle,
  CheckCircle2,
  Database,
  Loader2,
  RefreshCw,
  Trash2,
} from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard } from "./ui";
import {
  CacheConfig,
  clearCache,
  getCacheConfig,
  toggleCacheEnabled,
} from "@/lib/adminApi";

function formatTimestamp(epochSeconds: number | null): string {
  if (!epochSeconds) return "Never";
  try {
    return new Date(epochSeconds * 1000).toLocaleString();
  } catch {
    return "—";
  }
}

/**
 * Admin-only page for managing the frontend cache.
 *
 * The page reads/writes a single JSON row in the `site_settings` table via
 * the `/api/v1/admin/cache` endpoints. Every mutating call is recorded in
 * the admin audit log on the backend, so no extra client-side logging is
 * required here.
 */
export default function CmsCache() {
  const [config, setConfig] = useState<CacheConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [clearing, setClearing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

  const notify = (ok: boolean, msg: string) => {
    setToast({ ok, msg });
    setTimeout(() => setToast(null), 3500);
  };

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getCacheConfig();
      setConfig(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load cache config");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const onToggle = async (next: boolean) => {
    if (!config || saving) return;
    setSaving(true);
    try {
      const updated = await toggleCacheEnabled(next);
      setConfig(updated);
      notify(true, `Frontend cache ${next ? "enabled" : "disabled"}.`);
    } catch (e) {
      notify(false, e instanceof Error ? e.message : "Toggle failed");
    } finally {
      setSaving(false);
    }
  };

  const onClear = async () => {
    if (!config || clearing) return;
    const ok = window.confirm(
      "Clear the frontend cache for all visitors? Clients will reload their cached assets on next page load.",
    );
    if (!ok) return;
    setClearing(true);
    try {
      const updated = await clearCache("manual admin action");
      setConfig(updated);
      notify(true, `Cache cleared (version bumped to v${updated.cache_version}).`);
    } catch (e) {
      notify(false, e instanceof Error ? e.message : "Clear failed");
    } finally {
      setClearing(false);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        icon={<Database className="w-6 h-6" />}
        title="Cache Management"
        description="Enable, disable, and invalidate the frontend cache across all visitors."
      />

      {toast && (
        <div
          className={`fixed top-24 right-6 z-50 flex items-center gap-2 px-4 py-3 rounded-xl shadow-lg border ${
            toast.ok
              ? "bg-emerald-50 border-emerald-200 text-emerald-800"
              : "bg-rose-50 border-rose-200 text-rose-800"
          }`}
          role="status"
        >
          {toast.ok ? (
            <CheckCircle2 className="w-5 h-5" />
          ) : (
            <AlertCircle className="w-5 h-5" />
          )}
          <span className="text-sm font-medium">{toast.msg}</span>
        </div>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-24 text-slate-500">
          <Loader2 className="w-6 h-6 animate-spin mr-2" />
          Loading cache settings…
        </div>
      ) : error ? (
        <div className="bg-rose-50 border border-rose-200 text-rose-800 rounded-xl p-5 flex items-start gap-3">
          <AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
          <div className="flex-1">
            <div className="font-semibold">Unable to load cache settings</div>
            <div className="text-sm mt-1">{error}</div>
            <button
              onClick={() => void load()}
              className="mt-3 inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white border border-rose-200 text-rose-700 text-sm font-semibold hover:bg-rose-50"
            >
              <RefreshCw className="w-4 h-4" /> Retry
            </button>
          </div>
        </div>
      ) : config ? (
        <div className="space-y-6">
          <SectionCard
            title="Frontend cache"
            description="When enabled, clients may cache API responses and static assets according to their Cache-Control headers. When disabled, clients are instructed to bypass cached copies."
          >
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 p-4 bg-slate-50 border border-slate-200 rounded-xl">
              <div>
                <div className="font-semibold text-slate-900">
                  Cache is currently{" "}
                  <span
                    className={
                      config.enabled ? "text-emerald-700" : "text-rose-700"
                    }
                  >
                    {config.enabled ? "enabled" : "disabled"}
                  </span>
                </div>
                <div className="text-sm text-slate-500 mt-1">
                  Cache version:{" "}
                  <span className="font-mono font-semibold text-slate-700">
                    v{config.cache_version}
                  </span>{" "}
                  · Last cleared: {formatTimestamp(config.last_cleared_at)}
                </div>
              </div>
              <button
                onClick={() => void onToggle(!config.enabled)}
                disabled={saving}
                aria-pressed={config.enabled}
                className={`relative inline-flex h-10 w-40 items-center rounded-full px-1 text-sm font-semibold transition-colors disabled:opacity-60 ${
                  config.enabled
                    ? "bg-emerald-600 text-white"
                    : "bg-slate-300 text-slate-700"
                }`}
              >
                <span
                  className={`inline-block h-8 w-8 transform rounded-full bg-white shadow transition-transform ${
                    config.enabled ? "translate-x-28" : "translate-x-0"
                  }`}
                  aria-hidden="true"
                />
                <span className="absolute inset-0 flex items-center justify-center pointer-events-none">
                  {saving ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : config.enabled ? (
                    "Enabled"
                  ) : (
                    "Disabled"
                  )}
                </span>
              </button>
            </div>
          </SectionCard>

          <SectionCard
            title="Clear cache"
            description="Increment the global cache-busting version. All clients will treat their existing caches as stale on their next request."
          >
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
              <p className="text-sm text-slate-600 max-w-xl">
                Use this after deploying new assets or fixing a misconfigured
                response. This action is recorded in the audit log.
              </p>
              <button
                onClick={() => void onClear()}
                disabled={clearing}
                className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-rose-600 text-white font-semibold hover:bg-rose-700 disabled:opacity-60"
              >
                {clearing ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Trash2 className="w-4 h-4" />
                )}
                {clearing ? "Clearing…" : "Clear cache now"}
              </button>
            </div>
          </SectionCard>
        </div>
      ) : null}
    </CmsLayout>
  );
}