"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 { LokacijaContent } from "./page";
import {
  MapPinIcon,
  DevicePhoneMobileIcon,
  PlusIcon,
  TrashIcon,
} from "@heroicons/react/24/outline";

function LokacijaInner({
  content,
  setContent,
}: {
  content: LokacijaContent;
  setContent: (c: LokacijaContent) => void;
}) {
  const { setDirty, editMode } = useEditMode();
  const [activeMapSrc, setActiveMapSrc] = useState(content.mapsEmbed);

  function buildMapsEmbed(lat: string, lng: string): string {
    const latNum = parseFloat(lat.replace(/[^\d.\-]/g, ""));
    const lngNum = parseFloat(lng.replace(/[^\d.\-]/g, ""));
    if (isNaN(latNum) || isNaN(lngNum)) return content.mapsEmbed;
    return `https://maps.google.com/maps?q=${latNum},${lngNum}&output=embed&z=19&t=k`;
  }

  function update(path: string[], val: string) {
    const next = JSON.parse(JSON.stringify(content));
    let obj: Record<string, unknown> = next;
    for (let i = 0; i < path.length - 1; i++) obj = obj[path[i]] as Record<string, unknown>;
    obj[path[path.length - 1]] = val;
    setContent(next);
    setDirty(true);
  }

  function updateGps(index: number, field: "label" | "lat" | "lng", val: string) {
    const next: LokacijaContent = JSON.parse(JSON.stringify(content));
    next.gps[index][field] = val;
    if (field === "lat" || field === "lng") {
      const lat = field === "lat" ? val : next.gps[index].lat;
      const lng = field === "lng" ? val : next.gps[index].lng;
      const newSrc = buildMapsEmbed(lat, lng);
      if (index === 0) next.mapsEmbed = newSrc;
      setActiveMapSrc(newSrc);
    }
    setContent(next);
    setDirty(true);
  }

  function addGps() {
    const next: LokacijaContent = JSON.parse(JSON.stringify(content));
    next.gps.push({ label: "Nova lokacija", lat: "", lng: "" });
    setContent(next);
    setDirty(true);
  }

  function removeGps(index: number) {
    const next: LokacijaContent = JSON.parse(JSON.stringify(content));
    next.gps.splice(index, 1);
    if (next.gps.length > 0) {
      next.mapsEmbed = buildMapsEmbed(next.gps[0].lat, next.gps[0].lng);
    }
    setContent(next);
    setDirty(true);
  }

  function handleGpsClick(entry: { label: string; lat: string; lng: string }) {
    const url = buildMapsEmbed(entry.lat, entry.lng);
    setActiveMapSrc(url);
  }

  return (
    <div>
      {/* Naslov */}
      <div className="max-w-5xl mx-auto px-4 pt-12 pb-1">
        <h1 className="text-4xl font-bold text-sky-800 mb-2 flex items-center gap-3">
          <svg className="w-9 h-9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8.25 21v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21m0 0h4.5V3.545M12.75 21h7.5V10.75M2.25 21h1.5m18 0h-18M2.25 9l4.5-1.636M18.75 3l-1.5.545m0 6.205 3 1m1.5.5-1.5-.5M6.75 7.364V3h-3v18m3-13.636 10.5-3.819"/>
          </svg>
          Lokacija
        </h1>
        <p className="text-gray-500">Kako nas pronaći i kako doći</p>
      </div>

      <div className="max-w-5xl mx-auto px-4 pt-2 pb-10 space-y-8">
        {/* Mapa */}
        <div className="rounded-2xl overflow-hidden border border-gray-100 shadow-sm h-[410px]">
          <iframe
            key={activeMapSrc}
            src={activeMapSrc}
            width="100%"
            height="100%"
            style={{ border: 0, display: "block" }}
            allowFullScreen
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
            title="Mapa lokacije"
          />
        </div>

        {/* GPS koordinate */}
        <div className="bg-sky-50 rounded-2xl p-5 border border-sky-100">
          <h3 className="font-semibold text-sky-700 mb-3 flex items-center gap-2">
            <DevicePhoneMobileIcon className="w-4 h-4" /> GPS koordinate
          </h3>
          <ul className="space-y-2">
            {content.gps.map((entry, i) => (
              <li
                key={i}
                className={`flex items-center gap-2 group ${editMode ? "" : "cursor-pointer"}`}
              >
                {editMode ? (
                  <>
                    <EditableText
                      value={entry.label}
                      onChange={(val) => updateGps(i, "label", val)}
                      className="font-medium text-sky-800 text-sm min-w-[80px]"
                    />
                    <span className="text-gray-400 text-sm">:</span>
                    <EditableText
                      value={entry.lat}
                      onChange={(val) => updateGps(i, "lat", val)}
                      className="font-mono text-sm text-gray-700"
                    />
                    <span className="text-gray-400 text-sm">,</span>
                    <EditableText
                      value={entry.lng}
                      onChange={(val) => updateGps(i, "lng", val)}
                      className="font-mono text-sm text-gray-700"
                    />
                    <button
                      onClick={() => removeGps(i)}
                      className="ml-auto text-red-400 hover:text-red-600 transition-colors"
                      title="Ukloni"
                    >
                      <TrashIcon className="w-4 h-4" />
                    </button>
                  </>
                ) : (
                  <button
                    onClick={() => handleGpsClick(entry)}
                    className="flex items-center gap-2 text-left w-full rounded-lg px-2 py-1 hover:bg-sky-100 transition-colors"
                  >
                    <MapPinIcon className="w-4 h-4 text-sky-500 shrink-0" />
                    <span className="font-medium text-sky-800 text-sm">{entry.label}:</span>
                    <span className="font-mono text-sm text-gray-700">
                      {entry.lat}, {entry.lng}
                    </span>
                  </button>
                )}
              </li>
            ))}
          </ul>
          {editMode && (
            <button
              onClick={addGps}
              className="mt-3 flex items-center gap-1 text-sm text-sky-600 hover:text-sky-800 transition-colors"
            >
              <PlusIcon className="w-4 h-4" /> Dodaj lokaciju
            </button>
          )}
        </div>

        {/* Informativni blokovi */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <h2 className="text-xl font-semibold text-sky-700 mb-3 flex items-center gap-2">
              <MapPinIcon className="w-5 h-5" />
              <EditableText value={content.titles.address} onChange={(val) => update(["titles", "address"], val)} />
            </h2>
            <p className="text-gray-700 leading-relaxed whitespace-pre-line">
              <EditableText
                value={content.address}
                onChange={(val) => update(["address"], val)}
                multiline
                markdown
              />
            </p>
          </div>

          <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <h2 className="text-xl font-semibold text-sky-700 mb-3 flex items-center gap-2">
              <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                <path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/>
              </svg>
              <EditableText value={content.titles.directions} onChange={(val) => update(["titles", "directions"], val)} />
            </h2>
            <p className="text-gray-700 whitespace-pre-line">
              <EditableText
                value={content.directions}
                onChange={(val) => update(["directions"], val)}
                multiline
                markdown
              />
            </p>
          </div>

          <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <h2 className="text-xl font-semibold text-sky-700 mb-3 flex items-center gap-2">
              <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="3" width="18" height="18" rx="3" />
                <path d="M9 17V7h4a3 3 0 0 1 0 6H9" />
              </svg>
              <EditableText value={content.titles.parking} onChange={(val) => update(["titles", "parking"], val)} />
            </h2>
            <p className="text-gray-700 whitespace-pre-line">
              <EditableText
                value={content.parking}
                onChange={(val) => update(["parking"], val)}
                multiline
                markdown
              />
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

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

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