"use client";

import { useState, useEffect } from "react";
import { NavigationBlock } from "@/components/blocks/NavigationBlock";
import { HeroBlock } from "@/components/blocks/HeroBlock";
import { DoctorsBlock } from "@/components/blocks/DoctorsBlock";
import { CeoBlock } from "@/components/blocks/CeoBlock";
import { ReviewsBlock } from "@/components/blocks/ReviewsBlock";
import { NewsBlock } from "@/components/blocks/NewsBlock";
import { ContactFormsBlock } from "@/components/blocks/ContactFormsBlock";
import { FooterBlock } from "@/components/blocks/FooterBlock";

const STORAGE_KEY = "bb-preview-created";
const LS_PREFIX = "bb-block-preview:";

function BlockPlaceholder({ name, href }: { name: string; href: string }) {
  return (
    <div
      className="w-full py-14 flex flex-col items-center justify-center rounded-xl gap-2"
      style={{
        border: "2px dashed #d1d5db",
        background: "#f9fafb",
      }}
    >
      <p className="text-sm font-medium" style={{ color: "#6b7280" }}>
        {name}
      </p>
      <a
        href={href}
        className="text-xs underline"
        style={{ color: "var(--brand-053m)" }}
      >
        Открыть в брендбуке →
      </a>
    </div>
  );
}

interface BlockDef {
  id: string;
  name: string;
  href: string;
  path: string;
  defaultReady: boolean;
  component?: React.ReactNode;
}

const BLOCKS: BlockDef[] = [
  {
    id: "navigation",
    name: "Шапка / Навигация",
    href: "/blocks/navigation",
    path: "/blocks/navigation",
    defaultReady: true,
    component: <NavigationBlock />,
  },
  {
    id: "hero",
    name: "Hero-баннер",
    href: "/blocks/hero",
    path: "/blocks/hero",
    defaultReady: true,
    component: <HeroBlock />,
  },
  {
    id: "ceo",
    name: "Вводный текст (CEO-блок)",
    href: "/blocks/ceo",
    path: "/blocks/ceo",
    defaultReady: false,
    component: <CeoBlock />,
  },
  {
    id: "doctors",
    name: "Наши врачи",
    href: "/blocks/doctors",
    path: "/blocks/doctors",
    defaultReady: true,
    component: <DoctorsBlock />,
  },
  {
    id: "reviews",
    name: "Отзывы",
    href: "/blocks/reviews",
    path: "/blocks/reviews",
    defaultReady: false,
    component: <ReviewsBlock />,
  },
  {
    id: "contact-forms",
    name: "Формы записи",
    href: "/blocks/contact-forms",
    path: "/blocks/contact-forms",
    defaultReady: false,
    component: <ContactFormsBlock />,
  },
  {
    id: "news",
    name: "Новости",
    href: "/blocks/news",
    path: "/blocks/news",
    defaultReady: false,
    component: <NewsBlock />,
  },
  {
    id: "footer",
    name: "Подвал / Контакт",
    href: "/blocks/contact",
    path: "/blocks/contact",
    defaultReady: false,
    component: <FooterBlock />,
  },
];

