"use client";

import React, {
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { StoryTextOverlay } from "@/api/fetchStories";
import BoldIcon from "@/components/ui/BoldIcon";

const TEXT_COLORS = [
  "#ffffff",
  "#000000",
  "#ff3040",
  "#ffd60a",
  "#0a84ff",
  "#30d158",
  "#ff2d92",
  "#bf5af2",
];

const MIN_FONT = 0.03;
const MAX_FONT = 0.14;

type StoryEditorProps = {
  mediaUrl: string;
  mediaType: "image" | "video";
  overlays: StoryTextOverlay[];
  onChange: (overlays: StoryTextOverlay[]) => void;
};

export default function StoryEditor({
  mediaUrl,
  mediaType,
  overlays,
  onChange,
}: StoryEditorProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  const [selected, setSelected] = useState<number | null>(null);
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [draftText, setDraftText] = useState("");

  const dragState = useRef<{
    index: number;
    moved: boolean;
  } | null>(null);

  useLayoutEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const update = () =>
      setContainerSize({ width: el.clientWidth, height: el.clientHeight });
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const updateOverlay = useCallback(
    (index: number, patch: Partial<StoryTextOverlay>) => {
      onChange(
        overlays.map((o, i) => (i === index ? { ...o, ...patch } : o))
      );
    },
    [overlays, onChange]
  );

  const removeOverlay = useCallback(
    (index: number) => {
      onChange(overlays.filter((_, i) => i !== index));
      setSelected(null);
    },
    [overlays, onChange]
  );

  const openTextEditor = (index: number | null) => {
    if (index === null) {
      setDraftText("");
    } else {
      setDraftText(overlays[index]?.text ?? "");
    }
    setEditingIndex(index);
  };

  const commitText = () => {
    const text = draftText.trim();
    if (editingIndex === null) {
      if (text) {
        const next: StoryTextOverlay = {
          text,
          x: 0.5,
          y: 0.4,
          font_size: 0.07,
          color: "#ffffff",
          background: "",
          rotation: 0,
          align: "center",
        };
        onChange([...overlays, next]);
        setSelected(overlays.length);
      }
    } else if (text) {
      updateOverlay(editingIndex, { text });
    } else {
      removeOverlay(editingIndex);
    }
    setEditingIndex(null);
    setDraftText("");
  };

  const handlePointerDown = (
    e: React.PointerEvent<HTMLDivElement>,
    index: number
  ) => {
    e.stopPropagation();
    (e.target as HTMLElement).setPointerCapture?.(e.pointerId);
    dragState.current = { index, moved: false };
    setSelected(index);
  };

  const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    const state = dragState.current;
    const rect = containerRef.current?.getBoundingClientRect();
    if (!state || !rect) return;
    state.moved = true;
    const x = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
    const y = Math.min(1, Math.max(0, (e.clientY - rect.top) / rect.height));
    updateOverlay(state.index, { x, y });
  };

  const handlePointerUp = () => {
    dragState.current = null;
  };

  const selectedOverlay =
    selected !== null ? overlays[selected] : null;

  return (
    <div className="flex w-full flex-col gap-3">
      {/* Canvas frame 9:16 */}
      <div
        ref={containerRef}
        className="relative mx-auto aspect-[9/16] w-full max-w-[340px] overflow-hidden rounded-2xl bg-black"
        onPointerMove={handlePointerMove}
        onPointerUp={handlePointerUp}
        onClick={() => setSelected(null)}
      >
        {mediaType === "video" ? (
          <video
            src={mediaUrl}
            className="absolute inset-0 h-full w-full object-contain"
            playsInline
            muted
            loop
            autoPlay
          />
        ) : (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={mediaUrl}
            alt="story"
            className="absolute inset-0 h-full w-full object-contain"
          />
        )}

        {overlays.map((o, index) => {
          const fontPx = Math.max(
            10,
            o.font_size * (containerSize.width || 300)
          );
          return (
            <div
              key={index}
              onClick={(e) => e.stopPropagation()}
              onPointerDown={(e) => handlePointerDown(e, index)}
              onDoubleClick={() => openTextEditor(index)}
              style={{
                position: "absolute",
                left: `${o.x * 100}%`,
                top: `${o.y * 100}%`,
                transform: `translate(-50%, -50%) rotate(${o.rotation ?? 0}deg)`,
                color: o.color,
                fontSize: `${fontPx}px`,
                lineHeight: 1.2,
                fontWeight: 700,
                textAlign: (o.align ?? "center") as React.CSSProperties["textAlign"],
                background: o.background || "transparent",
                padding: o.background ? "0.15em 0.35em" : 0,
                borderRadius: o.background ? "0.35em" : 0,
                maxWidth: "90%",
                whiteSpace: "pre-wrap",
                wordBreak: "break-word",
                cursor: "move",
                touchAction: "none",
                userSelect: "none",
                textShadow: o.background
                  ? "none"
                  : "0 1px 3px rgba(0,0,0,0.55)",
                outline:
                  selected === index ? "2px dashed rgba(255,255,255,0.7)" : "none",
                outlineOffset: 4,
              }}
            >
              {o.text}
            </div>
          );
        })}

        {/* Add-text FAB */}
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            openTextEditor(null);
          }}
          className="absolute right-2 top-2 z-10 flex items-center gap-1 rounded-full bg-black/55 px-3 py-1.5 text-xs font-semibold text-white backdrop-blur"
        >
          <BoldIcon name="add" size={16} tinted className="text-white" />
          متن
        </button>
      </div>

      {/* Toolbar for selected overlay */}
      {selectedOverlay && (
        <div className="mx-auto w-full max-w-[340px] space-y-3 rounded-xl border border-neutral-200 p-3 dark:border-neutral-800">
          <div className="flex items-center justify-between">
            <span className="text-xs font-semibold text-neutral-500">
              ویرایش متن
            </span>
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => openTextEditor(selected)}
                className="rounded-md bg-neutral-100 px-2 py-1 text-xs dark:bg-neutral-800"
              >
                تغییر نوشته
              </button>
              <button
                type="button"
                onClick={() => selected !== null && removeOverlay(selected)}
                className="rounded-md bg-red-50 px-2 py-1 text-xs text-red-600 dark:bg-red-950/40"
              >
                حذف
              </button>
            </div>
          </div>

          {/* Colors */}
          <div className="flex flex-wrap items-center gap-2">
            {TEXT_COLORS.map((c) => (
              <button
                key={c}
                type="button"
                onClick={() =>
                  selected !== null && updateOverlay(selected, { color: c })
                }
                className={`h-7 w-7 rounded-full border ${
                  selectedOverlay.color === c
                    ? "ring-2 ring-offset-2 ring-[#0095f6] dark:ring-offset-neutral-900"
                    : "border-neutral-300 dark:border-neutral-600"
                }`}
                style={{ backgroundColor: c }}
                aria-label={c}
              />
            ))}
          </div>

          {/* Highlight background toggle */}
          <button
            type="button"
            onClick={() =>
              selected !== null &&
              updateOverlay(selected, {
                background: selectedOverlay.background ? "" : "#000000",
              })
            }
            className="rounded-md bg-neutral-100 px-3 py-1 text-xs dark:bg-neutral-800"
          >
            {selectedOverlay.background ? "حذف پس‌زمینه متن" : "افزودن پس‌زمینه متن"}
          </button>

          {/* Font size */}
          <label className="flex items-center gap-3 text-xs text-neutral-500">
            اندازه
            <input
              type="range"
              min={MIN_FONT}
              max={MAX_FONT}
              step={0.005}
              value={selectedOverlay.font_size}
              onChange={(e) =>
                selected !== null &&
                updateOverlay(selected, {
                  font_size: parseFloat(e.target.value),
                })
              }
              className="flex-1 accent-[#0095f6]"
            />
          </label>
        </div>
      )}

      {/* Text input modal */}
      {editingIndex !== null && (
        <div className="fixed inset-0 z-[1001] flex flex-col bg-black/85 p-6">
          <div className="flex items-center justify-between">
            <button
              type="button"
              onClick={() => {
                setEditingIndex(null);
                setDraftText("");
              }}
              className="text-sm text-white/70"
            >
              انصراف
            </button>
            <button
              type="button"
              onClick={commitText}
              className="text-sm font-semibold text-[#0095f6]"
            >
              تأیید
            </button>
          </div>
          <div className="flex flex-1 items-center justify-center">
            <textarea
              autoFocus
              value={draftText}
              onChange={(e) => setDraftText(e.target.value)}
              placeholder="متن استوری…"
              rows={3}
              className="w-full max-w-sm resize-none bg-transparent text-center text-2xl font-bold text-white outline-none placeholder:text-white/40"
            />
          </div>
        </div>
      )}
    </div>
  );
}
