"use client";

/* eslint-disable @next/next/no-img-element */

import { useMemo, useState } from "react";
import type { MediaFile } from "@/lib/admin/media";
import type { ContentDocuments, ContentKey, LinkContent, PageContent, SeoContent, ServiceContent, TextBlockContent } from "@/lib/content/types";

type Viewport = "desktop" | "tablet" | "mobile";
type ContentTabId = "home" | "services" | "radio-service" | "about" | "contact" | "footer" | "seo";
type SeoPageKey = Exclude<ContentKey, "settings">;

const tabs: Array<{ id: ContentTabId; label: string }> = [
  { id: "home", label: "Startseite" },
  { id: "services", label: "Leistungen" },
  { id: "radio-service", label: "Funkgeräte-Service" },
  { id: "about", label: "Über uns" },
  { id: "contact", label: "Kontakt" },
  { id: "footer", label: "Footer" },
  { id: "seo", label: "SEO" },
];

const seoPages: Array<{ key: SeoPageKey; label: string }> = [
  { key: "home", label: "Startseite" },
  { key: "services", label: "Leistungen" },
  { key: "radio-service", label: "Funkgeräte-Service" },
  { key: "repair", label: "Reparatur" },
  { key: "about", label: "Über uns" },
  { key: "contact", label: "Kontakt" },
];

type Props = {
  initialContent: ContentDocuments;
  mediaFiles: MediaFile[];
};

type ApiResponse<K extends ContentKey> = {
  message?: string;
  content?: ContentDocuments[K];
};

function contentKeyForTab(tab: ContentTabId, seoPage: SeoPageKey): ContentKey {
  if (tab === "footer") return "settings";
  if (tab === "seo") return seoPage;
  return tab;
}

function linesToText(lines: string[]) {
  return lines.join("\n");
}

function textToLines(value: string) {
  return value.split("\n").map((line) => line.trim()).filter(Boolean);
}

function updateLink(link: LinkContent, field: keyof LinkContent, value: string): LinkContent {
  return { ...link, [field]: value };
}

