import { useState } from "react";
import { X } from "lucide-react";
import { Input } from "@/components/ui/input";
import type {
  PageSection,
  SectionBreakpointKey,
  SectionBreakpointSettings,
  SectionSpacing,
  SectionStyleSettings,
  SectionWidth,
} from "../types";
import {
  BP_KEYS,
  getBreakpointSettings,
  normalizeSectionStyle,
  resolveSectionWidth,
  setBreakpointSettings,
  type EditorPreviewBreakpoint,
} from "@/lib/sectionStyle";

const labelCls = "block text-sm font-medium text-slate-700 mb-1.5";
const rowCls = "mb-4";
const inputCls = "flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm";

type SpacingKey = keyof SectionSpacing;

function SpacingFields({
  label,
  value,
  onChange,
}: {
  label: string;
  value: SectionSpacing;
  onChange: (v: SectionSpacing) => void;
}) {
  const sides: { key: SpacingKey; lbl: string }[] = [
    { key: "top", lbl: "Top" },
    { key: "right", lbl: "Right" },
    { key: "bottom", lbl: "Bottom" },
    { key: "left", lbl: "Left" },
  ];
  return (
    <div className={rowCls}>
      <p className={labelCls}>{label}</p>
      <div className="grid grid-cols-2 gap-3">
        {sides.map(({ key, lbl }) => (
          <div key={key}>
            <label className="text-xs text-slate-500 mb-1 block">{lbl}</label>
            <Input
              value={value[key] ?? ""}
              onChange={(e) => onChange({ ...value, [key]: e.target.value })}
              placeholder="e.g. 24px, 2rem"
            />
          </div>
        ))}
      </div>
    </div>
  );
}

function BreakpointTabs({
  active,
  onChange,
  label = "Breakpoint",
}: {
  active: SectionBreakpointKey;
  onChange: (bp: SectionBreakpointKey) => void;
  label?: string;
}) {
  return (
    <div className={rowCls}>
      <p className={labelCls}>{label}</p>
      <div className="flex gap-1 rounded-lg border border-slate-200 p-0.5 w-fit">
        {BP_KEYS.map((bp) => (
          <button
            key={bp}
            type="button"
            onClick={() => onChange(bp)}
            className={`px-3 py-1.5 text-xs font-medium rounded-md capitalize ${
              active === bp ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-50"
            }`}
          >
            {bp}
          </button>
        ))}
      </div>
    </div>
  );
}

