"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import ImageUploader from "@/components/ImageUploader";
import TemplatePicker from "@/components/TemplatePicker";

interface MonumentImage {
  id: string;
  key: string;
  url: string;
  order: number;
}

interface EditData {
  title: string;
  description: string;
  templateId: number;
  bornDate: string;
  passedDate: string;
}

export default function EditPage() {
  const router = useRouter();
  const [data, setData] = useState<EditData>({ title: "", description: "", templateId: 1, bornDate: "", passedDate: "" });
  const [images, setImages] = useState<MonumentImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showPreview, setShowPreview] = useState(false);

  useEffect(() => {
    fetch("/api/user/monument")
      .then((r) => r.json())
      .then((d) => {
        setData({
          title: d.user.title || "",
          description: d.user.description || "",
          templateId: d.user.templateId || 1,
          bornDate: d.user.bornDate || "",
          passedDate: d.user.passedDate || "",
        });
        setImages(d.user.images || []);
      })
      .finally(() => setLoading(false));
  }, []);

  const handleDeleteImage = async (imageId: string) => {
    try {
      const res = await fetch(`/api/user/monument/image/${imageId}`, { method: "DELETE" });
      if (res.ok) {
        setImages(images.filter((img) => img.id !== imageId));
      }
    } catch {
      // ignore
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/user/monument", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (res.ok) {
        router.push("/dashboard");
      }
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <div className="flex min-h-screen items-center justify-center">Вчитување...</div>;
  }

  const imagePreviews = images.map((img) => ({ url: img.url, order: img.order }));

  return (
    <div className="min-h-screen bg-stone-50">
      <header className="border-b border-stone-200 bg-white">
        <div className="mx-auto max-w-6xl px-6 py-4 flex items-center justify-between">
          <h1 className="text-xl font-semibold text-stone-900">Уреди спомен</h1>
          <button
            onClick={() => setShowPreview(!showPreview)}
            className="rounded-lg border border-stone-200 px-4 py-2 text-sm font-medium text-stone-700 transition-colors hover:bg-stone-50 lg:hidden"
          >
            {showPreview ? "Уреди" : "Преглед"}
          </button>
        </div>
      </header>

      <div className="mx-auto max-w-6xl px-6 py-8">
        <div className="flex gap-8">
          <div className={`flex-1 min-w-0 ${showPreview ? "hidden lg:block" : ""}`}>
            <div className="space-y-6">
              <div>
                <label htmlFor="title" className="block text-sm font-medium text-stone-700">Име</label>
                <input
                  id="title"
                  type="text"
                  value={data.title}
                  onChange={(e) => setData({ ...data, title: e.target.value })}
                  className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                  maxLength={100}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="bornDate" className="block text-sm font-medium text-stone-700">Роден/а</label>
                  <input
                    id="bornDate"
                    type="text"
                    value={data.bornDate}
                    onChange={(e) => setData({ ...data, bornDate: e.target.value })}
                    placeholder="нпр. 1960"
                    className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2 text-stone-900 placeholder:text-stone-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    maxLength={50}
                  />
                </div>
                <div>
                  <label htmlFor="passedDate" className="block text-sm font-medium text-stone-700">Починат/а</label>
                  <input
                    id="passedDate"
                    type="text"
                    value={data.passedDate}
                    onChange={(e) => setData({ ...data, passedDate: e.target.value })}
                    placeholder="нпр. 2024"
                    className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2 text-stone-900 placeholder:text-stone-400 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    maxLength={50}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="description" className="block text-sm font-medium text-stone-700">Епитафија / Животна приказна</label>
                <textarea
                  id="description"
                  value={data.description}
                  onChange={(e) => setData({ ...data, description: e.target.value })}
                  rows={5}
                  className="mt-1 block w-full rounded-lg border border-stone-200 px-3 py-2 text-stone-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                  maxLength={2000}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-stone-700 mb-2">Шаблон</label>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    { id: 1, name: "Елеганција" },
                    { id: 2, name: "Кинематски" },
                    { id: 3, name: "Спокој" },
                  ].map((t) => (
                    <button
                      key={t.id}
                      onClick={() => setData({ ...data, templateId: t.id })}
                      className={`rounded-lg border-2 px-4 py-2 text-sm font-medium transition-colors ${
                        data.templateId === t.id
                          ? "border-primary bg-primary/5 text-primary"
                          : "border-stone-200 text-stone-700 hover:border-stone-300"
                      }`}
                    >
                      {t.name}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-stone-700 mb-2">Фотографии</label>
                {images.length > 0 ? (
                  <div className="grid grid-cols-3 gap-3">
                    {images.map((img) => (
                      <div key={img.id} className="group relative overflow-hidden rounded-lg border border-stone-200">
                        <img src={img.url} alt="" className="h-32 w-full object-cover" />
                        <button
                          onClick={() => handleDeleteImage(img.id)}
                          className="absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs text-white opacity-0 transition-opacity group-hover:opacity-100"
                        >
                          &times;
                        </button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-stone-400">Нема фотографии.</p>
                )}
                {images.length < 3 && (
                  <div className="mt-4">
                    <ImageUploader
                      images={images.map((img) => ({ key: img.key, order: img.order }))}
                      onImagesChange={() => router.refresh()}
                    />
                  </div>
                )}
              </div>

              <div className="flex gap-3 pt-4">
                <button onClick={handleSave} disabled={saving} className="rounded-lg bg-primary px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-primary-light disabled:opacity-50">
                  {saving ? "Зачувување..." : "Зачувај промени"}
                </button>
                <button onClick={() => router.push("/dashboard")} className="rounded-lg border border-stone-200 px-6 py-2 text-sm font-medium text-stone-700 transition-colors hover:bg-stone-50">
                  Откажи
                </button>
              </div>
            </div>
          </div>

          <div className={`w-[420px] flex-shrink-0 ${showPreview ? "" : "hidden lg:block"}`}>
            <div className="sticky top-8">
              <p className="mb-2 text-xs font-medium text-stone-500 uppercase tracking-wider">Преглед во живо</p>
              <div className="overflow-hidden rounded-lg border border-stone-300 shadow-md">
                <div className="h-[600px] overflow-y-auto">
                  <TemplatePicker
                    value={data.templateId}
                    onChange={(id) => setData({ ...data, templateId: id })}
                    title={data.title}
                    description={data.description}
                    bornDate={data.bornDate}
                    passedDate={data.passedDate}
                    images={imagePreviews}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}