import Button from "@/components/Forms/Button";
import { exportarDistribuidoresExcel } from "@/requests/CFG001/ExportarImportarBases/exportarDistribuidoresExcel";
import { exportarFabricantesExcel } from "@/requests/CFG001/ExportarImportarBases/exportarFabricantesExcel";
import { exportarTodosItensKit } from "@/requests/CFG001/ExportarImportarBases/exportarTodosItensKit";
import { importarDistribuidoresExcel } from "@/requests/CFG001/ExportarImportarBases/importarDistribuidoresExcel";
import { importarFabricantesExcel } from "@/requests/CFG001/ExportarImportarBases/importarFabricantesExcel";
import { importarTodosItensKit } from "@/requests/CFG001/ExportarImportarBases/importarTodosItensKit";
import { useRef, useState } from "react";
import { BsDownload, BsUpload } from "react-icons/bs";
import { toast } from "react-toastify";

const ExportarImportarBasesComponent = () => {
  const [isExportingDistribuidoresExcel, setIsExportingDistribuidoresExcel] =
    useState(false);
  const [isImportingDistribuidores, setIsImportingDistribuidores] =
    useState(false);
  const [isExportingFabricantesExcel, setIsExportingFabricantesExcel] =
    useState(false);
  const [isImportingFabricantes, setIsImportingFabricantes] = useState(false);
  const [isExportingItens, setIsExportingItens] = useState(false);
  const [isImportingItens, setIsImportingItens] = useState(false);

  const fileInputDistribuidoresRef = useRef<HTMLInputElement>(null);
  const fileInputFabricantesRef = useRef<HTMLInputElement>(null);
  const fileInputItensRef = useRef<HTMLInputElement>(null);

  // ====== DISTRIBUIDORES ======
  const handleExportarDistribuidoresExcel = async () => {
    setIsExportingDistribuidoresExcel(true);
    try {
      const response = await exportarDistribuidoresExcel();

      if (response?.status === 1 && response?.conteudo_base64) {
        // Fazer o download do arquivo
        const binaryString = atob(response.conteudo_base64);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([bytes], { type: response.mime_type });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = response.arquivo_backup;
        link.click();
        URL.revokeObjectURL(url);

        toast.success(
          `${response.total_registros} distribuidores exportados em Excel com sucesso`
        );
      } else {
        throw new Error(response?.msg || "Erro na exportação");
      }
    } catch (error: any) {
      toast.error(error.message || "Erro ao exportar distribuidores em Excel");
    } finally {
      setIsExportingDistribuidoresExcel(false);
    }
  };

  const handleImportarDistribuidores = () => {
    fileInputDistribuidoresRef.current?.click();
  };

  const handleFileImportDistribuidores = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const ext = file.name.split(".").pop()?.toLowerCase();
    if (ext !== "xlsx" && ext !== "xls") {
      toast.error(
        "Por favor, selecione um arquivo Excel válido (.xlsx ou .xls)"
      );
      if (fileInputDistribuidoresRef.current) {
        fileInputDistribuidoresRef.current.value = "";
      }
      return;
    }

    setIsImportingDistribuidores(true);
    try {
      const formData = new FormData();
      formData.append("arquivo", file);

      const response = await importarDistribuidoresExcel(formData);

      if (response?.status === 1) {
        toast.success(
          `${response.total_inseridos} distribuidores importados com sucesso`
        );
        if (response.erros && response.erros.length > 0) {
          toast.warning(
            `⚠️ ${response.erros.length} linha(s) com erro. Verifique o log.`
          );
          console.error("Erros na importação:", response.erros);
        }
      } else {
        throw new Error(response?.msg || "Erro na importação");
      }
    } catch (error: any) {
      toast.error(
        error.message ||
          "Erro ao importar distribuidores. Verifique o formato do arquivo."
      );
    } finally {
      setIsImportingDistribuidores(false);
      if (fileInputDistribuidoresRef.current) {
        fileInputDistribuidoresRef.current.value = "";
      }
    }
  };

  // ====== FABRICANTES ======
  const handleExportarFabricantesExcel = async () => {
    setIsExportingFabricantesExcel(true);
    try {
      const response = await exportarFabricantesExcel();

      if (response?.status === 1 && response?.conteudo_base64) {
        // Fazer o download do arquivo
        const binaryString = atob(response.conteudo_base64);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([bytes], { type: response.mime_type });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = response.arquivo_backup;
        link.click();
        URL.revokeObjectURL(url);

        toast.success(
          `${response.total_registros} fabricantes exportados em Excel com sucesso`
        );
      } else {
        throw new Error(response?.msg || "Erro na exportação");
      }
    } catch (error: any) {
      toast.error(error.message || "Erro ao exportar fabricantes em Excel");
    } finally {
      setIsExportingFabricantesExcel(false);
    }
  };

  const handleImportarFabricantes = () => {
    fileInputFabricantesRef.current?.click();
  };

  const handleFileImportFabricantes = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const ext = file.name.split(".").pop()?.toLowerCase();
    if (ext !== "xlsx" && ext !== "xls") {
      toast.error(
        "Por favor, selecione um arquivo Excel válido (.xlsx ou .xls)"
      );
      if (fileInputFabricantesRef.current) {
        fileInputFabricantesRef.current.value = "";
      }
      return;
    }

    setIsImportingFabricantes(true);
    try {
      const formData = new FormData();
      formData.append("arquivo", file);

      const response = await importarFabricantesExcel(formData);

      if (response?.status === 1) {
        toast.success(
          `${response.total_inseridos} fabricantes importados com sucesso`
        );
        if (response.erros && response.erros.length > 0) {
          toast.warning(
            `⚠️ ${response.erros.length} linha(s) com erro. Verifique o log.`
          );
          console.error("Erros na importação:", response.erros);
        }
      } else {
        throw new Error(response?.msg || "Erro na importação");
      }
    } catch (error: any) {
      toast.error(
        error.message ||
          "Erro ao importar fabricantes. Verifique o formato do arquivo."
      );
    } finally {
      setIsImportingFabricantes(false);
      if (fileInputFabricantesRef.current) {
        fileInputFabricantesRef.current.value = "";
      }
    }
  };

  // ====== ITENS DO KIT ======
  const handleExportarItensKit = async () => {
    setIsExportingItens(true);
    try {
      const response = await exportarTodosItensKit();

      if (response?.status === 1 && response?.conteudo_base64) {
        // Fazer o download do arquivo
        const binaryString = atob(response.conteudo_base64);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([bytes], { type: response.mime_type });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = response.arquivo_backup;
        link.click();
        URL.revokeObjectURL(url);

        toast.success(
          `${response.total_registros} itens do kit exportados com sucesso`
        );
      } else {
        throw new Error(response?.msg || "Erro na exportação");
      }
    } catch (error: any) {
      toast.error(error.message || "Erro ao exportar itens do kit");
    } finally {
      setIsExportingItens(false);
    }
  };

  const handleImportarItensKit = () => {
    fileInputItensRef.current?.click();
  };

  const handleFileImportItensKit = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const ext = file.name.split(".").pop()?.toLowerCase();
    if (ext !== "xlsx" && ext !== "xls") {
      toast.error(
        "Por favor, selecione um arquivo Excel válido (.xlsx ou .xls)"
      );
      if (fileInputItensRef.current) {
        fileInputItensRef.current.value = "";
      }
      return;
    }

    setIsImportingItens(true);
    try {
      const formData = new FormData();
      formData.append("arquivo", file);

      const response = await importarTodosItensKit(formData);

      if (response?.status === 1) {
        toast.success(
          `Itens do Kit importados com sucesso! Inseridos: ${response.total_inseridos}, Atualizados: ${response.total_atualizados}`
        );

        if (response.erros && response.erros.length > 0) {
          toast.warning(
            `⚠️ ${response.erros.length} linha(s) com erro. Verifique o log.`
          );
          console.error("Erros na importação:", response.erros);
        }
      } else {
        throw new Error(response?.msg || "Erro na importação");
      }
    } catch (error: any) {
      toast.error(
        error.message ||
          "Erro ao importar itens do kit. Verifique o formato do arquivo."
      );
    } finally {
      setIsImportingItens(false);
      if (fileInputItensRef.current) {
        fileInputItensRef.current.value = "";
      }
    }
  };

  return (
    <div className="bg-white rounded-md p-6 space-y-6">
      <div>
        <h2 className="text-2xl font-bold mb-4">Exportar/Importar Bases</h2>
        <p className="text-sm text-gray-600 mb-6">
          Gerencie a exportação e importação de dados de Distribuidores,
          Fabricantes e Itens do Kit.
        </p>
      </div>

      {/* DISTRIBUIDORES */}
      <div className="border rounded-lg p-4 bg-green-50 border-green-200">
        <h3 className="text-lg font-semibold text-green-900 mb-4">
          Distribuidores/Fornecedores
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-sm text-green-700 mb-2">Exportar</p>
            <Button
              type="button"
              className="bg-green-600 hover:bg-green-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleExportarDistribuidoresExcel}
              loading={isExportingDistribuidoresExcel}
              disabled={isExportingDistribuidoresExcel}
            >
              <BsDownload size={16} />
              Exportar Excel
            </Button>
          </div>
          <div>
            <p className="text-sm text-green-700 mb-2">Importar</p>
            <input
              ref={fileInputDistribuidoresRef}
              type="file"
              accept=".xlsx,.xls"
              hidden
              onChange={handleFileImportDistribuidores}
            />
            <Button
              type="button"
              className="bg-green-600 hover:bg-green-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleImportarDistribuidores}
              loading={isImportingDistribuidores}
              disabled={isImportingDistribuidores}
            >
              <BsUpload size={16} />
              Importar
            </Button>
          </div>
        </div>
      </div>

      {/* FABRICANTES */}
      <div className="border rounded-lg p-4 bg-purple-50 border-purple-200">
        <h3 className="text-lg font-semibold text-purple-900 mb-4">
          Fabricantes
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-sm text-purple-700 mb-2">Exportar</p>
            <Button
              type="button"
              className="bg-purple-600 hover:bg-purple-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleExportarFabricantesExcel}
              loading={isExportingFabricantesExcel}
              disabled={isExportingFabricantesExcel}
            >
              <BsDownload size={16} />
              Exportar Excel
            </Button>
          </div>
          <div>
            <p className="text-sm text-purple-700 mb-2">Importar</p>
            <input
              ref={fileInputFabricantesRef}
              type="file"
              accept=".xlsx,.xls"
              hidden
              onChange={handleFileImportFabricantes}
            />
            <Button
              type="button"
              className="bg-purple-600 hover:bg-purple-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleImportarFabricantes}
              loading={isImportingFabricantes}
              disabled={isImportingFabricantes}
            >
              <BsUpload size={16} />
              Importar
            </Button>
          </div>
        </div>
      </div>

      {/* ITENS DO KIT */}
      <div className="border rounded-lg p-4 bg-blue-50 border-blue-200">
        <h3 className="text-lg font-semibold text-blue-900 mb-4">
          Itens do Kit
        </h3>
        <p className="text-sm text-blue-700 mb-4">
          Exportar/Importar todos os itens em planilha Excel
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-sm text-blue-700 mb-2">Exportar Dados</p>
            <Button
              type="button"
              className="bg-blue-600 hover:bg-blue-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleExportarItensKit}
              loading={isExportingItens}
              disabled={isExportingItens}
            >
              <BsDownload size={16} />
              Exportar Excel
            </Button>
          </div>
          <div>
            <p className="text-sm text-blue-700 mb-2">Importar Dados</p>
            <input
              ref={fileInputItensRef}
              type="file"
              accept=".xlsx,.xls"
              hidden
              onChange={handleFileImportItensKit}
            />
            <Button
              type="button"
              className="bg-blue-600 hover:bg-blue-700 text-white w-full flex items-center justify-center gap-2"
              onClick={handleImportarItensKit}
              loading={isImportingItens}
              disabled={isImportingItens}
            >
              <BsUpload size={16} />
              Importar
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExportarImportarBasesComponent;
