"use client";

import { useState } from "react";

export function ImageUrlInput() {
  const [urls, setUrls] = useState<string[]>([""]);

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

  function removeField(index: number) {
    setUrls(urls.filter((_, i) => i !== index));
  }

  function updateField(index: number, value: string) {
    const updated = [...urls];
    updated[index] = value;
    setUrls(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}/5</span>
      </label>
      <div className="space-y-2">
        {urls.map((url, i) => (
          <div key={i} className="flex gap-2">
            <input
              name="imageUrls"
              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)}
                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"
              >
                ✕
              </button>
            )}
          </div>
        ))}
      </div>
      {urls.length < 5 && (
        <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"
        >
          + 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>
  );
}
