'use client';

import { useActionState } from 'react';
import {
  subirAboutFoto,
  quitarAboutFoto,
  type LogoResult,
} from '@/app/panel/empresa/actions';
import ImageCropperField from '@/components/panel/ImageCropperField';

export default function AboutFotoUploader({ fotoUrl }: { fotoUrl: string | null }) {
  const [state, formAction, pending] = useActionState<LogoResult | null, FormData>(
    subirAboutFoto,
    null
  );

  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-center gap-4">
        <div className="w-24 h-24 rounded-lg border border-gray-200 bg-gray-50 flex items-center justify-center overflow-hidden">
          {fotoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={fotoUrl} alt="Foto" className="w-full h-full object-cover" />
          ) : (
            <span className="text-xs text-gray-400">Sin foto</span>
          )}
        </div>
        {fotoUrl && (
          <form action={quitarAboutFoto}>
            <button type="submit" className="text-xs text-red-500 hover:underline">
              Quitar foto
            </button>
          </form>
        )}
      </div>

      <form action={formAction} className="flex flex-wrap items-center gap-2">
        <ImageCropperField
          name="aboutFoto"
          maxDimension={500}
          accept="image/png,image/jpeg,image/webp"
          buttonLabel="Elegir foto"
          previewClassName="h-24 w-24 rounded-lg"
          disabled={pending}
        />
        <button
          type="submit"
          disabled={pending}
          className="rounded-lg bg-primary-700 px-4 py-1.5 text-sm font-medium text-white transition hover:bg-primary-900 disabled:opacity-50"
        >
          {pending ? 'Subiendo…' : 'Subir foto'}
        </button>
      </form>

      {state?.error && <p className="text-sm text-red-600">{state.error}</p>}
      {state?.ok && <p className="text-sm text-green-600">Foto actualizada ✓</p>}
      <p className="text-xs text-gray-400">
        PNG, JPG o WEBP. Se recorta y optimiza a WebP (máx. 500 px).
      </p>
    </div>
  );
}
