import { useEffect, useState } from "react";
import { adminApi, adminEndpoints } from "../api";
import { HEADER_LAYOUTS, HEADER_PREVIEWS, FOOTER_LAYOUTS } from "@/components/site-layouts";
import { notifySiteSettingsUpdated, useSiteSettings } from "@/contexts/SiteSettingsContext";

export default function SiteSettingsPage() {
  const { settings, loading, refresh } = useSiteSettings();
  const [headerLayout, setHeaderLayout] = useState<string>("default");
  const [footerLayout, setFooterLayout] = useState<string>("default");
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    setHeaderLayout(settings.header_layout);
    setFooterLayout(settings.footer_layout);
  }, [settings.footer_layout, settings.header_layout]);

  const handleSave = async () => {
    setSaving(true);
    setMessage(null);
    try {
      await adminApi.put(adminEndpoints.siteSettings, {
        header_layout: headerLayout,
        footer_layout: footerLayout,
      });
      notifySiteSettingsUpdated();
      await refresh();
      setMessage({
        type: "success",
        text: "Site settings saved. Header and footer updates now apply across all pages, previews, and the page builder.",
      });
    } catch (e) {
      setMessage({ type: "error", text: (e as Error).message || "Failed to save." });
    } finally {
      setSaving(false);
    }
  };

  const headerOptions = Object.entries(HEADER_LAYOUTS).map(([value, { label }]) => ({ value, label }));
  const footerOptions = Object.entries(FOOTER_LAYOUTS).map(([value, { label }]) => ({ value, label }));

  const HeaderPreviewComponent = HEADER_PREVIEWS[headerLayout] ?? HEADER_PREVIEWS.default;
  const FooterPreviewComponent = FOOTER_LAYOUTS[footerLayout]?.Component ?? FOOTER_LAYOUTS.default.Component;

  if (loading) {
    return (
      <div className="p-6">
        <p className="text-slate-500">Loading site settings...</p>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-2xl">
      <h1 className="text-2xl font-bold text-slate-900 mb-2">Site Settings</h1>
      <p className="text-slate-600 text-sm mb-6">
        Choose the header and footer layouts for the entire website. Changes apply globally to all pages — existing and new — including preview and the page builder.
      </p>

      <div className="space-y-6">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">Header layout</label>
          <select
            value={headerLayout}
            onChange={(e) => setHeaderLayout(e.target.value)}
            className="w-full rounded-lg border border-slate-300 bg-white px-4 py-2.5 text-sm text-slate-900 focus:border-slate-500 focus:outline-none focus:ring-1 focus:ring-slate-500"
          >
            {headerOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
          <div className="mt-3 rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
            <p className="px-3 py-1.5 text-xs font-medium text-slate-500 border-b border-slate-200 bg-white">Live preview</p>
            <div className="p-0 min-w-0">
              <HeaderPreviewComponent />
            </div>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-slate-700 mb-2">Footer layout</label>
          <select
            value={footerLayout}
            onChange={(e) => setFooterLayout(e.target.value)}
            className="w-full rounded-lg border border-slate-300 bg-white px-4 py-2.5 text-sm text-slate-900 focus:border-slate-500 focus:outline-none focus:ring-1 focus:ring-slate-500"
          >
            {footerOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
          <div className="mt-3 rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
            <p className="px-3 py-1.5 text-xs font-medium text-slate-500 border-b border-slate-200 bg-white">Live preview</p>
            <div className="p-0 min-w-0">
              <FooterPreviewComponent />
            </div>
          </div>
        </div>

        {message && (
          <div
            className={`rounded-lg px-4 py-3 text-sm ${
              message.type === "success" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"
            }`}
          >
            {message.text}
          </div>
        )}

        <button
          type="button"
          onClick={handleSave}
          disabled={saving}
          className="px-5 py-2.5 rounded-lg bg-slate-900 text-white font-medium text-sm hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {saving ? "Saving..." : "Save site settings"}
        </button>
      </div>
    </div>
  );
}
