import { useState } from "react";
import { Palette, Plus, Trash2, ImagePlus, ArrowUp, ArrowDown, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import {
  PageHeader, SectionCard, Field, TextInput, Select, ColorPicker, SaveBar, Badge,
} from "./ui";
import { useSiteSettings } from "@/hooks/useSiteSettings";
import { createClient } from "@metagptx/web-sdk";

const client = createClient();

type Slide = { id: string; title: string; subtitle: string; cta: string; ctaLink: string };
type BrandState = {
  logoUrl: string;
  faviconUrl: string;
  primary: string;
  secondary: string;
  accent: string;
  bg: string;
  fontHeading: string;
  fontBody: string;
  headingScale: number;
  slides: Slide[];
};

const DEFAULTS: BrandState = {
  logoUrl: "/logo.svg",
  faviconUrl: "/favicon.ico",
  primary: "#0b6e3e",
  secondary: "#063019",
  accent: "#f5c400",
  bg: "#03120a",
  fontHeading: "Inter",
  fontBody: "Inter",
  headingScale: 100,
  slides: [
    { id: "1", title: "Dedicated With Confidence.", subtitle: "Enterprise-grade cloud starting at $12.99/mo.", cta: "Get Prices", ctaLink: "/pricing" },
    { id: "2", title: "Virtual Cloud Servers", subtitle: "NVMe-powered VPS with 60s provisioning.", cta: "VPS Servers", ctaLink: "/cloud-vps" },
    { id: "3", title: "Managed IT Done Right.", subtitle: "24/7 monitoring and expert engineers on call.", cta: "Managed IT", ctaLink: "/managed-it" },
  ],
};

const FONTS = ["Inter", "Roboto", "Poppins", "Montserrat", "Cairo", "IBM Plex Sans", "Work Sans", "Open Sans"];

export default function CmsBranding() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<BrandState>("branding", DEFAULTS);
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);
  const [uploading, setUploading] = useState<"logo" | "favicon" | null>(null);

  const update = <K extends keyof BrandState>(k: K, v: BrandState[K]) => setState({ ...state, [k]: v });

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

  const handleSave = async () => {
    const r = await save();
    if (r.ok) notify(true, "Branding saved. Live site will update shortly.");
    else notify(false, r.error || "Save failed. Please retry.");
  };

  const reset = () => setState(DEFAULTS);

  const handleUpload = async (file: File, kind: "logo" | "favicon") => {
    const maxBytes = kind === "favicon" ? 512 * 1024 : 2 * 1024 * 1024;
    if (file.size > maxBytes) {
      notify(false, `File too large. Max ${Math.round(maxBytes / 1024)}KB.`);
      return;
    }
    if (!/^image\//.test(file.type)) {
      notify(false, "Please upload an image file.");
      return;
    }
    setUploading(kind);
    try {
      const resp: any = await (client as any).storage.upload({ file, bucket: "branding" });
      const url = resp?.data?.url ?? resp?.url ?? null;
      if (url) {
        update(kind === "logo" ? "logoUrl" : "faviconUrl", url);
        notify(true, `${kind === "logo" ? "Logo" : "Favicon"} uploaded. Click Save Changes to apply.`);
      } else {
        // Fallback: DataURL embed (works but larger)
        const reader = new FileReader();
        reader.onload = () => {
          update(kind === "logo" ? "logoUrl" : "faviconUrl", String(reader.result));
          notify(true, "Using inline image (backend upload unavailable).");
        };
        reader.readAsDataURL(file);
      }
    } catch {
      const reader = new FileReader();
      reader.onload = () => {
        update(kind === "logo" ? "logoUrl" : "faviconUrl", String(reader.result));
        notify(true, "Using inline image (storage error).");
      };
      reader.readAsDataURL(file);
    } finally {
      setUploading(null);
    }
  };

  const addSlide = () => {
    const id = Date.now().toString();
    update("slides", [...state.slides, { id, title: "New Slide Title", subtitle: "Describe this slide", cta: "Learn More", ctaLink: "/" }]);
  };
  const removeSlide = (id: string) => update("slides", state.slides.filter((s) => s.id !== id));
  const moveSlide = (id: string, dir: -1 | 1) => {
    const i = state.slides.findIndex((s) => s.id === id);
    if (i < 0) return;
    const j = i + dir;
    if (j < 0 || j >= state.slides.length) return;
    const next = [...state.slides];
    [next[i], next[j]] = [next[j], next[i]];
    update("slides", next);
  };
  const editSlide = (id: string, patch: Partial<Slide>) =>
    update("slides", state.slides.map((s) => (s.id === id ? { ...s, ...patch } : s)));

  return (
    <CmsLayout>
      <PageHeader
        icon={<Palette className="w-6 h-6" />}
        title="Branding"
        description="Customize your logo, hero slider, colors, and typography. Saved values apply site-wide in real time."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">
          Loading saved settings from server…
        </div>
      )}
      {toast && (
        <div className={`mb-4 p-3 rounded-lg text-sm flex items-center gap-2 ${toast.ok ? "bg-emerald-50 border border-emerald-200 text-emerald-800" : "bg-red-50 border border-red-200 text-red-800"}`}>
          {toast.ok ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <SectionCard title="Brand Assets" description="Upload your logo and favicon or paste a URL.">
        <div className="grid md:grid-cols-2 gap-5">
          {(["logo", "favicon"] as const).map((kind) => {
            const urlField = kind === "logo" ? "logoUrl" : "faviconUrl";
            const currentUrl = state[urlField];
            return (
              <div key={kind}>
                <div className="text-sm font-semibold text-slate-800 mb-2 capitalize">{kind}</div>
                <div className="rounded-xl border-2 border-dashed border-slate-300 p-6 bg-slate-50 flex flex-col items-center justify-center gap-3">
                  <div className={kind === "favicon" ? "" : "h-14 flex items-center"}>
                    <img src={currentUrl} alt={kind} className={kind === "favicon" ? "w-8 h-8" : "max-h-14"} onError={(e) => ((e.target as HTMLImageElement).style.display = "none")} />
                  </div>
                  <div className="flex items-center gap-2 w-full">
                    <label className="px-3 py-1.5 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold inline-flex items-center gap-1 hover:bg-[#0a8048] cursor-pointer shrink-0">
                      <ImagePlus className="w-3.5 h-3.5" /> {uploading === kind ? "Uploading…" : "Upload"}
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => {
                          const f = e.target.files?.[0];
                          if (f) handleUpload(f, kind);
                          e.currentTarget.value = "";
                        }}
                      />
                    </label>
                    <TextInput value={currentUrl} onChange={(e) => update(urlField, e.target.value)} placeholder="URL or path" className="!py-1.5 text-xs" />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Colors" description="These values drive the primary theme of the site.">
        <div className="grid md:grid-cols-4 gap-5">
          <ColorPicker label="Primary" value={state.primary} onChange={(v) => update("primary", v)} />
          <ColorPicker label="Secondary (Deep)" value={state.secondary} onChange={(v) => update("secondary", v)} />
          <ColorPicker label="Accent" value={state.accent} onChange={(v) => update("accent", v)} />
          <ColorPicker label="Hero Background" value={state.bg} onChange={(v) => update("bg", v)} />
        </div>
        <div className="mt-4 rounded-xl p-5 border border-slate-200 overflow-hidden" style={{ backgroundColor: state.bg }}>
          <div className="flex flex-wrap gap-2">
            <button className="px-4 py-2 rounded-md font-bold text-slate-900" style={{ backgroundColor: state.accent }}>Primary CTA</button>
            <button className="px-4 py-2 rounded-md font-bold text-white" style={{ backgroundColor: state.primary }}>Secondary CTA</button>
            <button className="px-4 py-2 rounded-md font-bold text-white" style={{ backgroundColor: state.secondary }}>Tertiary</button>
          </div>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Typography" description="Choose a font family for headings and body text.">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Heading Font">
            <Select value={state.fontHeading} onChange={(e) => update("fontHeading", e.target.value)}>
              {FONTS.map((f) => <option key={f} value={f}>{f}</option>)}
            </Select>
          </Field>
          <Field label="Body Font">
            <Select value={state.fontBody} onChange={(e) => update("fontBody", e.target.value)}>
              {FONTS.map((f) => <option key={f} value={f}>{f}</option>)}
            </Select>
          </Field>
          <Field label={`Heading Scale: ${state.headingScale}%`}>
            <input
              type="range" min={80} max={140} value={state.headingScale}
              onChange={(e) => update("headingScale", Number(e.target.value))}
              className="w-full accent-[#0b6e3e]"
            />
          </Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard
        title="Hero Slider"
        description="Manage the rotating slides shown on the landing page."
        actions={
          <button onClick={addSlide} className="px-3 py-1.5 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold inline-flex items-center gap-1 hover:bg-[#0a8048]">
            <Plus className="w-3.5 h-3.5" /> Add Slide
          </button>
        }
      >
        <div className="space-y-4">
          {state.slides.map((s, idx) => (
            <div key={s.id} className="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div className="flex items-center justify-between mb-3">
                <Badge tone="green">Slide {idx + 1}</Badge>
                <div className="flex items-center gap-1">
                  <button onClick={() => moveSlide(s.id, -1)} className="p-1.5 rounded hover:bg-slate-200" aria-label="Move up"><ArrowUp className="w-4 h-4" /></button>
                  <button onClick={() => moveSlide(s.id, 1)} className="p-1.5 rounded hover:bg-slate-200" aria-label="Move down"><ArrowDown className="w-4 h-4" /></button>
                  <button onClick={() => removeSlide(s.id)} className="p-1.5 rounded hover:bg-red-100 text-red-600" aria-label="Remove"><Trash2 className="w-4 h-4" /></button>
                </div>
              </div>
              <div className="grid md:grid-cols-2 gap-3">
                <Field label="Title"><TextInput value={s.title} onChange={(e) => editSlide(s.id, { title: e.target.value })} /></Field>
                <Field label="Subtitle"><TextInput value={s.subtitle} onChange={(e) => editSlide(s.id, { subtitle: e.target.value })} /></Field>
                <Field label="CTA Label"><TextInput value={s.cta} onChange={(e) => editSlide(s.id, { cta: e.target.value })} /></Field>
                <Field label="CTA Link"><TextInput value={s.ctaLink} onChange={(e) => editSlide(s.id, { ctaLink: e.target.value })} /></Field>
              </div>
            </div>
          ))}
          {state.slides.length === 0 && (
            <div className="text-center text-sm text-slate-500 py-10">No slides yet. Click "Add Slide".</div>
          )}
        </div>
      </SectionCard>

      <SaveBar onSave={handleSave} onReset={reset} saving={saving} />
    </CmsLayout>
  );
}