"use client";

import { useEffect } from "react";
import { CheckCircle2, Download, ExternalLink, Plus, Printer, X } from "lucide-react";
import { CustomSelect } from "@/components/ui/custom-select";
import { downloadPdvReceiptHtml, printPdvReceipt, type PdvReceiptPayload } from "@/lib/orders/pdv-receipt-print";
import { formatMoneyInput } from "@/utils/formatters";
import type { SellerAllocationDraft } from "@/lib/pdv/carrinho";
import { CupomFiscalDaVenda, type EstadoDoCupom } from "@/components/fiscal/nota-do-cupom";

/*
  As caixas do PDV.

  Nenhuma delas usa o diálogo do navegador nem o do sistema: o balcão tem o
  próprio ritmo, e a caixa precisa abrir e fechar no Esc sem tirar o foco de
  onde o caixa estava.
*/

export function Modal({
  aberto,
  aoFechar,
  titulo,
  sub,
  larga,
  children,
  acoes,
}: {
  aberto: boolean;
  aoFechar: () => void;
  titulo: string;
  sub?: string;
  larga?: boolean;
  children: React.ReactNode;
  acoes?: React.ReactNode;
}) {
  useEffect(() => {
    if (!aberto) return;
    const aoTeclar = (evento: KeyboardEvent) => {
      if (evento.key === "Escape") {
        /* Só a caixa fecha: o Esc não pode chegar ao atalho da página, que
           também o usa para voltar do passo de receber. */
        evento.stopImmediatePropagation();
        aoFechar();
      }
    };
    window.addEventListener("keydown", aoTeclar, true);
    return () => window.removeEventListener("keydown", aoTeclar, true);
  }, [aberto, aoFechar]);

  if (!aberto) return null;

  return (
    <div className="pdv-modal-fundo" role="dialog" aria-modal="true" onClick={aoFechar}>
      <div className={`pdv-modal ${larga ? "pdv-modal-larga" : ""}`} onClick={(evento) => evento.stopPropagation()}>
        <div className="pdv-modal-topo">
          <div className="min-w-0">
            <h2>{titulo}</h2>
            {sub ? <p className="pdv-modal-sub">{sub}</p> : null}
          </div>
          <button type="button" className="ks-icon-button ks-icon-button-sm" onClick={aoFechar} aria-label="Fechar">
            <X size={15} />
          </button>
        </div>
        {children}
        {acoes ? <div className="pdv-modal-acoes">{acoes}</div> : null}
      </div>
    </div>
  );
}

/* Quem vendeu: uma pessoa, ou o rateio entre duas ou mais. */
export function ModalDoVendedor({
  aberto,
  aoFechar,
  sellerMode,
  setSellerMode,
  sellerOptions,
  primarySellerUserId,
  setPrimarySellerUserId,
  sellerAllocations,
  updateSellerAllocation,
  removeSellerAllocation,
  addSellerAllocation,
  totalDoRateio,
}: {
  aberto: boolean;
  aoFechar: () => void;
  sellerMode: "single" | "split";
  setSellerMode: (modo: "single" | "split") => void;
  sellerOptions: Array<{ value: string; label: string }>;
  primarySellerUserId: string;
  setPrimarySellerUserId: (valor: string) => void;
  sellerAllocations: SellerAllocationDraft[];
  updateSellerAllocation: (id: string, patch: Partial<SellerAllocationDraft>) => void;
  removeSellerAllocation: (id: string) => void;
  addSellerAllocation: () => void;
  totalDoRateio: number;
}) {
  return (
    <Modal
      aberto={aberto}
      aoFechar={aoFechar}
      titulo="Quem vendeu"
      sub="A comissão desta venda segue o que ficar marcado aqui."
      acoes={
        <button type="button" className="pdv-botao pdv-botao-cheio" onClick={aoFechar}>
          Pronto
        </button>
      }
    >
      <div className="pdv-abas mb-4">
        <button
          type="button"
          className={`pdv-aba ${sellerMode === "single" ? "pdv-aba-ativa" : ""}`}
          onClick={() => setSellerMode("single")}
        >
          Um vendedor
        </button>
        <button
          type="button"
          className={`pdv-aba ${sellerMode === "split" ? "pdv-aba-ativa" : ""}`}
          onClick={() => setSellerMode("split")}
        >
          Rateio
        </button>
      </div>

      {sellerMode === "single" ? (
        <div>
          <label className="pdv-rotulo">Vendedor principal</label>
          <CustomSelect
            options={sellerOptions}
            value={primarySellerUserId}
            onChange={setPrimarySellerUserId}
            searchable
            className="pdv-select-campo"
            placeholder="Selecione o vendedor"
          />
        </div>
      ) : (
        <div className="space-y-3">
          {sellerAllocations.map((allocation, index) => (
            <div key={allocation.id} className="pdv-rateio">
              <div className="min-w-0">
                {index === 0 ? <label className="pdv-rotulo">Vendedor</label> : null}
                <CustomSelect
                  options={sellerOptions}
                  value={allocation.seller_user_id}
                  onChange={(value) => updateSellerAllocation(allocation.id, { seller_user_id: value })}
                  searchable
                  className="pdv-select-campo"
                  placeholder={index === 0 ? "Principal" : "Vendedor"}
                />
              </div>
              <div>
                {index === 0 ? <label className="pdv-rotulo">% do rateio</label> : null}
                <input
                  value={allocation.allocation_percent}
                  onChange={(evento) =>
                    updateSellerAllocation(allocation.id, { allocation_percent: formatMoneyInput(evento.target.value) })
                  }
                  className="pdv-campo pdv-campo-num"
                  placeholder="0,00"
                />
              </div>
              <button
                type="button"
                className="pdv-botao pdv-botao-perigo"
                onClick={() => removeSellerAllocation(allocation.id)}
                disabled={sellerAllocations.length <= 2}
              >
                Tirar
              </button>
            </div>
          ))}
          <div className="flex items-center justify-between border-t border-[var(--ks-color-border-subtle)] pt-3">
            <span className={`text-[12px] font-bold ${Math.abs(totalDoRateio - 100) > 0.01 ? "text-[var(--ks-color-status-danger)]" : "text-[var(--ks-color-status-success)]"}`}>
              Soma: {formatMoneyInput(totalDoRateio.toFixed(2))}% {Math.abs(totalDoRateio - 100) > 0.01 ? "— precisa dar 100%" : ""}
            </span>
            <button type="button" className="pdv-botao" onClick={addSellerAllocation}>
              <Plus size={14} />
              Mais um vendedor
            </button>
          </div>
        </div>
      )}
    </Modal>
  );
}

