import React, { useMemo, useState } from "react";
import PptxGenJS from "pptxgenjs";
import { useBrandKit } from "../../../utils/brand";
import { fileToDataUrl } from "../../../utils/file";

// Simple type for UI state
type BgMode = "solid" | "image";
type LogoPlacement = "none" | "top-left" | "top-right" | "bottom-left" | "bottom-right";

export default function DocumentCovers() {
  // 1) Brand Kit binding (from context/localStorage; has safe defaults)
  const brand = useBrandKit();

  // 2) Form state
  const [title, setTitle] = useState("Your Presentation Title");
  const [subtitle, setSubtitle] = useState("Optional subtitle or tagline goes here");
  const [bgMode, setBgMode] = useState<BgMode>("solid");
  const [bgColor, setBgColor] = useState<string>(brand.colors.primary || "#05445e");
  const [bgImageDataUrl, setBgImageDataUrl] = useState<string | null>(null);
  const [titleColor, setTitleColor] = useState<string>("#ffffff");
  const [subtitleColor, setSubtitleColor] = useState<string>("#d4f1f4");
  const [useLogo, setUseLogo] = useState<boolean>(!!brand.logo?.dataUrl);
  const [logoPlacement, setLogoPlacement] = useState<LogoPlacement>("top-right");
  const [logoScale, setLogoScale] = useState<number>(1); // multiplier against default size
  const [slideRatio, setSlideRatio] = useState<"16x9" | "4x3">("16x9");

  const slideW = slideRatio === "16x9" ? 13.33 : 10; // inches
  const slideH = slideRatio === "16x9" ? 7.5 : 7.5;

  const previewStyle = useMemo(() => {
    return {
      background:
        bgMode === "solid"
          ? bgColor
          : bgImageDataUrl
          ? `center/cover no-repeat url(${bgImageDataUrl})`
          : brand.colors.primary,
    } as React.CSSProperties;
  }, [bgMode, bgColor, bgImageDataUrl, brand.colors.primary]);

  async function onPickBackgroundImage(e: React.ChangeEvent<HTMLInputElement>) {
    const f = e.target.files?.[0];
    if (!f) return;
    const data = await fileToDataUrl(f);
    setBgImageDataUrl(data);
  }

  function placeLogo(slide: PptxGenJS.Slide, dataUrl: string) {
    if (!dataUrl || logoPlacement === "none") return;

    // Default logo size (inches) then scale
    const baseW = 1.6;
    const baseH = 1.6;
    const w = baseW * logoScale;
    const h = baseH * logoScale;

    const margin = 0.35;
    let x = margin;
    let y = margin;

    switch (logoPlacement) {
      case "top-left":
        x = margin;
        y = margin;
        break;
      case "top-right":
        x = slideW - w - margin;
        y = margin;
        break;
      case "bottom-left":
        x = margin;
        y = slideH - h - margin;
        break;
      case "bottom-right":
        x = slideW - w - margin;
        y = slideH - h - margin;
        break;
    }

    slide.addImage({ data: dataUrl, x, y, w, h });
  }

  function addBackground(slide: PptxGenJS.Slide) {
    if (bgMode === "solid") {
      slide.background = { color: bgColor };
    } else if (bgMode === "image" && bgImageDataUrl) {
      slide.background = { data: bgImageDataUrl };
    } else if (brand.colors.primary) {
      slide.background = { color: brand.colors.primary };
    }
  }

  function generatePptx() {
    const pptx = new PptxGenJS();
    // Slide size
    if (slideRatio === "16x9") {
      pptx.layout = "LAYOUT_16x9";
    } else {
      pptx.layout = "LAYOUT_4x3";
    }

    const slide = pptx.addSlide();

    // Background
    addBackground(slide);

    // Optional overlay to improve contrast (subtle, adjustable)
    slide.addShape(pptx.ShapeType.rect, {
      x: 0,
      y: 0,
      w: slideW,
      h: slideH,
      fill: { color: "000000", transparency: 80 }, // 0-100 (higher is more transparent)
      line: { color: "000000", transparency: 100 },
    });

    // Title / Subtitle text
    const titleFont = brand.fonts?.heading || "Inter";
    const bodyFont = brand.fonts?.body || "Inter";

    // Title block
    slide.addText(title, {
      x: 0.8,
      y: slideH * 0.32,
      w: slideW - 1.6,
      h: 1.6,
      align: "center",
      fontFace: titleFont,
      fontSize: 42,
      bold: true,
      color: hexToPptx(titleColor),
    });

    // Subtitle block
    if (subtitle.trim().length > 0) {
      slide.addText(subtitle, {
        x: 1.2,
        y: slideH * 0.48,
        w: slideW - 2.4,
        h: 1.1,
        align: "center",
        fontFace: bodyFont,
        fontSize: 20,
        color: hexToPptx(subtitleColor),
      });
    }

    // Logo
    if (useLogo && brand.logo?.dataUrl) {
      placeLogo(slide, brand.logo.dataUrl);
    }

    // File name: BrandName - Cover.pptx
    const brandName = brand.name || "Brand";
    const safeTitle = title.replace(/[\\/:*?"<>|]/g, "").slice(0, 80);
    const filename = `${brandName} - ${safeTitle || "Cover"}.pptx`;

    pptx.writeFile({ fileName: filename });
  }

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-2xl font-bold">Document Covers</h1>
      <p className="text-slate-300">
        Snap out a beautiful cover slide using your Brand Kit: colors, fonts, and logo. Exports a real{" "}
        <span className="font-semibold">.pptx</span>.
      </p>

      {/* Brand Kit summary */}
      <div className="rounded-xl border border-white/10 bg-slate-900/60 p-4">
        <div className="text-sm text-slate-400">Brand Kit</div>
        <div className="mt-2 flex flex-wrap items-center gap-4">
          <div>
            <div className="text-xs text-slate-400">Brand</div>
            <div className="font-medium">{brand.name || "Untitled Brand"}</div>
          </div>
          <div>
            <div className="text-xs text-slate-400">Fonts</div>
            <div className="text-sm">
              <span className="font-semibold">Heading:</span> {brand.fonts?.heading || "Inter"} &nbsp;•&nbsp;
              <span className="font-semibold">Body:</span> {brand.fonts?.body || "Inter"}
            </div>
          </div>
          <div className="flex items-center gap-2">
            {Object.entries(brand.colors)
              .slice(0, 6)
              .map(([k, v]) => (
                <div key={k} className="text-center">
                  <div className="h-6 w-6 rounded" style={{ background: v }} />
                  <div className="text-[10px] text-slate-400 mt-1">{k}</div>
                </div>
              ))}
          </div>
        </div>
      </div>

      {/* Designer form */}
      <div className="grid lg:grid-cols-2 gap-6">
        <div className="rounded-xl border border-white/10 bg-slate-900/60 p-5">
          <div className="grid gap-4">
            <div>
              <label className="text-sm text-slate-300">Title</label>
              <input
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="mt-1 w-full rounded-lg bg-slate-950/60 border border-white/10 p-2 text-slate-100 focus:outline-none focus:ring-2 focus:ring-sky-500/40"
                placeholder="Enter main title"
              />
            </div>

            <div>
              <label className="text-sm text-slate-300">Subtitle</label>
              <input
                value={subtitle}
                onChange={(e) => setSubtitle(e.target.value)}
                className="mt-1 w-full rounded-lg bg-slate-950/60 border border-white/10 p-2 text-slate-100 focus:outline-none focus:ring-2 focus:ring-sky-500/40"
                placeholder="Optional tagline"
              />
            </div>

            <div className="flex flex-wrap gap-4">
              <div>
                <label className="text-sm text-slate-300">Title Color</label>
                <input
                  type="color"
                  value={titleColor}
                  onChange={(e) => setTitleColor(e.target.value)}
                  className="block mt-1 h-9 w-12 bg-transparent"
                />
              </div>
              <div>
                <label className="text-sm text-slate-300">Subtitle Color</label>
                <input
                  type="color"
                  value={subtitleColor}
                  onChange={(e) => setSubtitleColor(e.target.value)}
                  className="block mt-1 h-9 w-12 bg-transparent"
                />
              </div>
            </div>

            <div>
              <label className="text-sm text-slate-300">Slide Ratio</label>
              <div className="mt-1 flex gap-2">
                <button
                  className={`px-3 py-1.5 rounded-lg border ${slideRatio === "16x9" ? "bg-white/10 border-white/20" : "border-white/10 hover:bg-white/5"}`}
                  onClick={() => setSlideRatio("16x9")}
                >
                  16:9
                </button>
                <button
                  className={`px-3 py-1.5 rounded-lg border ${slideRatio === "4x3" ? "bg-white/10 border-white/20" : "border-white/10 hover:bg-white/5"}`}
                  onClick={() => setSlideRatio("4x3")}
                >
                  4:3
                </button>
              </div>
            </div>

            <div>
              <label className="text-sm text-slate-300">Background</label>
              <div className="mt-2 flex items-center gap-3">
                <label className="inline-flex items-center gap-2">
                  <input
                    type="radio"
                    className="accent-sky-500"
                    checked={bgMode === "solid"}
                    onChange={() => setBgMode("solid")}
                  />
                  Solid
                </label>
                <label className="inline-flex items-center gap-2">
                  <input
                    type="radio"
                    className="accent-sky-500"
                    checked={bgMode === "image"}
                    onChange={() => setBgMode("image")}
                  />
                  Image
                </label>
              </div>

              {bgMode === "solid" ? (
                <div className="mt-2">
                  <input
                    type="color"
                    value={bgColor}
                    onChange={(e) => setBgColor(e.target.value)}
                    className="h-9 w-12 bg-transparent"
                  />
                </div>
              ) : (
                <div className="mt-2">
                  <input
                    type="file"
                    accept="image/*"
                    onChange={onPickBackgroundImage}
                    className="block text-sm text-slate-300 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-sm file:bg-slate-800 file:text-white hover:file:bg-slate-700"
                  />
                  {!bgImageDataUrl && (
                    <p className="text-xs text-slate-400 mt-1">
                      Choose a large image (1920×1080 or bigger) for the cleanest result.
                    </p>
                  )}
                </div>
              )}
            </div>

            <div className="rounded-lg border border-white/10 p-3">
              <label className="inline-flex items-center gap-2">
                <input
                  type="checkbox"
                  className="accent-sky-500"
                  checked={useLogo}
                  onChange={(e) => setUseLogo(e.target.checked)}
                />
                <span className="text-sm text-slate-300">Include brand logo</span>
              </label>

              <div className="mt-3 grid grid-cols-2 gap-3">
                <div>
                  <div className="text-xs text-slate-400 mb-1">Placement</div>
                  <div className="flex flex-wrap gap-2">
                    {(["none", "top-left", "top-right", "bottom-left", "bottom-right"] as LogoPlacement[]).map((p) => (
                      <button
                        key={p}
                        className={`px-2.5 py-1.5 rounded border text-xs ${
                          logoPlacement === p ? "bg-white/10 border-white/20" : "border-white/10 hover:bg-white/5"
                        }`}
                        onClick={() => setLogoPlacement(p)}
                      >
                        {p.replace("-", " ")}
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <div className="text-xs text-slate-400 mb-1">Size</div>
                  <input
                    type="range"
                    min={0.6}
                    max={2}
                    step={0.1}
                    value={logoScale}
                    onChange={(e) => setLogoScale(parseFloat(e.target.value))}
                    className="w-full"
                  />
                </div>
              </div>
              {!brand.logo?.dataUrl && (
                <p className="text-xs text-amber-300 mt-2">
                  No logo found in Brand Kit. Add one in Brand Kit settings to enable this.
                </p>
              )}
            </div>

            <div className="pt-2">
              <button
                onClick={generatePptx}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-sky-600 hover:bg-sky-700 text-white"
              >
                Generate PPTX
              </button>
              <p className="text-xs text-slate-400 mt-2">
                Uses your Brand Kit fonts and colors. PPTX opens in PowerPoint/Keynote/Google Slides.
              </p>
            </div>
          </div>
        </div>

        {/* Live Preview (HTML approximation) */}
        <div className="rounded-xl border border-white/10 bg-slate-900/60 p-5">
          <div className="text-sm text-slate-300 mb-2">Preview</div>
          <div
            className={`relative w-full ${slideRatio === "16x9" ? "aspect-video" : "aspect-[4/3]"} overflow-hidden rounded-xl border border-white/10`}
            style={previewStyle}
          >
            <div className="absolute inset-0" style={{ background: "rgba(0,0,0,0.2)" }} />

            {/* Title */}
            <div
              style={{
                position: "absolute",
                left: "6%",
                right: "6%",
                top: "32%",
                textAlign: "center",
                fontFamily: brand.fonts?.heading || "Inter",
                fontWeight: 800,
                fontSize: "2.4rem",
                lineHeight: 1.15,
                color: titleColor,
                textShadow: "0 2px 8px rgba(0,0,0,0.35)",
              }}
            >
              {title}
            </div>

            {/* Subtitle */}
            {subtitle.trim() && (
              <div
                style={{
                  position: "absolute",
                  left: "10%",
                  right: "10%",
                  top: "48%",
                  textAlign: "center",
                  fontFamily: brand.fonts?.body || "Inter",
                  fontWeight: 500,
                  fontSize: "1.05rem",
                  color: subtitleColor,
                  textShadow: "0 1px 6px rgba(0,0,0,0.3)",
                }}
              >
                {subtitle}
              </div>
            )}

            {/* Logo */}
            {useLogo && brand.logo?.dataUrl && logoPlacement !== "none" && (
              <img
                src={brand.logo.dataUrl}
                alt="logo"
                style={{
                  position: "absolute",
                  width: `${8 * logoScale}%`,
                  aspectRatio: "1 / 1",
                  ...(logoPlacement.includes("top") ? { top: "3%" } : { bottom: "3%" }),
                  ...(logoPlacement.includes("left") ? { left: "3%" } : { right: "3%" }),
                  opacity: 0.95,
                  filter: "drop-shadow(0 2px 6px rgba(0,0,0,0.35))",
                }}
              />
            )}
          </div>

          <p className="mt-3 text-xs text-slate-400">
            Preview approximates the slide. The exported PPTX uses PowerPoint’s layout engine and your chosen fonts.
          </p>
        </div>
      </div>
    </div>
  );
}

// Utilities
function hexToPptx(hex: string): string {
  // Accepts "#RRGGBB" or "RRGGBB"
  const clean = hex.replace("#", "");
  return clean.length === 6 ? clean.toUpperCase() : "FFFFFF";
}
