"use client";

import Image from "next/image";
import { useState, useTransition } from "react";

import { MediaUploader } from "@/components/admin/media/MediaUploader";
import { isInlineImageSrc } from "@/lib/image-utils";

type GalleryItem = {
  id: string;
  mediaId: string;
  sortOrder: number;
  media: {
    url: string;
    alt: string | null;
  };
};

export function SubmissionGalleryManager({
  submissionId,
  companyName,
  initialItems,
}: {
  submissionId: string;
  companyName: string;
  initialItems: GalleryItem[];
}) {
  const [items, setItems] = useState(initialItems);
  const [message, setMessage] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  async function updateGallery(
    method: "POST" | "PATCH" | "DELETE",
    body: Record<string, unknown>,
    successMessage: string,
  ) {
    const response = await fetch(`/api/admin/submissions/${submissionId}/gallery`, {
      method,
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(body),
    });

    const payload = (await response.json()) as {
      items?: GalleryItem[];
      message?: string;
    };

    if (!response.ok) {
      throw new Error(payload.message || "Ažuriranje galerije nije uspelo.");
    }

    setItems(payload.items ?? []);
    setMessage(successMessage);
  }

  function handleMove(index: number, direction: -1 | 1) {
    const nextIndex = index + direction;

    if (nextIndex < 0 || nextIndex >= items.length) {
      return;
    }

    const reordered = [...items];
    const [moved] = reordered.splice(index, 1);

    if (!moved) {
      return;
    }

    reordered.splice(nextIndex, 0, moved);

    startTransition(async () => {
      try {
        await updateGallery(
          "PATCH",
          {
            orderedMediaIds: reordered.map((item) => item.mediaId),
          },
          "Redosled galerije je sačuvan.",
        );
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Čuvanje redosleda nije uspelo.",
        );
      }
    });
  }

  function handleRemove(mediaId: string) {
    startTransition(async () => {
      try {
        await updateGallery(
          "DELETE",
          { mediaId },
          "Fotografija je uklonjena iz galerije.",
        );
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Brisanje fotografije nije uspelo.",
        );
      }
    });
  }

  function handleUploaded(uploadedItems: Array<{ id: string }>) {
    startTransition(async () => {
      try {
        await updateGallery(
          "POST",
          {
            mediaIds: uploadedItems.map((item) => item.id),
          },
          "Nove fotografije su dodate u galeriju prijave.",
        );
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Dodavanje fotografija nije uspelo.",
        );
      }
    });
  }

  return (
    <div className="space-y-6">
      <MediaUploader
        directory={`submissions/${submissionId}/gallery`}
        title="Dodaj fotografije u galeriju prijave"
        description="Uploaduj dodatne slike i odmah ih poveži sa ovom prijavom. Redosled ispod utiče na budući profil."
        buttonLabel="Dodaj u galeriju"
        onUploaded={handleUploaded}
      />

      {message ? (
        <p className="text-sm text-muted-foreground">{message}</p>
      ) : null}

      {items.length ? (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {items.map((item, index) => (
            <div
              key={item.id}
              className="rounded-[1.5rem] border border-border bg-white/80 p-3"
            >
              <Image
                src={item.media.url}
                alt={item.media.alt ?? companyName}
                width={600}
                height={420}
                className="h-36 w-full rounded-[1.25rem] object-cover"
                unoptimized={isInlineImageSrc(item.media.url)}
              />
              <div className="mt-3 flex items-center justify-between gap-2 text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground">
                <span>Pozicija {index + 1}</span>
                {isPending ? <span>Čuvanje...</span> : null}
              </div>
              <div className="mt-3 grid grid-cols-3 gap-2">
                <button
                  type="button"
                  onClick={() => handleMove(index, -1)}
                  className="ghost-button justify-center px-3 py-2 text-xs"
                  disabled={index === 0 || isPending}
                >
                  Gore
                </button>
                <button
                  type="button"
                  onClick={() => handleMove(index, 1)}
                  className="ghost-button justify-center px-3 py-2 text-xs"
                  disabled={index === items.length - 1 || isPending}
                >
                  Dole
                </button>
                <button
                  type="button"
                  onClick={() => handleRemove(item.mediaId)}
                  className="rounded-full border border-danger/20 bg-danger/8 px-3 py-2 text-xs font-semibold text-danger"
                  disabled={isPending}
                >
                  Ukloni
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="rounded-[1.5rem] border border-border bg-white/70 px-4 py-4 text-sm text-muted-foreground">
          Galerija je prazna. Upload iznad odmah dodaje fotografije u prijavu.
        </div>
      )}
    </div>
  );
}