/* A venda saiu: cupom, pedido e o caminho de volta ao balcão. */
export function ModalDoCupom({
  aberto,
  aoFechar,
  cupom,
  pedidoId,
  resumo,
  cupomFiscal = null,
  aoImprimirCupomFiscal,
  aoTentarCupomDeNovo,
  aoConsultarCupomDeNovo,
  entregaDigital = null,
}: {
  aberto: boolean;
  aoFechar: () => void;
  cupom: PdvReceiptPayload | null;
  /** Produto digital: o link da entrega e o QR code dele (o cliente aponta o celular). */
  entregaDigital?: { link: string; qr: string } | null;
  pedidoId: string;
  resumo: string;
  /** A venda pediu NFC-e: a janela mostra como ela está (quem emite e acompanha é a página do PDV). */
  cupomFiscal?: EstadoDoCupom | null;
  aoImprimirCupomFiscal?: () => void;
  aoTentarCupomDeNovo?: () => void;
  aoConsultarCupomDeNovo?: () => void;
}) {
  return (
    <Modal
      aberto={aberto}
      aoFechar={aoFechar}
      titulo="Venda concluída"
      acoes={
        <button type="button" className="pdv-botao" onClick={aoFechar}>
          Voltar ao balcão
        </button>
      }
    >
      <div className="pdv-feito">
        <div className="pdv-feito-check">
          <CheckCircle2 size={28} />
        </div>
        <strong>{cupom?.order.number ? `Pedido #${cupom.order.number}` : "Pedido registrado"}</strong>
        <span>{resumo}</span>
      </div>
      {entregaDigital ? (
        <div className="flex flex-col items-center gap-2 rounded-xl border border-[var(--ks-color-border-subtle)] p-3 text-center">
          <strong className="text-sm">Produto digital: o cliente recebe agora</strong>
          {entregaDigital.qr ? (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img src={entregaDigital.qr} alt="QR code da entrega" className="h-44 w-44" />
          ) : null}
          <span className="text-xs text-[var(--ks-color-text-muted)]">
            Ele aponta a câmera do celular para o código (também aparece na tela do cliente). O acesso vai junto para o e-mail dele.
          </span>
          <button
            type="button"
            className="pdv-botao"
            onClick={() => {
              void navigator.clipboard?.writeText(entregaDigital.link).catch(() => undefined);
            }}
          >
            Copiar o link
          </button>
        </div>
      ) : null}
      {cupomFiscal ? (
        <CupomFiscalDaVenda
          estado={cupomFiscal}
          aoImprimir={() => aoImprimirCupomFiscal?.()}
          aoTentarDeNovo={() => aoTentarCupomDeNovo?.()}
          aoConsultarDeNovo={() => aoConsultarCupomDeNovo?.()}
        />
      ) : null}
      <div className="grid gap-2">
        <button
          type="button"
          className={`pdv-botao pdv-botao-largo ${cupomFiscal ? "" : "pdv-botao-cheio"}`}
          onClick={() => {
            if (cupom) printPdvReceipt(cupom);
          }}
        >
          <Printer size={15} />
          {cupomFiscal ? "Imprimir cupom sem valor fiscal" : "Imprimir cupom"}
        </button>
        {cupomFiscal ? null : (
          <button
            type="button"
            className="pdv-botao pdv-botao-largo"
            onClick={() => {
              if (cupom) downloadPdvReceiptHtml(cupom);
            }}
          >
            <Download size={15} />
            Baixar cupom
          </button>
        )}
        {pedidoId ? (
          <button
            type="button"
            className="pdv-botao pdv-botao-largo"
            onClick={() => window.open(`/dashboard/orders/${pedidoId}`, "_blank", "noopener,noreferrer")}
          >
            <ExternalLink size={15} />
            Abrir o pedido
          </button>
        ) : null}
      </div>
    </Modal>
  );
}

