"use client";

import React, { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import MainEmpresa from "@/app/components/MainEmpresa";
import {
  documentoFiscalService,
  type DocumentoFiscal,
} from "@/services/DocumentoFiscal";
import { useThemeColors } from "@/context/ThemeContext";
import OutrosDocumentosTable from "@/app/components/Faturas/OutrosDocumentosTable";
import { FileText, ChevronDown } from "lucide-react";

/* ─── Helpers de autenticação (Sanctum) ──────────────────────────────────── */
function getXsrfToken(): string {
  return decodeURIComponent(Cookies.get("XSRF-TOKEN") ?? "");
}

async function garantirCsrf(baseUrl: string) {
  if (!Cookies.get("XSRF-TOKEN")) {
    await fetch(`${baseUrl}/sanctum/csrf-cookie`, { credentials: "include" });
  }
}

async function abrirUrlAutenticada(url: string, tipo: "pdf" | "html" = "pdf") {
  const baseUrl = url.split("/api/")[0];

  // 1. Garantir CSRF
  await garantirCsrf(baseUrl);
  const xsrf = getXsrfToken();

  // 2. Obter o tenant ID (igual ao usado no axios.ts)
  const tenantId = localStorage.getItem("tenant_id");
  if (!tenantId) {
    throw new Error("Empresa não identificada. Faça login novamente.");
  }

  // 3. Requisição com os headers completos
  const res = await fetch(url, {
    method: "GET",
    credentials: "include",
    headers: {
      Accept: tipo === "pdf" ? "application/pdf,*/*" : "text/html,*/*",
      "X-XSRF-TOKEN": xsrf,
      "X-Requested-With": "XMLHttpRequest",
      "X-Empresa-ID": tenantId,
    },
  });

  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`Erro ${res.status}: ${body || res.statusText}`);
  }

  const blob = await res.blob();
  const blobUrl = URL.createObjectURL(blob);
  const win = window.open(blobUrl, "_blank");

  if (win) {
    win.addEventListener("load", () => URL.revokeObjectURL(blobUrl), { once: true });
  } else {
    setTimeout(() => URL.revokeObjectURL(blobUrl), 60000);
  }
}
/* ─────────────────────────────────────────────────────────────────────────── */

