"use client";

/* eslint-disable @next/next/no-img-element */

import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

export type PostGalleryItem = {
  id: string;
  preview: string;
  file?: File | null;
  existingPath?: string;
};

type Props = {
  items: PostGalleryItem[];
  onChange: (items: PostGalleryItem[]) => void;
  max?: number;
};

export default function PostImageGallery({
  items,
  onChange,
  max = 10,
}: Props) {
  const { t } = useTranslation("common");

  const move = (index: number, dir: -1 | 1) => {
    const next = index + dir;
    if (next < 0 || next >= items.length) return;
    const copy = [...items];
    const tmp = copy[index];
    copy[index] = copy[next];
    copy[next] = tmp;
    onChange(copy);
  };

  const removeAt = (index: number) => {
    const target = items[index];
    if (target?.preview?.startsWith("blob:")) {
      URL.revokeObjectURL(target.preview);
    }
    onChange(items.filter((_, i) => i !== index));
  };

  const addFiles = (files: FileList | null) => {
    if (!files?.length) return;
    const room = max - items.length;
    if (room <= 0) return;
    const picked = Array.from(files)
      .filter((f) => f.type.startsWith("image/"))
      .slice(0, room)
      .map((file) => ({
        id: `new-${Date.now()}-${Math.random()}`,
        file,
        preview: URL.createObjectURL(file),
      }));
    if (picked.length) onChange([...items, ...picked]);
  };

  return (
    <div className="space-y-2 border-t border-neutral-200 p-3 dark:border-neutral-800">
      <div className="grid grid-cols-4 gap-2">
        {items.map((item, index) => (
          <div
            key={item.id}
            className="relative aspect-square overflow-hidden rounded-md bg-neutral-200 dark:bg-neutral-800"
          >
            <img
              src={item.preview}
              alt=""
              className="h-full w-full object-cover"
            />
            <div className="absolute inset-x-0 bottom-0 flex justify-between gap-0.5 bg-black/50 p-0.5">
              <button
                type="button"
                onClick={() => move(index, -1)}
                disabled={index === 0}
                className="rounded bg-white/20 px-1 text-[10px] text-white disabled:opacity-30"
                aria-label={t("posts.moveRight")}
              >
                ‹
              </button>
              <button
                type="button"
                onClick={() => removeAt(index)}
                className="rounded bg-red-500/80 px-1 text-[10px] text-white"
                aria-label={t("posts.removeMedia")}
              >
                ×
              </button>
              <button
                type="button"
                onClick={() => move(index, 1)}
                disabled={index === items.length - 1}
                className="rounded bg-white/20 px-1 text-[10px] text-white disabled:opacity-30"
                aria-label={t("posts.moveLeft")}
              >
                ›
              </button>
            </div>
          </div>
        ))}
        {items.length < max ? (
          <label className="flex aspect-square cursor-pointer items-center justify-center rounded-md border border-dashed border-neutral-300 dark:border-neutral-700">
            <BoldIcon name="add" size={20} className="block dark:invert" />
            <input
              type="file"
              accept="image/*"
              multiple
              className="hidden"
              onChange={(e) => {
                addFiles(e.target.files);
                e.target.value = "";
              }}
            />
          </label>
        ) : null}
      </div>
    </div>
  );
}
