"use client";

import { Plus, X } from "lucide-react";
import { LIMITS } from "@/lib/limits";

interface ImageUrlInputProps {
  value: string[];
  onChange: (urls: string[]) => void;
}

export function ImageUrlInput({ value, onChange }: ImageUrlInputProps) {
  const urls = value.length > 0 ? value : [""];
  const max = LIMITS.MAX_IMAGE_URLS;

  function addField() {
    if (urls.length < max) {
      onChange([...urls, ""]);
    }
  }

  function removeField(index: number) {
    const next = urls.filter((_, i) => i !== index);
    onChange(next.length > 0 ? next : [""]);
  }

  function updateField(index: number, next: string) {
    const updated = [...urls];
    updated[index] = next;
    onChange(updated);
  }

  return (
    <div>
      <label className="mb-2 flex items-center justify-between">
        <span className="text-sm font-semibold text-neutral-700">
          Foto Trip (URL)
        </span>
        <span className="text-xs text-neutral-400">
          {urls.length}/{max}
        </span>
      </label>
      <div className="space-y-2">
        {urls.map((url, i) => (
          <div key={i} className="flex gap-2">
            <input
              type="url"
              value={url}
              onChange={(e) => updateField(i, e.target.value)}
              className="flex-1 rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
              placeholder={
                i === 0
                  ? "URL foto utama (cover)"
                  : `URL foto ${i + 1} (opsional)`
              }
            />
            {urls.length > 1 && (
              <button
                type="button"
                onClick={() => removeField(i)}
                aria-label={`Hapus foto ${i + 1}`}
                className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-neutral-200 text-neutral-400 hover:bg-red-50 hover:text-red-500"
              >
                <X size={16} strokeWidth={2} aria-hidden />
              </button>
            )}
          </div>
        ))}
      </div>
      {urls.length < max && (
        <button
          type="button"
          onClick={addField}
          className="mt-2 flex items-center gap-1 rounded-lg px-2 py-1 text-sm font-medium text-secondary-600 hover:bg-secondary-50"
        >
          <Plus size={15} strokeWidth={2} aria-hidden />
          Tambah foto
        </button>
      )}
      <p className="mt-1.5 text-xs text-neutral-400">
        Upload foto ke hosting (imgur, imgbb, dll) lalu paste URL-nya di sini.
      </p>
    </div>
  );
}