export default function OutrosDocumentosPage() {
  const router = useRouter();
  const colors = useThemeColors();

  const [documentos, setDocumentos] = useState<DocumentoFiscal[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [baixandoPdf, setBaixandoPdf] = useState<string | null>(null);
  const [imprimindo] = useState<string | null>(null);
  const [dropdownAberto, setDropdownAberto] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const baseUrl =
    typeof window !== "undefined"
      ? `${window.location.protocol}//${window.location.hostname}:8000`
      : "http://localhost:8000";

  /* ── Fechar dropdown ao clicar fora ── */
  useEffect(() => {
    function handleClickFora(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setDropdownAberto(false);
      }
    }

    if (dropdownAberto) {
      document.addEventListener("mousedown", handleClickFora);
      return () => document.removeEventListener("mousedown", handleClickFora);
    }
  }, [dropdownAberto]);

  /* ── Carregar documentos ── */
  const carregarDocumentos = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const resultado = await documentoFiscalService.listar({
        per_page: 100,
        apenas_nao_vendas: true,
      });
      if (!resultado?.data) throw new Error("Erro ao carregar");
      // Filtra apenas os tipos desta página
      const filtrados = resultado.data.filter((d) =>
        ["FP", "FA", "NC", "ND", "FRt"].includes(d.tipo_documento)
      );
      setDocumentos(filtrados);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Erro ao carregar");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    carregarDocumentos();
  }, [carregarDocumentos]);

  /* ── 🆕 Imprimir A4 (nova rota print-a4) ── */
  const imprimirA4 = useCallback(
    async (documento: DocumentoFiscal) => {
      if (!documento.id) return;
      try {
        await abrirUrlAutenticada(
          `${baseUrl}/api/documentos-fiscais/${documento.id}/print-a4`,
          "html"
        );
      } catch (err: unknown) {
        alert(err instanceof Error ? err.message : "Erro ao abrir impressão A4");
      }
    },
    [baseUrl]
  );

  /* ── PDF Viewer autenticado (talão térmico para PDF) ── */
  const imprimirPdfNavegador = useCallback(
    async (documento: DocumentoFiscal) => {
      if (!documento.id) return;
      try {
        await abrirUrlAutenticada(
          `${baseUrl}/api/documentos-fiscais/${documento.id}/pdf-viewer`,
          "html"
        );
      } catch (err: unknown) {
        alert(err instanceof Error ? err.message : "Erro ao abrir PDF");
      }
    },
    [baseUrl]
  );

  /* ── Download PDF ── */
  const baixarPdf = useCallback(async (documento: DocumentoFiscal) => {
    if (!documento.id) return;
    try {
      setBaixandoPdf(documento.id);
      const nome = `${documento.tipo_documento}_${
        documento.numero_documento ?? documento.id
      }.pdf`;
      await documentoFiscalService.downloadPdf(documento.id, nome);
    } catch {
      alert("Erro ao baixar PDF");
    } finally {
      setBaixandoPdf(null);
    }
  }, []);

  /* ── Ver detalhes ── */
  const verDetalhes = (doc: DocumentoFiscal) => {
    if (doc.id) router.push(`/dashboard/Faturas/Faturas/${doc.id}/Ver`);
  };

  /* ── Formatar moeda ── */
  const formatKz = (valor: number | string | undefined) => {
    if (!valor) return "0,00 Kz";
    return Number(valor).toLocaleString("pt-AO", {
      style: "currency",
      currency: "AOA",
    });
  };

  return (
    <MainEmpresa>
      {/* ── Barra de topo ── */}
      <div
        className="flex flex-wrap items-center justify-between px-3 py-3"
        style={{ borderBottom: `0.5px solid ${colors.border}` }}
      >
        <span className="text-sm font-semibold" style={{ color: colors.secondary }}>
          Outros Documentos Fiscais
        </span>

        {/* ── Dropdown "Comece a Faturar" alinhado à direita ── */}
        <div ref={dropdownRef} className="relative">
          <button
            onClick={() => setDropdownAberto(!dropdownAberto)}
            className="flex items-center gap-2 px-4 py-2 text-sm text-white transition-opacity hover:opacity-80 rounded"
            style={{ backgroundColor: colors.primary }}
          >
            <span className="font-medium">Comece a Facturar</span>
            <ChevronDown
              size={18}
              className={`transition-transform duration-200 ${
                dropdownAberto ? "rotate-180" : ""
              }`}
            />
          </button>

          {/* ── Menu dropdown ── */}
          {dropdownAberto && (
            <div
              className="absolute right-0 mt-2 w-56 rounded shadow-lg z-50"
              style={{ backgroundColor: colors.background, border: `1px solid ${colors.border}` }}
            >
              {/* Nova Venda */}
              <button
                onClick={() => {
                  router.push("/dashboard/Vendas/Nova_venda");
                  setDropdownAberto(false);
                }}
                className="flex items-center gap-3 w-full px-4 py-3 text-sm transition-colors hover:bg-gray-100 dark:hover:bg-gray-800 first:rounded-t last:rounded-b"
                style={{
                  color: colors.text,
                  borderBottom: `0.5px solid ${colors.border}`,
                }}
              >
                <FileText size={16} style={{ color: colors.secondary }} />
                <div className="text-left">
                  <div className="font-medium">Gerar factura-recibo</div>
                  <div style={{ color: colors.text, opacity: 0.7 }} className="text-xs">
                    Registar uma nova venda
                  </div>
                </div>
              </button>

              {/* Nova Fatura */}
              <button
                onClick={() => {
                  router.push("/dashboard/Faturas/Fatura_Normal");
                  setDropdownAberto(false);
                }}
                className="flex items-center gap-3 w-full px-4 py-3 text-sm transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
                style={{
                  color: colors.text,
                  borderBottom: `0.5px solid ${colors.border}`,
                }}
              >
                <FileText size={16} style={{ color: colors.primary }} />
                <div className="text-left">
                  <div className="font-medium">Gerar factura</div>
                  <div style={{ color: colors.text, opacity: 0.7 }} className="text-xs">
                    Emitir uma factura normal
                  </div>
                </div>
              </button>

              {/* Nova Proforma */}
              <button
                onClick={() => {
                  router.push("/dashboard/Faturas/Faturas_Proforma");
                  setDropdownAberto(false);
                }}
                className="flex items-center gap-3 w-full px-4 py-3 text-sm transition-colors hover:bg-gray-100 dark:hover:bg-gray-800 last:rounded-b"
                style={{
                  color: colors.text,
                }}
              >
                <FileText size={16} style={{ color: colors.secondary }} />
                <div className="text-left">
                  <div className="font-medium">Gerar proforma</div>
                  <div style={{ color: colors.text, opacity: 0.7 }} className="text-xs">
                    Criar uma factura proforma
                  </div>
                </div>
              </button>
            </div>
          )}
        </div>
      </div>

      {/* ── Mensagem de erro ── */}
      {error && (
        <div className="px-3 py-2 text-sm" style={{ color: colors.danger }}>
          {error}
        </div>
      )}

      {/* ── Tabela ── */}
      <OutrosDocumentosTable
        documentos={documentos}
        loading={loading}
        baixandoPdf={baixandoPdf}
        imprimindo={imprimindo}
        onVerDetalhes={verDetalhes}
        onImprimirA4={imprimirA4}
        onImprimirPdf={imprimirPdfNavegador}
        onBaixarPdf={baixarPdf}
        formatKz={formatKz}
        documentoFiscalService={documentoFiscalService}
        colors={colors}
      />
    </MainEmpresa>
  );
}