"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 { OkolinaContent, Place } from "./page";
import {
  BuildingStorefrontIcon,
  TruckIcon,
  SparklesIcon,
  SunIcon,
  ShoppingBagIcon,
  MapIcon,
  PhoneIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import type { ComponentType, SVGProps } from "react";

type SectionKey = keyof OkolinaContent;

function PlaceCard({
  place,
  sectionKey,
  index,
  onUpdate,
  onRemove,
}: {
  place: Place;
  sectionKey: SectionKey;
  index: number;
  onUpdate: (key: SectionKey, i: number, field: keyof Place, val: string) => void;
  onRemove: (key: SectionKey, i: number) => void;
}) {
  const { editMode } = useEditMode();

  return (
    <div className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm relative">
      {editMode && (
        <button
          onClick={() => onRemove(sectionKey, index)}
          className="absolute top-2 right-2 text-red-400 hover:text-red-600"
          title="Ukloni"
        >
          <XMarkIcon className="w-4 h-4" />
        </button>
      )}
      <div className="flex items-start justify-between gap-2 mb-1 pr-4">
        <h3 className="font-semibold text-gray-800">
          <EditableText
            value={place.name}
            onChange={(val) => onUpdate(sectionKey, index, "name", val)}
          />
        </h3>
        <span className="text-xs bg-sky-50 text-sky-700 px-2 py-0.5 rounded-full whitespace-nowrap shrink-0">
          <EditableText
            value={place.distance}
            onChange={(val) => onUpdate(sectionKey, index, "distance", val)}
          />
        </span>
      </div>
      <p className="text-sm text-gray-500">
        <EditableText
          value={place.note}
          onChange={(val) => onUpdate(sectionKey, index, "note", val)}
          multiline
        />
      </p>
      {(place.phone || editMode) && (
        <p className="text-xs text-sky-600 mt-1 flex items-center gap-1">
          <PhoneIcon className="w-3 h-3 shrink-0" />
          <EditableText
            value={place.phone ?? ""}
            onChange={(val) => onUpdate(sectionKey, index, "phone", val)}
          />
        </p>
      )}
    </div>
  );
}

const SECTIONS: { key: SectionKey; icon: ComponentType<SVGProps<SVGSVGElement>>; title: string }[] = [
  { key: "restaurants", icon: BuildingStorefrontIcon, title: "Restorani i kafići" },
  { key: "parking", icon: TruckIcon, title: "Parkiranje" },
  { key: "laundry", icon: SparklesIcon, title: "Pranje veša" },
  { key: "beaches", icon: SunIcon, title: "Plaže" },
  { key: "shops", icon: ShoppingBagIcon, title: "Prodavnice" },
];

function OkolinaInner({
  content,
  setContent,
}: {
  content: OkolinaContent;
  setContent: (c: OkolinaContent) => void;
}) {
  const { editMode, setDirty } = useEditMode();

  function updatePlace(key: SectionKey, i: number, field: keyof Place, val: string) {
    const next = { ...content, [key]: content[key].map((p, idx) => idx === i ? { ...p, [field]: val } : p) };
    setContent(next);
    setDirty(true);
  }

  function removePlace(key: SectionKey, i: number) {
    setContent({ ...content, [key]: content[key].filter((_, idx) => idx !== i) });
    setDirty(true);
  }

  function addPlace(key: SectionKey) {
    const newPlace: Place = { name: "Novo mjesto", distance: "X min", note: "Opis..." };
    setContent({ ...content, [key]: [...content[key], newPlace] });
    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"><MapIcon className="w-9 h-9" /> Okolina</h1>
      <p className="text-gray-500 mb-10">
        Korisna mjesta u blizini kuće — restorani, parking, plaže i više
      </p>

      {SECTIONS.map(({ key, icon, title }) => (
        <section key={key} className="mb-12">
          <h2 className="text-2xl font-bold text-sky-700 mb-4 flex items-center gap-2">
            {(() => { const Icon = icon; return <Icon className="w-6 h-6" />; })()}
            {title}
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {content[key].map((place, i) => (
              <PlaceCard
                key={i}
                place={place}
                sectionKey={key}
                index={i}
                onUpdate={updatePlace}
                onRemove={removePlace}
              />
            ))}
          </div>
          {editMode && (
            <button
              onClick={() => addPlace(key)}
              className="mt-3 text-sm text-sky-500 hover:text-sky-700 flex items-center gap-1"
            >
              + Dodaj mjesto
            </button>
          )}
        </section>
      ))}

      <div className="bg-sky-50 border border-sky-100 rounded-2xl p-6 text-sm text-sky-800">
        <strong>Napomena:</strong> Radno vrijeme i kontakti su okvirni — preporučujemo
        provjeru prije dolaska, posebno van turističke sezone.
      </div>
    </div>
  );
}

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

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