/**
 * @fileoverview React component for Playground.jsx
 * 
 * @module pages.Playground.Playground
 */

import React, { useState, useCallback } from "react";
import { PanelGroup, Panel } from "react-resizable-panels";
import { Moon, Sun, HelpCircle } from "lucide-react";
import * as Blockly from "blockly/core";
import "blockly/blocks";
import GameNavBar from "../../components/game/GameNavBar";
import ResizeHandle from "../../components/game/ResizeHandle";
import PlaygroundEditor from "./components/PlaygroundEditor";
import PlaygroundViewer from "./components/PlaygroundViewer";
import PlaygroundModal from "./components/PlaygroundModal";
import { useCodeGeneration } from "./hooks/useCodeGeneration";
import { useCodeExecution } from "./hooks/useCodeExecution";
import { usePlaygroundTour } from "./hooks/usePlaygroundTour";
import { useIsMobile } from "../../hooks/useIsMobile";
import "shepherd.js/dist/css/shepherd.css";
import "../../styles/shepherd-theme.css";
import "./Playground.css";

const Playground = () => {
  const [workspace, setWorkspace] = useState(null);
  const [workspaceVersion, setWorkspaceVersion] = useState(0);
  const [theme, setTheme] = useState("light");
  const [modal, setModal] = useState({
    isOpen: false,
    type: "success",
    title: "",
    message: "",
    details: "",
  });
  const isMobile = useIsMobile();
  const generatedCode = useCodeGeneration(workspace, workspaceVersion);
  const { output, isRunning, runCode, clearOutput } = useCodeExecution();
  const { startTour } = usePlaygroundTour();

  const blockCount = generatedCode.javascript
    ? generatedCode.javascript.split("\n").filter((line) => line.trim()).length
    : 0;

  const handleWorkspaceChange = useCallback((newWorkspace) => {
    setWorkspace(newWorkspace);
    setWorkspaceVersion((v) => v + 1);
  }, []);

  const handleRunCode = useCallback(() => {
    if (generatedCode.javascript) {
      runCode(generatedCode.javascript);
    }
  }, [generatedCode.javascript, runCode]);

  const toggleTheme = useCallback(() => {
    setTheme((prev) => (prev === "light" ? "dark" : "light"));
  }, []);

  const handleHelp = useCallback(() => {
    startTour();
  }, [startTour]);

  const closeModal = useCallback(() => {
    setModal({
      isOpen: false,
      type: "success",
      title: "",
      message: "",
      details: "",
    });
  }, []);

  const handleDownloadWorkspace = useCallback(() => {
    if (!workspace) {
      setModal({
        isOpen: true,
        type: "error",
        title: "Erro ao Salvar",
        message: "Nenhum workspace disponível para salvar.",
        details: "",
      });
      return;
    }

    try {
      const json = Blockly.serialization.workspaces.save(workspace);
      const dataStr = JSON.stringify(json, null, 2);
      const dataBlob = new Blob([dataStr], { type: "application/json" });
      const url = URL.createObjectURL(dataBlob);
      const link = document.createElement("a");
      link.href = url;
      const fileName = `playground-${new Date().toISOString().slice(0, 10)}.json`;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      setModal({
        isOpen: true,
        type: "success",
        title: "Blocos Salvos com Sucesso!",
        message: "Seu workspace foi exportado com sucesso.",
        details: `Arquivo: ${fileName}\nLocalização: Pasta de Downloads`,
      });
    } catch (error) {
      console.error("Erro ao baixar workspace:", error);
      setModal({
        isOpen: true,
        type: "error",
        title: "Erro ao Salvar",
        message: "Ocorreu um erro ao exportar o workspace.",
        details: error.message,
      });
    }
  }, [workspace]);

  const handleUploadWorkspace = useCallback(() => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json";

    input.onchange = (e) => {
      const file = e.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          const json = JSON.parse(event.target.result);

          if (!workspace) {
            setModal({
              isOpen: true,
              type: "error",
              title: "Erro ao Carregar",
              message: "O workspace não está pronto para receber dados.",
              details: "",
            });
            return;
          }

          // Limpar workspace atual
          workspace.clear();

          // Carregar novo workspace
          Blockly.serialization.workspaces.load(json, workspace);

          // Atualizar versão para forçar regeneração do código
          setWorkspaceVersion((v) => v + 1);

          setModal({
            isOpen: true,
            type: "success",
            title: "Blocos Carregados com Sucesso!",
            message: "O workspace foi carregado e está pronto para uso.",
            details: `Arquivo: ${file.name}`,
          });
        } catch (error) {
          console.error("Erro ao carregar workspace:", error);
          setModal({
            isOpen: true,
            type: "error",
            title: "Erro ao Carregar",
            message:
              "Não foi possível carregar o arquivo. Verifique se é um arquivo JSON válido.",
            details: error.message,
          });
        }
      };

      reader.readAsText(file);
    };

    input.click();
  }, [workspace]);

  return (
    <div
      className={`w-screen h-screen flex flex-col overflow-hidden transition-colors duration-300 ${theme === "light" ? "bg-gray-100" : "bg-[#1e1e1e]"}`}
    >
      <GameNavBar title="Laboratório" type="code" />

      <div className="flex-1 overflow-hidden">
        <PanelGroup direction={isMobile ? "vertical" : "horizontal"}>
          <Panel
            defaultSize={50}
            minSize={isMobile ? 10 : 50}
            maxSize={isMobile ? 90 : 50}
          >
            <div
              className={`h-full flex flex-col ${theme === "light" ? "bg-white" : "bg-[#1e1e1e]"}`}
            >
              <div
                className={`flex justify-between items-center px-5 py-4 min-h-[60px] border-b-2 ${theme === "light" ? "bg-gray-100 border-gray-300 text-gray-800" : "bg-[#252526] border-gray-700 text-white"}`}
                style={{
                  borderBottomColor: "var(--action-green)",
                }}
              >
                <h2 className="m-0 text-lg font-title font-semibold leading-none">
                  Editor de Blocos
                </h2>
                {!isMobile && (
                  <div className="flex items-center gap-2">
                    <button
                      className={`rounded-lg p-2 flex items-center justify-center transition-all duration-200 flex-shrink-0 w-10 h-10 ${
                        theme === "light"
                          ? "bg-black/10 hover:bg-black/20 text-gray-800"
                          : "bg-white/10 hover:bg-white/20 text-white"
                      } hover:scale-110`}
                      onClick={handleHelp}
                      title="Ajuda"
                      data-tour="help-button"
                    >
                      <HelpCircle className="w-5 h-5" />
                    </button>
                  </div>
                )}
              </div>
              <div className="flex-1 overflow-hidden">
                <PlaygroundEditor
                  onWorkspaceChange={handleWorkspaceChange}
                  onDownloadWorkspace={handleDownloadWorkspace}
                  onUploadWorkspace={handleUploadWorkspace}
                  onRunCode={handleRunCode}
                  onHelp={handleHelp}
                  isRunning={isRunning}
                  blockCount={blockCount}
                  theme={theme}
                />
              </div>
            </div>
          </Panel>

          <ResizeHandle
            direction={isMobile ? "vertical" : "horizontal"}
            theme={theme}
            disabled={!isMobile}
          />

          <Panel
            defaultSize={50}
            minSize={isMobile ? 15 : 50}
            maxSize={isMobile ? 85 : 50}
          >
            <div
              className={`h-full flex flex-col ${theme === "light" ? "bg-white" : "bg-[#1e1e1e]"}`}
            >
              <div
                className={`flex justify-between items-center px-5 py-4 min-h-[60px] border-b-2 ${theme === "light" ? "bg-gray-100 border-gray-300 text-gray-800" : "bg-[#252526] border-gray-700 text-white"}`}
                style={{
                  borderBottomColor: "var(--action-green)",
                }}
              >
                <h2 className="m-0 text-lg font-title font-semibold leading-none">
                  Código
                </h2>
                <button
                  className={`rounded-lg p-2 flex items-center justify-center transition-all duration-200 ml-auto flex-shrink-0 w-10 h-10 ${
                    theme === "light"
                      ? "bg-black/10 hover:bg-black/20 text-gray-800"
                      : "bg-white/10 hover:bg-white/20 text-white"
                  } hover:scale-110`}
                  onClick={toggleTheme}
                  title={
                    theme === "light"
                      ? "Mudar para tema escuro"
                      : "Mudar para tema claro"
                  }
                  data-tour="theme-toggle"
                >
                  {theme === "light" ? (
                    <Moon className="w-5 h-5" />
                  ) : (
                    <Sun className="w-5 h-5" />
                  )}
                </button>
              </div>
              <div className="flex-1 overflow-hidden">
                <PlaygroundViewer
                  generatedCode={generatedCode}
                  output={output}
                  onClearConsole={clearOutput}
                  theme={theme}
                />
              </div>
            </div>
          </Panel>
        </PanelGroup>
      </div>

      <PlaygroundModal
        isOpen={modal.isOpen}
        onClose={closeModal}
        type={modal.type}
        title={modal.title}
        message={modal.message}
        details={modal.details}
      />
    </div>
  );
};

export default Playground;
