"use client";

import { useState } from "react";
import Image from "next/image";
import { X, ShoppingBag, Plus, Minus, ShoppingCart, Check } from "lucide-react";
import { cn, formatarMoeda, GENERO_LABEL } from "@/lib/utils";
import { useCarrinho } from "@/lib/carrinho-store";

type Tamanho = {
  id: string;
  tamanho: string;
  preco: any;
  estoque: number;
};

type Aluno = {
  id: string;
  nome: string;
  turma?: string;
};

export function FardamentoDetalheModal({
  fardamento,
  alunos,
  onClose,
}: {
  fardamento: any;
  alunos: Aluno[];
  onClose: () => void;
}) {
  const [imagemAtiva, setImagemAtiva] = useState(0);
  const [tamanhoSelecionado, setTamanhoSelecionado] = useState<Tamanho | null>(null);
  const [alunoSelecionado, setAlunoSelecionado] = useState<string>(
    alunos.length === 1 ? alunos[0].id : ""
  );
  const [quantidade, setQuantidade] = useState(1);
  const [adicionado, setAdicionado] = useState(false);

  const adicionarAoCarrinho = useCarrinho((s) => s.adicionarItem);

  function handleAdicionar() {
    if (!tamanhoSelecionado || !alunoSelecionado) return;

    const aluno = alunos.find((a) => a.id === alunoSelecionado)!;

    adicionarAoCarrinho({
      fardamentoTamanhoId: tamanhoSelecionado.id,
      fardamentoNome: fardamento.nome,
      tamanho: tamanhoSelecionado.tamanho,
      preco: Number(tamanhoSelecionado.preco),
      quantidade,
      imagem: fardamento.imagens[0] ?? null,
      alunoId: aluno.id,
      alunoNome: aluno.nome,
    });

    setAdicionado(true);
    setTimeout(() => {
      setAdicionado(false);
      onClose();
    }, 1000);
  }

  const podeAdicionar = tamanhoSelecionado && alunoSelecionado;

  return (
    <div className="fixed inset-0 z-50 flex items-end">
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />
      <div className="relative bg-white w-full max-h-[92dvh] overflow-y-auto rounded-t-3xl shadow-2xl">
        {/* Botão fechar */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 z-10 bg-white/90 backdrop-blur-sm p-2 rounded-full shadow"
        >
          <X size={20} />
        </button>

        {/* Galeria de imagens */}
        <div className="relative bg-gray-100 aspect-square">
          {fardamento.imagens.length > 0 ? (
            <>
              <Image
                src={fardamento.imagens[imagemAtiva]}
                alt={fardamento.nome}
                fill
                className="object-cover"
              />
              {fardamento.imagens.length > 1 && (
                <div className="absolute bottom-3 left-0 right-0 flex justify-center gap-1.5">
                  {fardamento.imagens.map((_: string, i: number) => (
                    <button
                      key={i}
                      onClick={() => setImagemAtiva(i)}
                      className={cn(
                        "w-2 h-2 rounded-full transition-all",
                        i === imagemAtiva
                          ? "bg-white scale-125"
                          : "bg-white/50"
                      )}
                    />
                  ))}
                </div>
              )}
            </>
          ) : (
            <div className="flex items-center justify-center h-full text-gray-300">
              <ShoppingBag size={64} />
            </div>
          )}
        </div>

        {/* Conteúdo */}
        <div className="p-5 space-y-5">
          {/* Nome e preço */}
          <div>
            <p className="text-xs text-gray-400 uppercase tracking-wide">
              {GENERO_LABEL[fardamento.genero]} · {fardamento.categoria}
            </p>
            <h2 className="text-xl font-bold text-gray-900 mt-1">
              {fardamento.nome}
            </h2>
            {fardamento.descricao && (
              <p className="text-gray-500 text-sm mt-1">{fardamento.descricao}</p>
            )}
          </div>

          {/* Seleção de tamanho */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-semibold text-gray-900">Tamanho</h3>
              {tamanhoSelecionado && (
                <span className="text-primary-700 font-bold text-lg">
                  {formatarMoeda(tamanhoSelecionado.preco)}
                </span>
              )}
            </div>
            <div className="flex flex-wrap gap-2">
              {fardamento.tamanhos.map((t: Tamanho) => (
                <button
                  key={t.id}
                  onClick={() => setTamanhoSelecionado(t)}
                  className={cn(
                    "px-4 py-2 rounded-xl border-2 font-medium text-sm transition-all",
                    tamanhoSelecionado?.id === t.id
                      ? "border-primary-700 bg-primary-50 text-primary-700"
                      : "border-gray-200 text-gray-700 hover:border-gray-300"
                  )}
                >
                  {t.tamanho}
                  <span className="text-xs text-gray-400 ml-1">
                    ({t.estoque})
                  </span>
                </button>
              ))}
            </div>
          </div>

          {/* Selecionar aluno (se mais de 1) */}
          {alunos.length > 1 && (
            <div>
              <h3 className="font-semibold text-gray-900 mb-3">Para qual aluno?</h3>
              <div className="space-y-2">
                {alunos.map((a) => (
                  <button
                    key={a.id}
                    onClick={() => setAlunoSelecionado(a.id)}
                    className={cn(
                      "w-full text-left p-3 rounded-xl border-2 transition-all",
                      alunoSelecionado === a.id
                        ? "border-primary-700 bg-primary-50"
                        : "border-gray-200"
                    )}
                  >
                    <p className="font-medium text-gray-900 text-sm">{a.nome}</p>
                    {a.turma && (
                      <p className="text-xs text-gray-400 mt-0.5">{a.turma}</p>
                    )}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Quantidade */}
          <div>
            <h3 className="font-semibold text-gray-900 mb-3">Quantidade</h3>
            <div className="flex items-center gap-4">
              <button
                onClick={() => setQuantidade((q) => Math.max(1, q - 1))}
                disabled={quantidade <= 1}
                className="w-10 h-10 rounded-xl border border-gray-200 flex items-center justify-center disabled:opacity-30 active:bg-gray-100"
              >
                <Minus size={16} />
              </button>
              <span className="text-xl font-bold w-8 text-center">{quantidade}</span>
              <button
                onClick={() =>
                  setQuantidade((q) =>
                    Math.min(tamanhoSelecionado?.estoque ?? 99, q + 1)
                  )
                }
                disabled={
                  !!tamanhoSelecionado && quantidade >= tamanhoSelecionado.estoque
                }
                className="w-10 h-10 rounded-xl border border-gray-200 flex items-center justify-center disabled:opacity-30 active:bg-gray-100"
              >
                <Plus size={16} />
              </button>
            </div>
          </div>
        </div>

        {/* Botão adicionar ao carrinho */}
        <div className="sticky bottom-0 bg-white border-t border-gray-100 p-4 safe-bottom">
          <button
            onClick={handleAdicionar}
            disabled={!podeAdicionar || adicionado}
            className={cn(
              "btn-primary flex items-center justify-center gap-2 transition-all",
              adicionado && "bg-green-600 hover:bg-green-600"
            )}
          >
            {adicionado ? (
              <>
                <Check size={18} /> Adicionado!
              </>
            ) : (
              <>
                <ShoppingCart size={18} />
                {podeAdicionar
                  ? `Adicionar ao carrinho · ${formatarMoeda(
                      Number(tamanhoSelecionado?.preco) * quantidade
                    )}`
                  : "Selecione tamanho" + (alunos.length > 1 ? " e aluno" : "")}
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