function TextInput({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
  return (
    <label>
      {label}
      <input value={value} onChange={(event) => onChange(event.target.value)} />
    </label>
  );
}

function TextArea({ label, value, onChange, rows = 4 }: { label: string; value: string; rows?: number; onChange: (value: string) => void }) {
  return (
    <label>
      {label}
      <textarea rows={rows} value={value} onChange={(event) => onChange(event.target.value)} />
    </label>
  );
}

function SectionTitle({ children }: { children: string }) {
  return <h3 className="content-editor-heading">{children}</h3>;
}

function ImagePicker({ label, value, mediaFiles, onChange, fallback = "" }: { label: string; value: string; mediaFiles: MediaFile[]; fallback?: string; onChange: (value: string) => void }) {
  const images = mediaFiles.filter((file) => file.isImage);
  const preview = value || fallback;

  return (
    <div className="content-image-picker">
      <label>
        {label}
        <select value={value} onChange={(event) => onChange(event.target.value)}>
          <option value="">Standard verwenden</option>
          <option value="/funktechnik_schubert_logo.jpg">Standard-Logo</option>
          <option value="/workbench-signal.svg">Standard-Hintergrund</option>
          {images.map((file) => <option key={file.name} value={file.url}>{file.name}</option>)}
        </select>
      </label>
      {preview && (
        <div className="content-image-preview">
          <img src={preview} alt="" />
          <button className="button light" type="button" onClick={() => onChange("")}>Bild entfernen</button>
        </div>
      )}
    </div>
  );
}

function SaveActions({ pending, onSave }: { pending: boolean; onSave: () => void }) {
  return (
    <div className="content-save-actions">
      <button className="button" type="button" onClick={onSave} disabled={pending}>{pending ? "Speichert..." : "Speichern"}</button>
    </div>
  );
}

function BlocksEditor({ blocks, onChange }: { blocks: TextBlockContent[]; onChange: (blocks: TextBlockContent[]) => void }) {
  function update(index: number, field: keyof TextBlockContent, value: string) {
    onChange(blocks.map((block, current) => current === index ? { ...block, [field]: value } : block));
  }

  return (
    <div className="content-repeaters">
      {blocks.map((block, index) => (
        <div key={index} className="content-repeater">
          <TextInput label="Titel" value={block.title} onChange={(value) => update(index, "title", value)} />
          <TextArea label="Text" value={block.text} onChange={(value) => update(index, "text", value)} />
          <button className="button light" type="button" onClick={() => onChange(blocks.filter((_, current) => current !== index))}>Entfernen</button>
        </div>
      ))}
      <button className="button light" type="button" onClick={() => onChange([...blocks, { title: "", text: "" }])}>Block hinzufügen</button>
    </div>
  );
}

function PageFields({ page, onChange }: { page: PageContent; onChange: (page: PageContent) => void }) {
  return (
    <>
      <SectionTitle>Hero</SectionTitle>
      <div className="content-field-grid">
        <TextInput label="Titel" value={page.title} onChange={(value) => onChange({ ...page, title: value })} />
        <TextInput label="Untertitel" value={page.subtitle} onChange={(value) => onChange({ ...page, subtitle: value })} />
        <TextInput label="Eyebrow" value={page.eyebrow} onChange={(value) => onChange({ ...page, eyebrow: value })} />
        <TextArea label="Hero Text" value={page.heroText} onChange={(value) => onChange({ ...page, heroText: value })} />
      </div>
      <SectionTitle>Inhalt</SectionTitle>
      <TextArea label="Einleitung" value={page.intro} onChange={(value) => onChange({ ...page, intro: value })} />
      <TextArea label="Listenpunkte, eine Zeile pro Eintrag" value={linesToText(page.list)} onChange={(value) => onChange({ ...page, list: textToLines(value) })} />
      <BlocksEditor blocks={page.paragraphs} onChange={(paragraphs) => onChange({ ...page, paragraphs })} />
      <SectionTitle>Call-To-Action</SectionTitle>
      <div className="content-field-grid">
        <TextInput label="CTA Text" value={page.cta.text} onChange={(value) => onChange({ ...page, cta: { ...page.cta, text: value } })} />
        <TextInput label="Button 1 Text" value={page.cta.primary.label} onChange={(value) => onChange({ ...page, cta: { ...page.cta, primary: updateLink(page.cta.primary, "label", value) } })} />
        <TextInput label="Button 1 Link" value={page.cta.primary.href} onChange={(value) => onChange({ ...page, cta: { ...page.cta, primary: updateLink(page.cta.primary, "href", value) } })} />
        <TextInput label="Button 2 Text" value={page.cta.secondary.label} onChange={(value) => onChange({ ...page, cta: { ...page.cta, secondary: updateLink(page.cta.secondary, "label", value) } })} />
        <TextInput label="Button 2 Link" value={page.cta.secondary.href} onChange={(value) => onChange({ ...page, cta: { ...page.cta, secondary: updateLink(page.cta.secondary, "href", value) } })} />
      </div>
    </>
  );
}

function SeoFields({ seo, mediaFiles, onChange }: { seo: SeoContent; mediaFiles: MediaFile[]; onChange: (seo: SeoContent) => void }) {
  return (
    <div className="content-field-grid">
      <TextInput label="Meta Title" value={seo.metaTitle} onChange={(value) => onChange({ ...seo, metaTitle: value })} />
      <TextInput label="Meta Description" value={seo.metaDescription} onChange={(value) => onChange({ ...seo, metaDescription: value })} />
      <TextInput label="Keywords" value={seo.keywords} onChange={(value) => onChange({ ...seo, keywords: value })} />
      <TextInput label="OpenGraph Title" value={seo.openGraphTitle} onChange={(value) => onChange({ ...seo, openGraphTitle: value })} />
      <TextInput label="OpenGraph Description" value={seo.openGraphDescription} onChange={(value) => onChange({ ...seo, openGraphDescription: value })} />
      <ImagePicker label="OpenGraph Image" value={seo.socialImage} mediaFiles={mediaFiles} fallback="/funktechnik_schubert_logo.jpg" onChange={(value) => onChange({ ...seo, socialImage: value })} />
      <TextInput label="Canonical URL" value={seo.canonicalUrl} onChange={(value) => onChange({ ...seo, canonicalUrl: value })} />
    </div>
  );
}

function ServicesEditor({ services, onChange }: { services: ServiceContent[]; onChange: (services: ServiceContent[]) => void }) {
  function update(index: number, field: keyof ServiceContent, value: string | number | boolean) {
    onChange(services.map((service, current) => current === index ? { ...service, [field]: value } : service));
  }

  return (
    <div className="content-repeaters">
      {services.map((service, index) => (
        <div key={index} className="content-repeater">
          <div className="content-field-grid">
            <TextInput label="Titel" value={service.title} onChange={(value) => update(index, "title", value)} />
            <TextInput label="Icon" value={service.icon} onChange={(value) => update(index, "icon", value)} />
            <label>
              Sortierung
              <input type="number" value={service.sortOrder} onChange={(event) => update(index, "sortOrder", Number(event.target.value))} />
            </label>
            <label className="admin-checkbox">
              <input type="checkbox" checked={service.visible} onChange={(event) => update(index, "visible", event.target.checked)} />
              Einblenden
            </label>
          </div>
          <TextArea label="Beschreibung" value={service.description} onChange={(value) => update(index, "description", value)} />
          <button className="button light" type="button" onClick={() => onChange(services.filter((_, current) => current !== index))}>Leistung entfernen</button>
        </div>
      ))}
      <button className="button light" type="button" onClick={() => onChange([...services, { title: "", description: "", icon: "radio", sortOrder: services.length * 10 + 10, visible: true }])}>Leistung hinzufügen</button>
    </div>
  );
}

export default function ContentManager({ initialContent, mediaFiles }: Props) {
  const [content, setContent] = useState(initialContent);
  const [activeTab, setActiveTab] = useState<ContentTabId>("home");
  const [seoPage, setSeoPage] = useState<SeoPageKey>("home");
  const [viewport, setViewport] = useState<Viewport>("desktop");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);

  const active = contentKeyForTab(activeTab, seoPage);
  const current = content[active];
  const activeLabel = useMemo(() => tabs.find((tab) => tab.id === activeTab)?.label ?? "Startseite", [activeTab]);
  const pagePreview = "title" in current ? current : content.home;

  function update<K extends ContentKey>(key: K, value: ContentDocuments[K]) {
    setContent((previous) => ({ ...previous, [key]: value }));
  }

  async function save() {
    setPending(true);
    setMessage("");
    setError("");

    try {
      const response = await fetch("/api/admin/content", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ key: active, content: current }),
      });
      const result = await response.json() as ApiResponse<typeof active>;
      if (!response.ok || !result.content) throw new Error("Inhalt konnte nicht gespeichert werden.");
      update(active, result.content);
      setMessage("Inhalt wurde gespeichert.");
    } catch {
      setError("Der Inhalt konnte nicht gespeichert werden. Bitte prüfen Sie die Eingaben und versuchen Sie es erneut.");
    } finally {
      setPending(false);
    }
  }

  const heroBackground = content.home.heroImage || "/workbench-signal.svg";

  return (
    <div className="content-manager">
      {message && <p className="success admin-message">{message}</p>}
      {error && <p className="error admin-message">{error}</p>}
      <section className="admin-card content-editor-layout">
        <aside className="content-tabs" aria-label="Website-Inhalte">
          {tabs.map((tab) => (
            <button key={tab.id} type="button" aria-current={activeTab === tab.id ? "page" : undefined} onClick={() => setActiveTab(tab.id)}>
              {tab.label}
            </button>
          ))}
        </aside>
        <div className="content-editor">
          <div className="content-editor-top">
            <div>
              <p className="eyebrow">Editor</p>
              <h2>{activeLabel}</h2>
            </div>
            <SaveActions pending={pending} onSave={save} />
          </div>

          {activeTab === "home" && (
            <>
              <PageFields page={content.home} onChange={(value) => update("home", { ...content.home, ...value })} />
              <SectionTitle>Medien</SectionTitle>
              <ImagePicker label="Hero-Bild" value={content.home.heroImage} mediaFiles={mediaFiles} fallback="/workbench-signal.svg" onChange={(value) => update("home", { ...content.home, heroImage: value })} />
              <SectionTitle>Homepage Builder</SectionTitle>
              <TextArea label="Badges, eine Zeile pro Eintrag" value={linesToText(content.home.badges)} onChange={(value) => update("home", { ...content.home, badges: textToLines(value) })} />
              <h4>3 Featureboxen</h4>
              <BlocksEditor blocks={content.home.features} onChange={(features) => update("home", { ...content.home, features })} />
              <h4>3 Leistungsboxen</h4>
              <BlocksEditor blocks={content.home.services} onChange={(services) => update("home", { ...content.home, services })} />
              <h4>Kundenversprechen</h4>
              <TextInput label="Headline" value={content.home.promise.title} onChange={(value) => update("home", { ...content.home, promise: { ...content.home.promise, title: value } })} />
              <TextArea label="Text" value={content.home.promise.text} onChange={(value) => update("home", { ...content.home, promise: { ...content.home.promise, text: value } })} />
              <TextArea label="Punkte, eine Zeile pro Eintrag" value={linesToText(content.home.promise.bullets)} onChange={(value) => update("home", { ...content.home, promise: { ...content.home.promise, bullets: textToLines(value) } })} />
              <TextArea label="Footer-Text" value={content.home.footerText} onChange={(value) => update("home", { ...content.home, footerText: value })} />
            </>
          )}

          {activeTab === "services" && (
            <>
              <PageFields page={content.services} onChange={(value) => update("services", { ...content.services, ...value })} />
              <SectionTitle>Leistungen</SectionTitle>
              <ServicesEditor services={content.services.services} onChange={(services) => update("services", { ...content.services, services })} />
            </>
          )}

          {activeTab === "radio-service" && (
            <>
              <PageFields page={content["radio-service"]} onChange={(value) => update("radio-service", { ...content["radio-service"], ...value })} />
              <SectionTitle>Funkgeräte-Service</SectionTitle>
              <TextArea label="Marken" value={linesToText(content["radio-service"].brands)} onChange={(value) => update("radio-service", { ...content["radio-service"], brands: textToLines(value) })} />
              <TextArea label="Fehlerbilder" value={linesToText(content["radio-service"].symptoms)} onChange={(value) => update("radio-service", { ...content["radio-service"], symptoms: textToLines(value) })} />
              <TextArea label="Ablauf" value={linesToText(content["radio-service"].workflow)} onChange={(value) => update("radio-service", { ...content["radio-service"], workflow: textToLines(value) })} />
              <TextArea label="Messmöglichkeiten" value={linesToText(content["radio-service"].measurements)} onChange={(value) => update("radio-service", { ...content["radio-service"], measurements: textToLines(value) })} />
              <TextArea label="Abgleich" value={content["radio-service"].alignment} onChange={(value) => update("radio-service", { ...content["radio-service"], alignment: value })} />
              <TextArea label="Reparatur" value={content["radio-service"].repair} onChange={(value) => update("radio-service", { ...content["radio-service"], repair: value })} />
            </>
          )}

          {activeTab === "about" && (
            <>
              <PageFields page={content.about} onChange={(value) => update("about", { ...content.about, ...value })} />
              <SectionTitle>Über uns</SectionTitle>
              <TextArea label="Firmenbeschreibung" value={content.about.companyDescription} onChange={(value) => update("about", { ...content.about, companyDescription: value })} />
              <TextArea label="Werkstattbeschreibung" value={content.about.workshopDescription} onChange={(value) => update("about", { ...content.about, workshopDescription: value })} />
              <TextArea label="Philosophie" value={content.about.philosophy} onChange={(value) => update("about", { ...content.about, philosophy: value })} />
            </>
          )}

          {activeTab === "contact" && (
            <>
              <PageFields page={content.contact} onChange={(value) => update("contact", { ...content.contact, ...value })} />
              <SectionTitle>Kontaktinformationen</SectionTitle>
              <div className="content-field-grid">
                <TextInput label="Telefon" value={content.contact.phone} onChange={(value) => update("contact", { ...content.contact, phone: value })} />
                <TextInput label="E-Mail" value={content.contact.email} onChange={(value) => update("contact", { ...content.contact, email: value })} />
                <TextInput label="Adresse" value={content.contact.address} onChange={(value) => update("contact", { ...content.contact, address: value })} />
                <TextInput label="Öffnungszeiten" value={content.contact.openingHours} onChange={(value) => update("contact", { ...content.contact, openingHours: value })} />
                <TextInput label="Google Maps Link" value={content.contact.googleMapsLink} onChange={(value) => update("contact", { ...content.contact, googleMapsLink: value })} />
              </div>
            </>
          )}

          {activeTab === "footer" && (
            <>
              <SectionTitle>Footer und Header</SectionTitle>
              <div className="content-field-grid">
                <TextInput label="Site Name" value={content.settings.siteName} onChange={(value) => update("settings", { ...content.settings, siteName: value })} />
                <ImagePicker label="Logo" value={content.settings.logoUrl} mediaFiles={mediaFiles} fallback="/funktechnik_schubert_logo.jpg" onChange={(value) => update("settings", { ...content.settings, logoUrl: value })} />
                <TextInput label="Copyright" value={content.settings.copyright} onChange={(value) => update("settings", { ...content.settings, copyright: value })} />
                <TextInput label="Header CTA Text" value={content.settings.headerCta.label} onChange={(value) => update("settings", { ...content.settings, headerCta: updateLink(content.settings.headerCta, "label", value) })} />
                <TextInput label="Header CTA Link" value={content.settings.headerCta.href} onChange={(value) => update("settings", { ...content.settings, headerCta: updateLink(content.settings.headerCta, "href", value) })} />
              </div>
              <TextArea label="Footer-Kurztext" value={content.settings.footerShortText} onChange={(value) => update("settings", { ...content.settings, footerShortText: value })} />
            </>
          )}

          {activeTab === "seo" && (
            <>
              <SectionTitle>SEO pro Seite</SectionTitle>
              <label>
                Seite
                <select value={seoPage} onChange={(event) => setSeoPage(event.target.value as SeoPageKey)}>
                  {seoPages.map((page) => <option key={page.key} value={page.key}>{page.label}</option>)}
                </select>
              </label>
              <SeoFields seo={content[seoPage].seo} mediaFiles={mediaFiles} onChange={(seo) => update(seoPage, { ...content[seoPage], seo })} />
            </>
          )}

          <SaveActions pending={pending} onSave={save} />
        </div>
      </section>

      <section className="admin-card content-preview-card">
        <div className="content-preview-toolbar">
          <div>
            <p className="eyebrow">Vorschau</p>
            <h2>Live Preview</h2>
          </div>
          <div>
            {(["desktop", "tablet", "mobile"] as const).map((item) => (
              <button key={item} type="button" aria-current={viewport === item ? "true" : undefined} onClick={() => setViewport(item)}>{item}</button>
            ))}
          </div>
        </div>
        <div className={`content-preview ${viewport}`} style={{ backgroundImage: `linear-gradient(90deg, rgba(6, 24, 52, 0.95), rgba(8, 42, 96, 0.72)), url("${activeTab === "home" ? heroBackground : pagePreview.heroImage || "/workbench-signal.svg"}")` }}>
          <p className="eyebrow">{activeTab === "seo" ? content[seoPage].seo.metaTitle || pagePreview.eyebrow : pagePreview.eyebrow}</p>
          <h1>{pagePreview.title}</h1>
          <p className="lead">{pagePreview.subtitle}</p>
          <p>{pagePreview.heroText}</p>
          <div className="hero-actions">
            <span className="button">{pagePreview.cta.primary.label}</span>
            <span className="button light">{pagePreview.cta.secondary.label}</span>
          </div>
        </div>
      </section>
    </div>
  );
}
