'use client';

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

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

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

      <form action={formAction} className="flex flex-wrap items-center gap-2">
        <ImageCropperField
          name="logo"
          maxDimension={500}
          accept="image/png,image/jpeg,image/webp,image/svg+xml"
          buttonLabel="Elegir logo"
          previewClassName="h-20 w-32 rounded-lg"
          previewImgClassName="h-full w-full object-contain"
          allowSvgPassthrough
          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 logo'}
        </button>
      </form>

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