import { Button, Modal, message, Space } from "antd";
import React, { useState } from "react";
import InputItem from "../FormItems";
import { frontEndUrl } from "@/app/utils/variables";
import { errorMessage, successMessage } from "@/app/utils/alertMessages";
import GoogleIcon from "../GoogleIcon";
import * as XLSX from "xlsx";

const SAMPLE_DATA = {
  lead: [
    {
      "lead id": 202,
      "lead type": "Hot",
      "customer type": "Individual",
      "lead source": "Website",
      name: "John Doe",
      email: "john.doe@example.com",
      phone: "9876543210",
      whatsapp: "9876543210",
      website: "www.johndoeconsulting.com",
      "contact persons":
        "salutation: Ms., full_name: Sarah Connor, designation: Sales Manager, department: Sales, phone_1: 9123456789, phone_2: 9876501234, email: sarah.connor@example.com, notes: Interested in premium plan, follow-up next week",
      "converted to customer": 1,
    },
  ],
};

const normalizeKeys = (data) =>
  data.map((item) => {
    const newItem = {};
    Object.entries(item).forEach(([key, value]) => {
      let newKey = key.toLowerCase().trim().replace(/\s+/g, "_");
      if (newKey === "inventory_id" || newKey === "inventoryid") newKey = "inventory_id";
      if (newKey === "customer_name" || newKey === "customername") newKey = "customer_name";
      newItem[newKey] = value;
    });
    return newItem;
  });

const expandToJsonStringifiedObjects = (data) =>
  data.map((item) => {
    const newItem = { ...item };
    Object.entries(newItem).forEach(([key, val]) => {
      if (typeof val === "string" && val.includes(":") && !val.startsWith("[") && !val.startsWith("{")) {
        newItem[key] = JSON.stringify(
          val
            .split("|")
            .map((segment) =>
              segment
                .split(",")
                .map((pair) => pair.trim())
                .filter(Boolean)
                .reduce((acc, pair) => {
                  const [k, ...rest] = pair.split(":");
                  if (!k || rest.length === 0) return acc;
                  const valueStr = rest.join(":").trim();
                  const numValue = Number(valueStr);
                  acc[k.trim()] = !isNaN(numValue) ? numValue : valueStr;
                  return acc;
                }, {})
            )
            .filter((obj) => Object.keys(obj).length)
        );
      }
    });
    return newItem;
  });

const stringifyNestedObjects = (data) =>
  data.map((item) => {
    const newItem = { ...item };
    Object.keys(newItem).forEach((key) => {
      const val = newItem[key];
      if (typeof val === "object" && val !== null) newItem[key] = JSON.stringify(val);
    });
    return newItem;
  });

export default function ImportData({ typeFor }) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [testFiles, setTestFiles] = useState([]);
  const [sheetPreview, setSheetPreview] = useState([]);

  const showModal = () => setIsModalVisible(true);
  const hideModal = () => setIsModalVisible(false);

  const readExcel = async (file) => {
    const arrayBuffer = await file.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, { type: "array" });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    return XLSX.utils.sheet_to_json(sheet, { defval: "" });
  };

  const handleOk = async () => {
    if (!testFiles.length) {
      errorMessage("Please upload an Excel file");
      return;
    }

    try {
      const file = testFiles[0].originFileObj || testFiles[0];
      const rows = await readExcel(file);
      const normalizedData = stringifyNestedObjects(expandToJsonStringifiedObjects(normalizeKeys(rows)));
      setSheetPreview(normalizedData.slice(0, 5));
      const csvBody = rows.length ? XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet(rows)) : "";

      const response = await fetch(`${frontEndUrl}api/import-csv`, {
        method: "POST",
        body: JSON.stringify({
          table: typeFor || "lead",
          csv: csvBody,
        }),
      });

      if (!response.ok) throw new Error("API error");
      successMessage("Excel successfully imported to server!");
      hideModal();
      setTestFiles([]);
      window.location.reload();
    } catch (error) {
      console.error(error);
      errorMessage("Could not import Excel file. Please verify the sheet.");
    }
  };

  const handleDownloadSample = () => {
    const sample = SAMPLE_DATA[typeFor] || SAMPLE_DATA.lead;
    const worksheet = XLSX.utils.json_to_sheet(sample);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, typeFor || "sample");
    const wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
    const blob = new Blob([wbout], { type: "application/octet-stream" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = `${typeFor || "sample"}_template.xlsx`;
    link.click();
  };

  return (
    <>
      <div className="flex gap-3">
        <InputItem
          type="button"
          title="Import as Excel"
          icon={<GoogleIcon name="download" size={22} />}
          onClick={showModal}
        />
        {/* <InputItem
          type="button"
          title="Download Excel template"
          icon={<GoogleIcon name="download" size={22} />}
          onClick={handleDownloadSample}
        /> */}
      </div>

      <Modal
        title={`Import ${typeFor} data`}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={hideModal}
        okText="Import"
        width="90%"
      >
        <InputItem
          type="fileupload"
          accept=".xlsx"
          subtype="drag"
          placeholder={`Upload ${typeFor} Excel file`}
          value={testFiles}
          onChange={setTestFiles}
          formValidation={["myFiles"]}
        />
        {sheetPreview.length > 0 && (
          <pre>{JSON.stringify(sheetPreview, null, 2)}</pre>
        )}
      </Modal>
    </>
  );
}
