import React, { useEffect, useState } from "react";
import useLayoutStore from "../../store/builder/uselayoutStore";
import { useActiveLayer, useDfxUpload } from "../../store/builder/store";
import DxfParser from "dxf-parser";
import { getWallPointsFromBlueprint } from "../../modules/builder/dfx/functions/getWallPointsFromBlueprint";
import { convertDXFToThree } from "../../modules/builder/dfx/functions/convertDxfToThree";
import { AIIcon } from "../icons/ExportCommonIcons";
import { useBuilderStore } from "../../store/builder/useBuilderStore";
import { useSceneContext } from "../../modules/scene/sceneContext";
type DXFData = any;
const SelectFloorPlan: React.FC = () => {
  // Access layout state and state setters
  const { currentLayout, setLayout } = useLayoutStore();
  // Access DXF-related states and setters
  const { setDfxUploaded, setDxfWallGenerate, setObjValue, objValue } =
    useDfxUpload();
  const { activeLayer } = useActiveLayer();
  const { wallThickness, wallHeight, insideMaterial, outsideMaterial } = useBuilderStore();
  const { wallStore } = useSceneContext();
  const { addWall } = wallStore();
  // Local state to store the parsed DXF file
  const [parsedFile, setParsedFile] = useState<DXFData | undefined>(undefined);
  const { walls } = wallStore();
  // Flag to trigger generation after file upload
  const [generate, setGenerate] = useState<boolean>(false);

  // Handles file upload and DXF parsing
  const handleFileUpload = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setLayout(null); // Reset current layout
    setParsedFile(undefined); // Clear any previously parsed file
    const file = event.target.files?.[0];
    if (!file || !file.name.endsWith(".dxf")) {
      alert("Please upload a valid .dxf file.");
      return;
    }

    const reader = new FileReader();
    reader.onload = async (e) => {
      const dxfContent = e.target?.result as string;

      try {
        const parser = new DxfParser();
        const parsedDatas = parser.parse(dxfContent) as DXFData;
        const geometries = convertDXFToThree(parsedDatas);
        setParsedFile(parsedDatas);
        setObjValue({ x: 0, y: 0, z: 0 });
        setDfxUploaded(geometries);
      } catch (error) {
        console.error("Failed to import your .dxf file", error);
      } finally {
        // ✅ Reset input AFTER processing
        event.target.value = "";
      }
    };

    reader.readAsText(file); // Read the uploaded file as text
  };

  // Trigger wall point generation when `generate` flag changes
  useEffect(() => {
    if (parsedFile !== undefined) {
      getWallPointsFromBlueprint({
        parsedData: parsedFile,
        setDxfWallGenerate,
        objValue,
        wallThickness, wallHeight, outsideMaterial, insideMaterial, activeLayer, addWall, walls
      });
    }
  }, [generate]);

  return (
    <div className="select-floorplane-wrapper">
      Upload Layouts
      <div className="presets-container">
        <input
          type="file"
          id="file-upload"
          accept=".dxf"
          style={{ display: "none", width: "10px" }}
          onChange={handleFileUpload}
        />

        <label
          htmlFor="file-upload"
          className="preset upload-btn"
          style={{
            cursor: "pointer",
            padding: "10px 48px",
          }}
        >
          Upload
        </label>

        {parsedFile && (
          <button
            type="button"
            id="generate-upload"
            className="generate-walls-btn"
            onClick={() => {
              setDfxUploaded([]);
              setLayout(null);
              setGenerate(!generate);
            }}
          >
            <AIIcon />
            Generate
          </button>
        )}
      </div>
      or
      <div className="presets-container">
        <button
          className={`preset ${currentLayout === "layout1" ? "active" : ""}`}
          onClick={() => {
            setLayout("layout1");
            setDfxUploaded([]);
            setGenerate(false);
          }}
        >
          Preset 1
        </button>

        <button
          className={`preset ${currentLayout === "layout2" ? "active" : ""}`}
          onClick={() => {
            setLayout("layout2");
            setDfxUploaded([]);
            setGenerate(false);
          }}
        >
          Preset 2
        </button>
      </div>
    </div>
  );
};

export default SelectFloorPlan;
