'use client';

import { useActionState, useState } from 'react';
import { useFormStatus } from 'react-dom';
import type { EnviarOpinionResult } from '@/app/opinion/actions';

const MAX_FOTOS = 4;

const inputClass =
  'w-full px-4 py-3 text-base font-sans text-dark bg-white border-[1.5px] border-gray-200 rounded-lg transition-all duration-150 outline-none placeholder:text-gray-400 focus:border-black focus:shadow-[0_0_0_3px_rgba(0,0,0,0.06)]';

function Estrella({ filled }: { filled: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={`w-9 h-9 ${filled ? 'fill-yellow-400' : 'fill-gray-200'}`}
      aria-hidden="true"
    >
      <path d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" />
    </svg>
  );
}

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      className="btn btn-primary btn-lg w-full justify-center mt-1 disabled:opacity-60 disabled:cursor-not-allowed"
      disabled={pending}
      aria-busy={pending}
    >
      {pending ? 'Enviando...' : 'Enviar mi opinión'}
    </button>
  );
}

export default function OpinionForm({
  action,
  nombreCliente,
}: {
  action: (prev: EnviarOpinionResult | null, formData: FormData) => Promise<EnviarOpinionResult>;
  nombreCliente: string;
}) {
  const [state, formAction] = useActionState(action, null);
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);
  const [previews, setPreviews] = useState<string[]>([]);

  const handleFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []).slice(0, MAX_FOTOS);
    previews.forEach((url) => URL.revokeObjectURL(url));
    setPreviews(files.map((f) => URL.createObjectURL(f)));
  };

  if (state?.ok) {
    return (
      <div className="bg-white border border-gray-200 rounded-xl p-8 text-center flex flex-col gap-3">
        <span className="text-4xl" aria-hidden="true">
          🙌
        </span>
        <h2 className="text-xl font-black text-black">¡Gracias por tu opinión!</h2>
        <p className="text-sm text-gray-500">
          La hemos recibido correctamente. Aparecerá en la web del reformista una vez la revise.
        </p>
      </div>
    );
  }

  return (
    <form action={formAction} className="flex flex-col gap-5">
      <input type="hidden" name="rating" value={rating} />

      <div className="flex flex-col gap-2">
        <span className="text-sm font-semibold text-dark">Tu valoración</span>
        <div className="flex gap-1" role="radiogroup" aria-label="Valoración de 1 a 5 estrellas">
          {[1, 2, 3, 4, 5].map((n) => (
            <button
              key={n}
              type="button"
              onClick={() => setRating(n)}
              onMouseEnter={() => setHover(n)}
              onMouseLeave={() => setHover(0)}
              aria-label={`${n} estrella${n > 1 ? 's' : ''}`}
              aria-checked={rating === n}
              role="radio"
              className="p-0.5"
            >
              <Estrella filled={n <= (hover || rating)} />
            </button>
          ))}
        </div>
      </div>

      <div className="flex flex-col gap-2">
        <label htmlFor="texto" className="text-sm font-semibold text-dark">
          ¿Cómo fue tu experiencia?
        </label>
        <textarea
          id="texto"
          name="texto"
          rows={5}
          placeholder="Cuéntanos cómo fue el trato, el resultado de la reforma, los plazos…"
          className={inputClass}
        />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="nombre" className="text-sm font-semibold text-dark">
            Tu nombre
          </label>
          <input
            id="nombre"
            name="nombre"
            type="text"
            defaultValue={nombreCliente}
            className={inputClass}
          />
        </div>
        <div className="flex flex-col gap-2">
          <label htmlFor="contexto" className="text-sm font-semibold text-dark">
            Reforma <span className="text-gray-400 font-normal">(opcional)</span>
          </label>
          <input
            id="contexto"
            name="contexto"
            type="text"
            placeholder="Reforma de cocina · Madrid"
            className={inputClass}
          />
        </div>
      </div>

      <div className="flex flex-col gap-2">
        <label htmlFor="fotos" className="text-sm font-semibold text-dark">
          Sube fotos del resultado{' '}
          <span className="text-gray-400 font-normal">(opcional, hasta {MAX_FOTOS})</span>
        </label>
        <input
          id="fotos"
          name="fotos"
          type="file"
          accept="image/*"
          multiple
          onChange={handleFiles}
          className="block w-full text-sm text-gray-600 file:mr-4 file:py-2.5 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-black file:text-white hover:file:bg-gray-800 file:cursor-pointer cursor-pointer"
        />
        {previews.length > 0 && (
          <div className="flex flex-wrap gap-3 mt-2">
            {previews.map((url, i) => (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                key={i}
                src={url}
                alt=""
                className="w-20 h-20 object-cover rounded-lg border border-gray-200"
              />
            ))}
          </div>
        )}
      </div>

      {state?.error && <p className="text-sm text-red-600">{state.error}</p>}

      <SubmitButton />
    </form>
  );
}
