"use client";

import { useState } from "react";
import { ArrowSquareOut as ExternalLink, CircleNotch as Loader2, DownloadSimple as Download } from "@phosphor-icons/react";

import { avisoDaLoja } from "@/components/AvisoDaLoja";
import { getReadableTextColor } from "@/lib/color-contrast";
import { corDoSelo } from "@/lib/digitais/produto";

import type { TemaDosMembros } from "./tema";

/* Os materiais da aula (arquivo para baixar ou link), cada clique conferido pelo servidor. */

export type MaterialNaSala = { id: string; titulo: string; link: boolean; selo: string; detalhe: string | null };

export default function MateriaisDaAula({
  slug,
  materiais,
  cor,
  tema,
}: {
  slug: string;
  materiais: MaterialNaSala[];
  cor: string;
  tema: TemaDosMembros;
}) {
  const [abrindo, setAbrindo] = useState<string | null>(null);

  async function abrir(material: MaterialNaSala) {
    if (abrindo) return;
    /* O link abre numa aba nova, criada já no clique (senão o navegador bloqueia). */
    const janela = material.link ? window.open("", "_blank") : null;
    if (janela) janela.opener = null;
    setAbrindo(material.id);
    try {
      const resposta = await fetch(`/api/digitais/material/${material.id}`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ slug }),
      });
      const corpo = (await resposta.json().catch(() => null)) as { url?: string; error?: string } | null;
      if (!resposta.ok || !corpo?.url) throw new Error(corpo?.error || "Não foi possível abrir agora.");
      if (janela) janela.location.href = corpo.url;
      else window.location.href = corpo.url;
    } catch (e) {
      if (janela) janela.close();
      avisoDaLoja.erro(e instanceof Error ? e.message : "Não foi possível abrir agora.");
    } finally {
      setAbrindo(null);
    }
  }

  if (!materiais.length) return <p className={`py-4 text-[14px] ${tema.suave}`}>Este vídeo não tem materiais.</p>;

  return (
    <ul className={`divide-y ${tema.escuro ? "divide-white/10" : "divide-[#ECEEF3]"}`}>
      {materiais.map((material) => (
        <li key={material.id} className="flex items-center gap-3.5 py-3.5">
          <span
            className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-[10px] font-extrabold tracking-wide text-white"
            style={{ backgroundColor: corDoSelo(material.selo) }}
          >
            {material.selo}
          </span>
          <div className="min-w-0 flex-1">
            <div className="text-[14.5px] font-semibold leading-snug">{material.titulo}</div>
            {material.detalhe ? <div className={`mt-0.5 text-[12.5px] ${tema.suave}`}>{material.detalhe}</div> : null}
          </div>
          <button
            type="button"
            onClick={() => void abrir(material)}
            disabled={Boolean(abrindo)}
            className="inline-flex h-10 shrink-0 items-center gap-1.5 rounded-[10px] px-4 text-[12.5px] font-bold transition hover:opacity-90 disabled:opacity-60"
            style={{ backgroundColor: tema.escuro ? cor : "#1B2440", color: tema.escuro ? getReadableTextColor(cor) : "#fff" }}
          >
            {abrindo === material.id ? (
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
            ) : material.link ? (
              <ExternalLink className="h-3.5 w-3.5" />
            ) : (
              <Download className="h-3.5 w-3.5" />
            )}
            {material.link ? "Abrir" : "Baixar"}
          </button>
        </li>
      ))}
    </ul>
  );
}
