"use client";

import { useState, useCallback } from "react";
import { EditModeProvider, useEditMode } from "@/components/EditModeProvider";
import { EditableText } from "@/components/EditableText";
import { EditModeToggle } from "@/components/EditModeToggle";
import type { VodicContent } from "./page";
import {
  HomeIcon,
  PhoneIcon,
  XMarkIcon,
  KeyIcon,
  WifiIcon,
  FireIcon,
  MoonIcon,
  SparklesIcon,
  SunIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  PlusIcon,
  ShieldCheckIcon,
  MapPinIcon,
  StarIcon,
  HeartIcon,
  BoltIcon,
  LifebuoyIcon,
  BuildingOfficeIcon,
  CameraIcon,
  MusicalNoteIcon,
  ShoppingBagIcon,
  TruckIcon,
  Bars3Icon,
} from "@heroicons/react/24/outline";
import type { ComponentType, SVGProps } from "react";

const SECTION_ICON_MAP: Record<string, ComponentType<SVGProps<SVGSVGElement>>> = {
  KeyIcon,
  WifiIcon,
  FireIcon,
  MoonIcon,
  SparklesIcon,
  SunIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  ShieldCheckIcon,
  MapPinIcon,
  StarIcon,
  HeartIcon,
  BoltIcon,
  LifebuoyIcon,
  BuildingOfficeIcon,
  CameraIcon,
  MusicalNoteIcon,
  ShoppingBagIcon,
  TruckIcon,
};

const ICON_NAMES = Object.keys(SECTION_ICON_MAP);

function IconPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
  const [open, setOpen] = useState(false);
  const Icon = SECTION_ICON_MAP[value];
  return (
    <div className="relative" onMouseDown={(e) => e.stopPropagation()}>
      <button
        onClick={() => setOpen((o) => !o)}
        className="p-1 rounded hover:bg-sky-100 border border-sky-300 bg-sky-50"
        title="Promeni ikonu"
        type="button"
      >
        {Icon ? <Icon className="w-5 h-5 text-sky-600" /> : <span className="text-xs text-gray-400">?</span>}
      </button>
      {open && (
        <div className="absolute z-10 top-8 left-0 bg-white border border-gray-200 rounded-xl shadow-lg p-2 grid grid-cols-5 gap-1 w-52">
          {ICON_NAMES.map((name) => {
            const I = SECTION_ICON_MAP[name];
            return (
              <button
                key={name}
                type="button"
                onClick={() => { onChange(name); setOpen(false); }}
                className={`p-1.5 rounded hover:bg-sky-50 ${value === name ? "bg-sky-100" : ""}`}
                title={name.replace("Icon", "")}
              >
                <I className="w-5 h-5 text-sky-600" />
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function VodicInner({ content, setContent }: {
  content: VodicContent;
  setContent: (c: VodicContent) => void;
}) {
  const { editMode, setDirty } = useEditMode();
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dropIndex, setDropIndex] = useState<number | null>(null);

  function moveSection(from: number, to: number) {
    if (from === to) return;
    const sections = [...content.sections];
    const [moved] = sections.splice(from, 1);
    sections.splice(to, 0, moved);
    setContent({ ...content, sections });
    setDirty(true);
  }

  function updateSectionTitle(i: number, val: string) {
    const sections = content.sections.map((s, idx) =>
      idx === i ? { ...s, title: val } : s
    );
    setContent({ ...content, sections });
    setDirty(true);
  }

  function updateSectionItem(si: number, ii: number, val: string) {
    const sections = content.sections.map((s, idx) => {
      if (idx !== si) return s;
      const items = s.items.map((item, jdx) => (jdx === ii ? val : item));
      return { ...s, items };
    });
    setContent({ ...content, sections });
    setDirty(true);
  }

  function addSectionItem(si: number) {
    const sections = content.sections.map((s, idx) =>
      idx === si ? { ...s, items: [...s.items, "Nova stavka"] } : s
    );
    setContent({ ...content, sections });
    setDirty(true);
  }

  function removeSectionItem(si: number, ii: number) {
    const sections = content.sections.map((s, idx) => {
      if (idx !== si) return s;
      return { ...s, items: s.items.filter((_, jdx) => jdx !== ii) };
    });
    setContent({ ...content, sections });
    setDirty(true);
  }

  function updateSectionIcon(si: number, icon: string) {
    const sections = content.sections.map((s, idx) =>
      idx === si ? { ...s, icon } : s
    );
    setContent({ ...content, sections });
    setDirty(true);
  }

  function addSection() {
    setContent({
      ...content,
      sections: [
        ...content.sections,
        { icon: "SparklesIcon", title: "Novi blok", items: ["Nova stavka"] },
      ],
    });
    setDirty(true);
  }

  function removeSection(si: number) {
    setContent({
      ...content,
      sections: content.sections.filter((_, idx) => idx !== si),
    });
    setDirty(true);
  }

  function updateContact(ci: number, field: "label" | "value", val: string) {
    const contacts = content.contacts.map((c, idx) =>
      idx === ci ? { ...c, [field]: val } : c
    );
    setContent({ ...content, contacts });
    setDirty(true);
  }

  function addContact() {
    setContent({
      ...content,
      contacts: [...content.contacts, { label: "Novi kontakt", value: "" }],
    });
    setDirty(true);
  }

  function removeContact(ci: number) {
    setContent({
      ...content,
      contacts: content.contacts.filter((_, idx) => idx !== ci),
    });
    setDirty(true);
  }

  return (
    <div className="max-w-5xl mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold text-sky-800 mb-2 flex items-center gap-3"><HomeIcon className="w-9 h-9" /> Vodič kroz kuću</h1>
      <p className="text-gray-500 mb-10">Sve što trebate znati za udoban boravak</p>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {content.sections.map((s, si) => (
          <div
            key={si}
            className={`bg-white rounded-2xl p-6 shadow-sm border transition-all relative ${
              dropIndex === si && dragIndex !== si ? "border-sky-400 ring-2 ring-sky-200" : "border-gray-100"
            } ${dragIndex === si ? "opacity-40" : "opacity-100"}`}
            draggable={editMode}
            onDragStart={editMode ? (e) => {
              if (!(e.target as HTMLElement).closest("[data-drag-handle]")) {
                e.preventDefault();
                return;
              }
              setDragIndex(si);
            } : undefined}
            onDragOver={editMode ? (e) => { e.preventDefault(); setDropIndex(si); } : undefined}
            onDrop={editMode ? () => { if (dragIndex !== null) moveSection(dragIndex, si); setDragIndex(null); setDropIndex(null); } : undefined}
            onDragEnd={editMode ? () => { setDragIndex(null); setDropIndex(null); } : undefined}
          >
            {editMode && (
              <div data-drag-handle className="absolute top-3 left-3 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing">
                <Bars3Icon className="w-4 h-4" />
              </div>
            )}
            {editMode && (
              <button
                onClick={() => removeSection(si)}
                className="absolute top-3 right-3 text-red-400 hover:text-red-600"
                title="Ukloni blok"
                type="button"
              >
                <XMarkIcon className="w-4 h-4" />
              </button>
            )}
            <h2 className={`text-lg font-semibold text-sky-700 mb-3 flex items-center gap-2 ${editMode ? "pl-5" : ""}`}>
              {editMode ? (
                <IconPicker value={s.icon} onChange={(icon) => updateSectionIcon(si, icon)} />
              ) : (
                (() => { const Icon = SECTION_ICON_MAP[s.icon]; return Icon ? <Icon className="w-5 h-5 shrink-0" /> : null; })()
              )}
              <EditableText
                value={s.title}
                onChange={(val) => updateSectionTitle(si, val)}
              />
            </h2>
            <ul className="space-y-1.5">
              {s.items.map((item, ii) => (
                <li key={ii} className="flex gap-2 text-gray-700 text-sm items-start">
                  <span className="text-sky-400 mt-0.5 shrink-0">•</span>
                  <EditableText
                    value={item}
                    onChange={(val) => updateSectionItem(si, ii, val)}
                    className="flex-1"
                  />
                  {editMode && (
                    <button
                      onClick={() => removeSectionItem(si, ii)}
                      className="text-red-400 hover:text-red-600 shrink-0 ml-1"
                      title="Ukloni stavku"
                    >
                      <XMarkIcon className="w-3.5 h-3.5" />
                    </button>
                  )}
                </li>
              ))}
            </ul>
            {editMode && (
              <button
                onClick={() => addSectionItem(si)}
                className="mt-3 text-xs text-sky-500 hover:text-sky-700 flex items-center gap-1"
              >
                + Dodaj stavku
              </button>
            )}
          </div>
        ))}
        {editMode && (
          <button
            onClick={addSection}
            className="flex flex-col items-center justify-center gap-2 rounded-2xl border-2 border-dashed border-sky-300 text-sky-400 hover:border-sky-500 hover:text-sky-600 min-h-[120px] transition-colors"
            type="button"
          >
            <PlusIcon className="w-7 h-7" />
            <span className="text-sm font-medium">Dodaj blok</span>
          </button>
        )}
      </div>

      <div className="mt-8 bg-amber-50 border border-amber-200 rounded-2xl p-6">
        <h2 className="text-lg font-semibold text-amber-700 mb-2 flex items-center gap-2">
          <PhoneIcon className="w-5 h-5 shrink-0" />
          <EditableText
            value={content.contactsTitle}
            onChange={(val) => { setContent({ ...content, contactsTitle: val }); setDirty(true); }}
          />
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
          {content.contacts.map((c, ci) => (
            <div key={ci} className="relative">
              {editMode && (
                <button
                  onClick={() => removeContact(ci)}
                  className="absolute -top-1 -right-1 text-red-400 hover:text-red-600"
                  title="Ukloni kontakt"
                  type="button"
                >
                  <XMarkIcon className="w-3.5 h-3.5" />
                </button>
              )}
              <p className="font-medium text-gray-700">
                <EditableText
                  value={c.label}
                  onChange={(val) => updateContact(ci, "label", val)}
                />
              </p>
              <p className="text-gray-500">
                <EditableText
                  value={c.value}
                  onChange={(val) => updateContact(ci, "value", val)}
                />
              </p>
            </div>
          ))}
          {editMode && (
            <button
              onClick={addContact}
              className="flex items-center gap-1 text-amber-500 hover:text-amber-700 text-xs font-medium self-center"
              type="button"
            >
              <PlusIcon className="w-4 h-4" /> Dodaj kontakt
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

export function VodicClient({
  initialContent,
  isAdmin,
}: {
  initialContent: VodicContent;
  isAdmin: boolean;
}) {
  const [content, setContent] = useState(initialContent);
  const getContent = useCallback(() => content, [content]);

  return (
    <EditModeProvider>
      <VodicInner content={content} setContent={setContent} />
      {isAdmin && <EditModeToggle page="vodic" getContent={getContent} />}
    </EditModeProvider>
  );
}