export function PreviewClient() {
  const [created, setCreated] = useState(false);
  const [mounted, setMounted] = useState(false);
  // Map of path → isInPreview from API; null = not loaded yet
  const [apiMeta, setApiMeta] = useState<Record<string, boolean> | null>(null);

  const apiUrl = process.env.NEXT_PUBLIC_API_URL;

  // Counter to force re-render when localStorage preview toggles change
  const [, setRefresh] = useState(0);

  useEffect(() => {
    setMounted(true);
    if (localStorage.getItem(STORAGE_KEY) === "true") {
      setCreated(true);
    }
    const handler = () => setRefresh((n) => n + 1);
    window.addEventListener("bb-preview-change", handler);
    return () => window.removeEventListener("bb-preview-change", handler);
  }, []);

  useEffect(() => {
    if (!apiUrl) return;
    fetch(`${apiUrl}/blocks`)
      .then((r) => r.json())
      .then((data: Array<{ path: string; isInPreview: boolean }>) => {
        const map: Record<string, boolean> = {};
        for (const b of data) map[b.path] = b.isInPreview;
        setApiMeta(map);
      })
      .catch(() => {
        // API offline — fall back to defaultReady
      });
  }, [apiUrl]);

  function isReady(block: BlockDef): boolean {
    // 1. API online → use API data
    if (apiMeta !== null && block.path in apiMeta) {
      return apiMeta[block.path] && !!block.component;
    }
    // 2. Check localStorage (set by BlockMetaBar toggle)
    const lsVal = typeof window !== "undefined" ? localStorage.getItem(LS_PREFIX + block.path) : null;
    if (lsVal !== null) {
      return lsVal === "true" && !!block.component;
    }
    // 3. Fallback to defaultReady
    return block.defaultReady && !!block.component;
  }

  function handleCreate() {
    localStorage.setItem(STORAGE_KEY, "true");
    setCreated(true);
  }

  function handleRebuild() {
    localStorage.removeItem(STORAGE_KEY);
    setCreated(false);
  }

  if (!mounted) return null;

  const readyCount = BLOCKS.filter(isReady).length;

  /* ── ПУСТОЕ СОСТОЯНИЕ ── */
  if (!created) {
    return (
      <div
        className="flex flex-col items-center justify-center min-h-screen"
        style={{ background: "var(--bb-bg)" }}
      >
        <div className="text-center max-w-md space-y-5 p-8">
          <p
            className="text-xs font-semibold uppercase tracking-widest"
            style={{ color: "var(--brand-053m)" }}
          >
            Страницы
          </p>
          <h1 className="text-2xl font-bold" style={{ color: "var(--bb-text)" }}>
            Просмотр текущей страницы
          </h1>
          <p className="text-sm" style={{ color: "var(--bb-text-muted)", lineHeight: 1.7 }}>
            Нажмите «Создать», чтобы собрать главную страницу{" "}
            <span className="font-mono text-xs">perm.oclinica.ru/lor</span> из блоков,
            задокументированных в брендбуке.
          </p>
          <div
            className="flex items-center justify-center gap-2 text-xs px-4 py-2 rounded-lg"
            style={{ background: "var(--bb-sidebar-bg)", border: "1px solid var(--bb-border)" }}
          >
            <span
              className="inline-block w-2 h-2 rounded-full"
              style={{ background: "#22c55e" }}
            />
            <span style={{ color: "var(--bb-text-muted)" }}>
              Готово блоков: {readyCount} из {BLOCKS.length}
            </span>
            <span style={{ color: "var(--bb-text-muted)" }}>·</span>
            <span style={{ color: "var(--bb-text-muted)" }}>
              {BLOCKS.length - readyCount} плейсхолдеров
            </span>
          </div>
          <div>
            <button onClick={handleCreate} className="bb-btn bb-btn-md bb-btn-primary">
              Создать
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ── СОЗДАННОЕ СОСТОЯНИЕ ── */
  return (
    <div>
      {/* Топ-бар */}
      <div
        className="sticky top-0 z-10 flex items-center justify-between px-6 py-3 border-b"
        style={{
          background: "var(--bb-sidebar-bg)",
          borderColor: "var(--bb-border)",
        }}
      >
        <div>
          <p
            className="text-xs font-semibold uppercase tracking-widest"
            style={{ color: "var(--brand-053m)" }}
          >
            Просмотр текущей страницы
          </p>
          <p className="text-xs mt-0.5" style={{ color: "var(--bb-text-muted)" }}>
            perm.oclinica.ru/lor · {readyCount}/{BLOCKS.length} блоков готово
            {apiMeta === null && apiUrl && (
              <span style={{ color: "#f59e0b" }}> · API загружается...</span>
            )}
          </p>
        </div>
        <button onClick={handleRebuild} className="bb-btn bb-btn-sm bb-btn-outline">
          Пересобрать
        </button>
      </div>

      {/* Собранная страница */}
      <div className="max-w-5xl mx-auto px-8 py-8 space-y-12">
        {BLOCKS.map((block) =>
          isReady(block) ? (
            <section key={block.id}>{block.component}</section>
          ) : (
            <section key={block.id}>
              <BlockPlaceholder name={block.name} href={block.href} />
            </section>
          )
        )}
      </div>
    </div>
  );
}
