import React, { useEffect } from "react";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { FileText } from "lucide-react";
interface ItemCompra {
  tipo_item_pendencia_compra_material: string;
  valor_pendencia_compra_material: string;
  valor_total_item: number;
  qtd_pendencia_compra_material: string;
  descricao_pendencia_compra_material: string;
  origem_item_pendencia_compra_material: string;
  previsto_pendencia_compra_material: string | number;
  realizado_pendencia_compra_material: string | number;
  numero_pedido_pendencia_compra_material: string;
  data_pendencia_compra_material: string;
  fornecedor_pendencia_compra_material: string;
  data_previsao_entrega_compra_material: string;
}

interface ComponenteKit {
  id_item: string;
  nome: string;
  categoria: string;
  descricao: string;
  qtd: string;
  precoUnitario_item: string;
}

interface DadosKit {
  componentesKit: ComponenteKit[];
}

interface CustoExtra {
  id_custo_extra: string;
  nome_custo_extra: string;
  value: string;
  tabelaPrecos?: {
    de_custo_extra_tabela: number;
    ate_custo_extra_tabela: number;
    qtd_custo_extra_tabela: number;
  }[];
}

interface Precificacao {
  custos_extras: CustoExtra[];
  [key: string]: any;
}

interface ListaComponentesKitProps {
  id_kit?: string;
  custosExtras: CustoExtra[];
  dadosKit: DadosKit | any;
  perfil?: any;
  precificacao: any; // JSON string
  itensCompra: ItemCompra[];
  distribuidores: any[];
  setItensCompra: (itens: ItemCompra[]) => void;
}
const ListaComponentesComprados: React.FC<ListaComponentesKitProps> = ({
  custosExtras,
  itensCompra,
  setItensCompra,
  distribuidores = [],
  dadosKit,
  precificacao,
  perfil,
}) => {
  // Utils
  const formatBRL = (n: number) =>
    n?.toLocaleString("pt-BR", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });

  const parseBRToNumber = (value?: string): number => {
    if (!value) return 0;

    // remove separador de milhar e converte vírgula em ponto
    const normalized = value.replace(/\./g, "").replace(",", ".");
    const n = parseFloat(normalized);
    return Number.isFinite(n) ? n : 0;
  };

  const dataFormat = (data?: string) => {
    if (!data) return "";
    if (data.includes("-")) {
      const partes = data.split("-");
      if (partes.length === 3) return `${partes[2]}/${partes[1]}/${partes[0]}`;
    }
    return data;
  };

  // Parse seguro da precificação
  const precificacaoFormat: Precificacao = React.useMemo(() => {
    try {
      return JSON.parse(precificacao);
    } catch (e) {
      console.error("Erro ao parsear precificação:", e);
      return { custos_extras: [] };
    }
  }, [precificacao]);

  const custosExtrasIds = custosExtras.map((c) => c.id_custo_extra);
  const custosExtrasFiltrados = precificacaoFormat.custos_extras.filter(
    (custo) => custosExtrasIds.includes(custo.id_custo_extra)
  );

  const calcularValorPrevistoOuReal = (item: ItemCompra): number => {
    const tipo = item?.tipo_item_pendencia_compra_material;
    const qtd = Number(item?.qtd_pendencia_compra_material || 0);
    const origem = item?.origem_item_pendencia_compra_material;

    if (!tipo || tipo === "0") return 0;

    if (origem === "kit") {
      // Soma dos itens do kit pela categoria = tipo
      const total = (dadosKit?.componentesKit || [])
        .filter((kit: ComponenteKit) => kit.categoria === tipo)
        .reduce((acc: number, kit: ComponenteKit) => {
          const preco = parseFloat(kit.precoUnitario_item || "0");
          return acc + qtd * preco;
        }, 0);
      return total;
    }

    // Custo extra
    const custoExtra = custosExtrasFiltrados.find(
      (ce) => ce.id_custo_extra === tipo
    );
    if (custoExtra) {
      return parseBRToNumber(custoExtra.value);
    }

    return 0;
  };

  // Atualiza previstos/realizados no estado quando houver mudanças
  useEffect(() => {
    if (!dadosKit || !precificacao || itensCompra.length === 0) return;

    const itensAtualizados = itensCompra.map((item) => {
      const previsto = calcularValorPrevistoOuReal(item);
      const realizado = parseBRToNumber(
        String(item.valor_pendencia_compra_material || "0")
      );
      return {
        ...item,
        previsto_pendencia_compra_material: previsto,
        realizado_pendencia_compra_material: realizado,
      };
    });

    const hasChanges = itensCompra.some((item, idx) => {
      return (
        item.previsto_pendencia_compra_material !==
          itensAtualizados[idx].previsto_pendencia_compra_material ||
        item.realizado_pendencia_compra_material !==
          itensAtualizados[idx].realizado_pendencia_compra_material
      );
    });

    if (hasChanges) {
      setItensCompra(itensAtualizados);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dadosKit, precificacao, custosExtras]);

  const getNomeItem = (item: ItemCompra): string => {
    const origem = item?.origem_item_pendencia_compra_material;
    const tipo = item?.tipo_item_pendencia_compra_material;
    if (!tipo) return "";
    if (origem === "kit") return tipo;

    const custoExtra = custosExtras.find((ce) => ce.id_custo_extra === tipo);
    return custoExtra?.nome_custo_extra ?? "";
  };

  const calcularTotalDoItem = (item: ItemCompra): number => {
    const valorUnit = parseFloat(item?.valor_pendencia_compra_material);
    const qtd = Number(item?.qtd_pendencia_compra_material || 0);
    return valorUnit * qtd;
  };

  const totalGeralItens = itensCompra.reduce(
    (acc, item) => acc + calcularTotalDoItem(item),
    0
  );

  const getNomeFornecedor = (item: ItemCompra): string => {
    const id = item.fornecedor_pendencia_compra_material;
    if (id === "0") return "Distribuidor não informado";
    if (id === "999") return "Estoque Próprio";
    const dist = distribuidores?.find(
      (d: any) => String(d.id_distribuidor) === String(id)
    );
    return dist?.nome_distribuidor || "—";
  };

  const handleGerarPDF = () => {
    const doc = new jsPDF({
      orientation: "landscape",
      unit: "pt",
      format: "a4",
    });

    doc.setFontSize(14);
    doc.text("Itens de Compra", 40, 40);

    const head = [
      [
        "Nro Pedido",
        "Nome",
        "Descrição",
        "Data Compra",
        "Previsão Entrega",
        "Distribuidor/Fornecedor",
        "Qtd",
        "Previsto",
        "Real",
        "Total",
      ],
    ];

    const body = itensCompra.map((item) => {
      const nome = getNomeItem(item);
      const prev = calcularValorPrevistoOuReal(item);
      const totalItem = calcularTotalDoItem(item);
      return [
        item.numero_pedido_pendencia_compra_material || "",
        nome,
        item.descricao_pendencia_compra_material || "",
        dataFormat(item.data_pendencia_compra_material),
        dataFormat(item.data_previsao_entrega_compra_material),
        getNomeFornecedor(item),
        item.qtd_pendencia_compra_material || "0",
        `R$ ${formatBRL(prev)}`,
        `R$ ${formatBRL(parseFloat(item.valor_pendencia_compra_material))}`,
        `R$ ${formatBRL(totalItem)}`,
      ];
    });

    autoTable(doc, {
      head,
      body,
      styles: { fontSize: 9, cellPadding: 6 },
      headStyles: { fillColor: [33, 150, 243] },
      theme: "grid",
      startY: 60,
    });

    const finalY = (doc as any).lastAutoTable?.finalY || 60;

    autoTable(doc, {
      body: [
        [
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "Total Geral",
          `R$ ${formatBRL(totalGeralItens)}`,
        ],
      ],
      styles: { fontSize: 10, cellPadding: 6 },
      theme: "plain",
      startY: finalY + 10,
      columnStyles: {
        8: { halign: "right", fontStyle: "bold" },
        9: { halign: "right", fontStyle: "bold" },
      },
    });

    doc.save("itens_compra.pdf");
  };

  if (!dadosKit || itensCompra.length === 0) {
    return (
      <div className="w-full border border-gray-300 rounded-md p-4 mb-4">
        <p>Nenhum item de compra disponível.</p>
      </div>
    );
  }

  return (
    <div className="w-full border border-gray-300 rounded-md p-4 mb-4 space-y-3">
      <div className="flex items-center justify-between">
        {/* <h3 className="text-base font-semibold">Itens de Compra</h3> */}
        <button
          onClick={handleGerarPDF}
          className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-meta-1 text-white hover:bg-blue-700 text-sm"
          title="Gerar PDF dos itens"
        >
          <FileText size={16} />
          Gerar PDF
        </button>
      </div>

      <div className="overflow-auto">
        <table className="w-full text-left text-black border-collapse text-sm min-w-[900px]">
          <thead>
            <tr className="border-b font-semibold">
              <th className="p-2">Nro Pedido</th>
              <th className="p-2">Nome</th>
              <th className="p-2">Descrição</th>
              <th className="p-2">Data Compra</th>
              <th className="p-2">Previsão Entrega</th>
              <th className="p-2">Distribuidor/Fornecedor</th>
              <th className="p-2">Qtd</th>
              <th className="p-2">Previsto</th>
              <th className="p-2">Real</th>
              <th className="p-2">Total</th>
            </tr>
          </thead>
          <tbody>
            {itensCompra.map((item, idx) => {
              const nome = getNomeItem(item);
              const valorPrevisto = calcularValorPrevistoOuReal(item);
              const valorTotal = calcularTotalDoItem(item);
              const nomeFornecedor = getNomeFornecedor(item);

              return (
                <tr key={idx} className="border-b">
                  <td className="p-2">
                    {item.numero_pedido_pendencia_compra_material}
                  </td>
                  <td className="p-2">{nome}</td>
                  <td className="p-2">
                    {item.descricao_pendencia_compra_material}
                  </td>
                  <td className="p-2">
                    {dataFormat(item.data_pendencia_compra_material)}
                  </td>
                  <td className="p-2">
                    {dataFormat(item.data_previsao_entrega_compra_material)}
                  </td>
                  <td className="p-2">{nomeFornecedor}</td>
                  <td className="p-2">{item.qtd_pendencia_compra_material}</td>
                  <td className="p-2">R$ {formatBRL(valorPrevisto)}</td>
                  <td className="p-2">
                    R${" "}
                    {formatBRL(
                      parseFloat(item.valor_pendencia_compra_material)
                    )}
                  </td>
                  <td className="p-2">
                    R${" "}
                    {formatBRL(
                      parseFloat(item.valor_pendencia_compra_material) *
                        Number(item.qtd_pendencia_compra_material)
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr className="border-t font-semibold">
              <td className="p-2" colSpan={9} style={{ textAlign: "right" }}>
                Total Geral
              </td>
              <td className="p-2">R$ {formatBRL(totalGeralItens)}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
};
export default ListaComponentesComprados;
