'use client';

import { useActionState, useEffect, useRef } from 'react';
import { subirFotoGaleria, type GaleriaResult } from '@/app/panel/galeria/actions';
import ImageCropperField from '@/components/panel/ImageCropperField';

export default function GaleriaUploader({
  total,
  max,
}: {
  total: number;
  max: number;
}) {
  const [state, formAction, pending] = useActionState<GaleriaResult | null, FormData>(
    subirFotoGaleria,
    null
  );
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (state?.ok) formRef.current?.reset();
  }, [state]);

  const lleno = total >= max;

  return (
    <div className="flex flex-col gap-3 rounded-xl border border-gray-200 bg-white p-5">
      <div className="flex items-baseline justify-between">
        <h2 className="text-sm font-semibold text-gray-900">Añadir foto</h2>
        <span className="text-xs text-gray-400">
          {total}/{max} fotos
        </span>
      </div>

      <form ref={formRef} action={formAction} className="flex flex-col gap-3">
        <ImageCropperField
          key={total}
          name="foto"
          maxDimension={1200}
          accept="image/png,image/jpeg,image/webp"
          buttonLabel="Elegir foto"
          previewClassName="h-24 w-32 rounded-lg"
          disabled={lleno || pending}
        />
        <input
          type="text"
          name="titulo"
          maxLength={80}
          placeholder="Título opcional (ej. Cocina en Chamberí)"
          disabled={lleno || pending}
          className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-gray-400 focus:outline-none disabled:opacity-50"
        />
        <div>
          <button
            type="submit"
            disabled={lleno || pending}
            className="inline-flex items-center justify-center rounded-lg bg-primary-700 px-4 py-2 text-sm font-semibold text-white transition hover:bg-primary-900 disabled:opacity-50"
          >
            {pending ? 'Subiendo…' : 'Añadir foto'}
          </button>
        </div>
      </form>

      {lleno && (
        <p className="text-sm text-amber-600">Has alcanzado el máximo de {max} fotos.</p>
      )}
      {state?.error && <p className="text-sm text-red-600">{state.error}</p>}
      {state?.ok && <p className="text-sm text-green-600">Foto añadida ✓</p>}
      <p className="text-xs text-gray-400">
        PNG, JPG o WEBP. Se recorta y optimiza a WebP (máx. 1200 px).
      </p>
    </div>
  );
}