export function SectionStyleEditForm({
  sectionIndex,
  section,
  onChange,
  onPreviewBreakpointChange,
  initialPreviewBreakpoint = "desktop",
  onSave,
  onClose,
}: {
  sectionIndex: number;
  section: PageSection;
  onChange: (patch: { width?: SectionWidth; style?: SectionStyleSettings }) => void;
  onPreviewBreakpointChange?: (bp: EditorPreviewBreakpoint) => void;
  initialPreviewBreakpoint?: EditorPreviewBreakpoint;
  onSave: () => void;
  onClose: () => void;
}) {
  const [style, setStyle] = useState<SectionStyleSettings>(() => normalizeSectionStyle(section.style));
  const [sectionWidth, setSectionWidth] = useState<SectionWidth>(section.width);
  const [spacingTab, setSpacingTab] = useState<"padding" | "margin">("padding");
  const [activeBreakpoint, setActiveBreakpoint] = useState<SectionBreakpointKey>(initialPreviewBreakpoint);

  const push = (nextStyle: SectionStyleSettings, nextWidth = sectionWidth) => {
    setStyle(nextStyle);
    setSectionWidth(nextWidth);
    onChange({ style: nextStyle, width: nextWidth });
  };

  const updateGlobal = (patch: Partial<SectionStyleSettings>) => {
    push({ ...style, ...patch });
  };

  const bp = getBreakpointSettings(style, activeBreakpoint);
  const effectiveWidth = resolveSectionWidth(sectionWidth, style, activeBreakpoint);

  const updateBp = (patch: Partial<SectionBreakpointSettings>) => {
    let next = setBreakpointSettings(style, activeBreakpoint, patch);
    let nextWidth = sectionWidth;
    if (activeBreakpoint === "desktop" && patch.width) {
      nextWidth = patch.width;
    }
    if (activeBreakpoint === "desktop" && patch.width === undefined && "width" in patch) {
      // cleared override — keep section width
    }
    push(next, nextWidth);
  };

  const setActiveBp = (next: SectionBreakpointKey) => {
    setActiveBreakpoint(next);
    onPreviewBreakpointChange?.(next);
  };

  const layoutLabel = `Section ${sectionIndex + 1}`;
  const inheritedHint =
    activeBreakpoint === "desktop"
      ? "Values apply to desktop viewports (1025px and wider)."
      : `Leave fields empty to inherit from ${activeBreakpoint === "tablet" ? "desktop" : "tablet/desktop"}. Only filled fields override.`;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6">
      <div
        className="bg-white rounded-2xl shadow-xl max-w-3xl w-full max-h-[90vh] overflow-hidden flex flex-col"
      >
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200">
          <h2 className="text-lg font-semibold text-slate-900">Edit section — {layoutLabel}</h2>
          <button type="button" onClick={onClose} className="p-2 text-slate-500 hover:text-slate-700 rounded-lg hover:bg-slate-100">
            <X size={20} />
          </button>
        </div>

        <div className="px-6 py-4 overflow-y-auto flex-1 space-y-2">
          <BreakpointTabs
            active={activeBreakpoint}
            onChange={setActiveBp}
            label="Edit & preview breakpoint"
          />
          <p className="text-xs text-slate-500 -mt-2 mb-4">{inheritedHint}</p>

          <div className={rowCls}>
            <label className={labelCls}>
              Section width {activeBreakpoint !== "desktop" && `(effective: ${effectiveWidth})`}
            </label>
            <div className="flex gap-3 flex-wrap">
              {(["full", "container"] as const).map((w) => (
                <button
                  key={w}
                  type="button"
                  onClick={() => updateBp({ width: w })}
                  className={`flex-1 min-w-[120px] py-2.5 rounded-lg border text-sm font-medium ${
                    effectiveWidth === w ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white text-slate-700 hover:bg-slate-50"
                  }`}
                >
                  {w === "full" ? "Full width" : "Container"}
                </button>
              ))}
              {activeBreakpoint !== "desktop" && bp.width && (
                <button
                  type="button"
                  onClick={() => updateBp({ width: undefined })}
                  className="px-3 py-2.5 rounded-lg border border-slate-200 text-sm text-slate-600 hover:bg-slate-50"
                >
                  Reset to inherited
                </button>
              )}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className={rowCls}>
              <label className={labelCls}>Max width</label>
              <Input
                value={bp.maxWidth ?? ""}
                onChange={(e) => updateBp({ maxWidth: e.target.value })}
                placeholder="e.g. 72rem, 1200px"
              />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Container horizontal padding</label>
              <Input
                value={bp.containerPaddingX ?? ""}
                onChange={(e) => updateBp({ containerPaddingX: e.target.value })}
                placeholder="e.g. 1.5rem, 24px"
              />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Text alignment</label>
              <select
                value={bp.textAlign ?? ""}
                onChange={(e) => updateBp({ textAlign: e.target.value })}
                className={inputCls}
              >
                <option value="">Inherit / default</option>
                <option value="left">Left</option>
                <option value="center">Center</option>
                <option value="right">Right</option>
              </select>
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Base font size</label>
              <Input
                value={bp.fontSize ?? ""}
                onChange={(e) => updateBp({ fontSize: e.target.value })}
                placeholder="e.g. 1rem, 18px"
              />
            </div>
          </div>

          <hr className="border-slate-200 my-4" />
          <h3 className="text-sm font-semibold text-slate-800 mb-3">Background (all breakpoints)</h3>
          <div className="grid grid-cols-2 gap-3">
            <div className={rowCls}>
              <label className={labelCls}>Background color</label>
              <div className="flex gap-2">
                <input
                  type="color"
                  value={style.backgroundColor?.startsWith("#") ? style.backgroundColor : "#ffffff"}
                  onChange={(e) => updateGlobal({ backgroundColor: e.target.value })}
                  className="h-10 w-12 rounded border border-slate-200 cursor-pointer"
                />
                <Input
                  value={style.backgroundColor ?? ""}
                  onChange={(e) => updateGlobal({ backgroundColor: e.target.value })}
                  placeholder="#f8fafc or transparent"
                />
              </div>
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Background image URL</label>
              <Input
                value={style.backgroundImage ?? ""}
                onChange={(e) => updateGlobal({ backgroundImage: e.target.value })}
                placeholder="https://..."
              />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Background size</label>
              <select
                value={style.backgroundSize ?? "cover"}
                onChange={(e) => updateGlobal({ backgroundSize: e.target.value })}
                className={inputCls}
              >
                <option value="cover">cover</option>
                <option value="contain">contain</option>
                <option value="auto">auto</option>
              </select>
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Background position</label>
              <Input
                value={style.backgroundPosition ?? "center"}
                onChange={(e) => updateGlobal({ backgroundPosition: e.target.value })}
                placeholder="center, top left"
              />
            </div>
          </div>

          <hr className="border-slate-200 my-4" />
          <h3 className="text-sm font-semibold text-slate-800 mb-3">Border & shadow (all breakpoints)</h3>
          <div className="grid grid-cols-2 gap-3">
            <div className={rowCls}>
              <label className={labelCls}>Border radius</label>
              <Input value={style.borderRadius ?? ""} onChange={(e) => updateGlobal({ borderRadius: e.target.value })} placeholder="e.g. 12px" />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Border width</label>
              <Input value={style.borderWidth ?? ""} onChange={(e) => updateGlobal({ borderWidth: e.target.value })} placeholder="e.g. 1px" />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Border color</label>
              <Input value={style.borderColor ?? ""} onChange={(e) => updateGlobal({ borderColor: e.target.value })} placeholder="#e5e7eb" />
            </div>
            <div className={rowCls}>
              <label className={labelCls}>Box shadow</label>
              <Input
                value={style.boxShadow ?? ""}
                onChange={(e) => updateGlobal({ boxShadow: e.target.value })}
                placeholder="0 4px 24px rgba(0,0,0,0.08)"
              />
            </div>
          </div>

          <hr className="border-slate-200 my-4" />
          <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
            <h3 className="text-sm font-semibold text-slate-800">
              Spacing — {activeBreakpoint}
            </h3>
            <div className="flex gap-1 rounded-lg border border-slate-200 p-0.5">
              {(["padding", "margin"] as const).map((t) => (
                <button
                  key={t}
                  type="button"
                  onClick={() => setSpacingTab(t)}
                  className={`px-3 py-1 text-xs font-medium rounded-md capitalize ${
                    spacingTab === t ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-50"
                  }`}
                >
                  {t}
                </button>
              ))}
            </div>
          </div>
          <SpacingFields
            label={`${spacingTab} (${activeBreakpoint})`}
            value={spacingTab === "padding" ? (bp.padding ?? {}) : (bp.margin ?? {})}
            onChange={(v) => updateBp(spacingTab === "padding" ? { padding: v } : { margin: v })}
          />
        </div>

        <div className="px-6 py-4 border-t border-slate-200 flex justify-end gap-3">
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-lg border border-slate-300 bg-white font-medium text-slate-700 hover:bg-slate-50">
            Cancel
          </button>
          <button type="button" onClick={onSave} className="px-4 py-2 rounded-lg bg-slate-900 text-white font-medium hover:bg-slate-800">
            Done
          </button>
        </div>
      </div>
    </div>
  );
}
