import React, { useEffect, useState } from "react";
import useLayoutStore from "../../store/builder/uselayoutStore";
import { useDfxUpload } from "../../store/builder/store";
import DxfParser from "dxf-parser";
import { Box3, BufferGeometry, MathUtils, Vector3 } from "three";
import { getWallPointsFromBlueprint } from "../../modules/builder/dfx/functions/getWallPointsFromBlueprint";
import { convertDXFToThree } from "../../modules/builder/dfx/functions/convertDxfToThree";
// Define types for DXF entities and geometries


const SelectFloorPlan: React.FC = () => {
  const { currentLayout, setLayout } = useLayoutStore();
  const { setDfxUploaded, setDfxGenerate } = useDfxUpload();

  const [parsedFile, setParsedFile] = useState<DXFData>();
  const [generate, setGenerate] = useState<boolean>(false);

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    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 parsedData = parser.parse(dxfContent) as DXFData;
        const geometries = convertDXFToThree(parsedData);

        setParsedFile(parsedData);
        setDfxUploaded(geometries);

      } catch (error) {
        echo.error("Failed to import your .dxf file")
      }
    };

    reader.readAsText(file);
  };

  useEffect(() => {
    if (parsedFile !== undefined)
      getWallPointsFromBlueprint({ parsedData: parsedFile, setDfxGenerate })
  }, [generate])

  return (
    <div className="select-floorplane-wrapper">
      Preset Layouts
      <div className="presets-container">
        <button
          className={`preset ${currentLayout === "layout1" ? "active" : ""}`}
          onClick={() => {
            setLayout("layout1");
          }}
        >
          Preset 1
        </button>
        <button
          className={`preset ${currentLayout === "layout2" ? "active" : ""}`}
          onClick={() => {
            setLayout("layout2");
          }}
        >
          Preset 2
        </button>

        <input
          type="file"
          id="file-upload"
          accept=".dxf"
          style={{ display: "none", width: "10px" }}
          onChange={handleFileUpload}
        />
        <label
          htmlFor="file-upload"
          className="preset"
          style={{
            cursor: "pointer",
            padding: "10px 48px",
          }}
        >
          Upload
        </label>
        <button
          type="button"
          id="generate-upload"
          onClick={() => {
            setDfxUploaded([])
            setGenerate(!generate);
          }}
        >
          Generate
        </button>
      </div>
    </div >
  );
};

export default SelectFloorPlan;





