"use client";

import { useState, useRef, useEffect } from "react";

export default function XgridsWizard() {
  const [files, setFiles] = useState<File[]>([]);
  const [status, setStatus] = useState<string>("Waiting for upload...");
  const [isProcessing, setIsProcessing] = useState(false);
  const workerRef = useRef<Worker | null>(null);

  useEffect(() => {
    const worker = new Worker(
      new URL("./workers/converter.worker.ts", import.meta.url),
    );
    workerRef.current = worker;

    worker.onmessage = (e) => {
      const { type, message, data } = e.data;
      if (type === "LOG") setStatus(message);

      if (type === "DONE") {
        setIsProcessing(false);
        setStatus("Pipeline Complete!");
        data.files.forEach((file: { name: string; blob: Blob }) => {
          downloadFile(file.blob, file.name);
        });
      }
    };
    return () => worker.terminate();
  }, []);

  const downloadFile = (blob: Blob, name: string) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = name;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleFolderUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const uploadedFiles = Array.from(e.target.files || []);
    if (uploadedFiles.length > 0) {
      setFiles(uploadedFiles);
      setStatus(`Loaded ${uploadedFiles.length} files. Ready to convert.`);
    }
  };

  const startPipeline = async () => {
    if (!files.length || !workerRef.current) return;

    setIsProcessing(true);
    setStatus("Preparing files for Worker...");

    const mainLcc = files.find((f) => f.name.toLowerCase().endsWith(".lcc"));

    const filesData = await Promise.all(
      files.map(async (f) => ({
        name: f.name,
        buffer: await f.arrayBuffer(),
      })),
    );

    // Send EVERYTHING to the worker.
    // The worker will now handle Collision, Environment, SOG, and LODs.
    workerRef.current.postMessage(
      {
        type: "START_CONVERSION",
        filesData,
        mainLccName: mainLcc?.name,
        fileName: mainLcc?.name.replace(".lcc", ""),
      },
      filesData.map((f) => f.buffer),
    );
  };

  return (
    <main className="min-h-screen bg-slate-900 text-white p-8 flex flex-col items-center">
      <div className="max-w-2xl w-full bg-slate-800 rounded-xl p-8 shadow-2xl border border-slate-700">
        <header className="mb-8 text-center">
          <h1 className="text-3xl font-bold mb-2">Xgrids Scene Wizard</h1>
          <p className="text-slate-400">Targeting collision.lci + scene.lcc</p>
        </header>

        <div className="space-y-6">
          <div className="border-2 border-dashed border-slate-600 rounded-lg p-10 text-center hover:border-blue-500 transition-colors">
            <input
              type="file"
              id="folder-upload"
              //@ts-ignore
              webkitdirectory=""
              directory=""
              className="hidden"
              onChange={handleFolderUpload}
            />
            <label htmlFor="folder-upload" className="cursor-pointer">
              <span className="bg-blue-600 px-6 py-3 rounded-md font-medium hover:bg-blue-500 transition-all inline-block shadow-lg">
                Select Xgrids Folder
              </span>
              <p className="mt-4 text-sm text-slate-500 italic">
                {files.length > 0
                  ? `${files.length} files selected`
                  : "Upload folder"}
              </p>
            </label>
          </div>

          <div className="bg-black/40 p-4 rounded-md font-mono text-sm border border-slate-700">
            <p
              className={`${isProcessing ? "text-yellow-400" : "text-emerald-400"}`}
            >
              {"> "} {status}
            </p>
          </div>

          <button
            onClick={startPipeline}
            disabled={files.length === 0 || isProcessing}
            className="w-full py-4 bg-emerald-600 hover:bg-emerald-500 disabled:bg-slate-700 disabled:text-slate-500 rounded-lg font-bold transition-all shadow-lg"
          >
            {isProcessing ? "Processing..." : "Generate Scene Files"}
          </button>
        </div>
      </div>
    </main>
  );
}
