import React, { useState, useEffect, useRef } from "react";
import fatorialSvg from "./assets/fatorial.svg";

const CtaPlayground = () => {
  const [activeTab, setActiveTab] = useState("blocos");
  const [displayedCode, setDisplayedCode] = useState("");
  const [isTyping, setIsTyping] = useState(true);
  const typingTimeoutRef = useRef(null);
  const terminalRef = useRef(null);

  /**
   * Gera elementos React para destacar sintaxe de `code` na `language` especificada.
   * Suporta 'javascript', 'python' e 'console'. Retorna array de nós React.
   *
   * @function highlightCode
   * @param {string} code - Código-fonte a ser destacado
   * @param {string} language - Linguagem do código ('javascript'|'python'|'console')
   * @returns {React.ReactNode[]} Elementos React representando o código com destaque
   */
  const highlightCode = (code, language) => {
    if (language === "console") {
      // Highlight para console
      return code.split("\n").map((line, i) => {
        if (line.startsWith(">")) {
          return (
            <div key={i}>
              <span className="text-green-400">&gt;</span>
              <span className="text-gray-300">{line.substring(1)}</span>
            </div>
          );
        }
        return (
          <div key={i} className="text-gray-300">
            {line}
          </div>
        );
      });
    }

    // Palavras-chave por linguagem
    const keywords = {
      javascript: [
        "var",
        "for",
        "count",
        "if",
        "else",
        "function",
        "return",
        "const",
        "let",
        "typeof",
        "window",
        "alert",
      ],
      python: [
        "from",
        "import",
        "for",
        "in",
        "range",
        "int",
        "if",
        "else",
        "def",
        "return",
        "print",
        "isinstance",
        "str",
      ],
    };

    const types = {
      javascript: ["Number"],
      python: ["Number", "numbers"],
    };

    const currentKeywords = keywords[language] || [];
    const currentTypes = types[language] || [];

    // Tokenizar o código
    const tokens = [];
    let currentToken = "";
    let inString = false;
    let stringChar = "";
    let _inComment = false;

    for (let i = 0; i < code.length; i++) {
      const char = code[i];
      const nextChar = code[i + 1];

      // Detectar início/fim de string
      if ((char === '"' || char === "'") && code[i - 1] !== "\\") {
        if (!inString) {
          if (currentToken) {
            tokens.push({ type: "text", value: currentToken });
            currentToken = "";
          }
          inString = true;
          stringChar = char;
          currentToken = char;
        } else if (char === stringChar) {
          currentToken += char;
          tokens.push({ type: "string", value: currentToken });
          currentToken = "";
          inString = false;
          stringChar = "";
        } else {
          currentToken += char;
        }
        continue;
      }

      if (inString) {
        currentToken += char;
        continue;
      }

      // Detectar comentários
      if (char === "/" && nextChar === "/" && language === "javascript") {
        if (currentToken) {
          tokens.push({ type: "text", value: currentToken });
          currentToken = "";
        }
        // Pegar resto da linha
        const endOfLine = code.indexOf("\n", i);
        const comment = code.substring(
          i,
          endOfLine !== -1 ? endOfLine : code.length,
        );
        tokens.push({ type: "comment", value: comment });
        i = endOfLine !== -1 ? endOfLine - 1 : code.length;
        continue;
      }

      if (char === "#" && language === "python") {
        if (currentToken) {
          tokens.push({ type: "text", value: currentToken });
          currentToken = "";
        }
        const endOfLine = code.indexOf("\n", i);
        const comment = code.substring(
          i,
          endOfLine !== -1 ? endOfLine : code.length,
        );
        tokens.push({ type: "comment", value: comment });
        i = endOfLine !== -1 ? endOfLine - 1 : code.length;
        continue;
      }

      // Separadores
      if (/\s|[(){}.,;]/.test(char) || char === "[" || char === "]") {
        if (currentToken) {
          tokens.push({ type: "text", value: currentToken });
          currentToken = "";
        }
        tokens.push({ type: "separator", value: char });
        continue;
      }

      // Operadores
      if (/[+\-*/<>=!:]/.test(char)) {
        if (currentToken) {
          tokens.push({ type: "text", value: currentToken });
          currentToken = "";
        }
        tokens.push({ type: "operator", value: char });
        continue;
      }

      currentToken += char;
    }

    if (currentToken) {
      if (inString) {
        tokens.push({ type: "string", value: currentToken });
      } else {
        tokens.push({ type: "text", value: currentToken });
      }
    }

    // Renderizar tokens com cores
    return tokens.map((token, i) => {
      if (token.type === "string") {
        return (
          <span key={i} className="text-green-400">
            {token.value}
          </span>
        );
      }
      if (token.type === "comment") {
        return (
          <span key={i} className="text-gray-500 italic">
            {token.value}
          </span>
        );
      }
      if (token.type === "operator") {
        return (
          <span key={i} className="text-pink-400">
            {token.value}
          </span>
        );
      }
      if (token.type === "separator") {
        return (
          <span key={i} className="text-gray-300">
            {token.value}
          </span>
        );
      }
      if (token.type === "text") {
        // Verificar se é palavra-chave
        if (currentKeywords.includes(token.value)) {
          return (
            <span key={i} className="text-blue-400 font-semibold">
              {token.value}
            </span>
          );
        }
        // Verificar se é tipo
        if (currentTypes.includes(token.value)) {
          return (
            <span key={i} className="text-cyan-400">
              {token.value}
            </span>
          );
        }
        // Verificar se é número
        if (/^\d+$/.test(token.value)) {
          return (
            <span key={i} className="text-orange-400">
              {token.value}
            </span>
          );
        }
        // Verificar se é booleano ou null
        if (
          [
            "True",
            "False",
            "None",
            "null",
            "undefined",
            "true",
            "false",
          ].includes(token.value)
        ) {
          return (
            <span key={i} className="text-purple-400">
              {token.value}
            </span>
          );
        }
        return (
          <span key={i} className="text-gray-300">
            {token.value}
          </span>
        );
      }
      return <span key={i}>{token.value}</span>;
    });
  };

  // Código do exemplo de fatorial
  const codes = {
    javascript: `var numero, fatorial, i;

numero = 5;
fatorial = 1;
i = 1;
for (var count = 0; count < numero; count++) {
  fatorial = fatorial * i;
  i = (typeof i === 'number' ? i : 0) + 1;
}
window.alert([numero,'! = ',fatorial].join(''));`,

    python: `from numbers import Number

numero = None
fatorial = None
i = None

numero = 5
fatorial = 1
i = 1
for count in range(int(numero)):
  fatorial = fatorial * i
  i = (i if isinstance(i, Number) else 0) + 1
print(''.join([str(x) for x in [numero, '! = ', fatorial]]))`,

    console: `> Executando programa...
> 
> Calculando 5!
> 5! = 120
> 
> Programa finalizado com sucesso.`,
  };

  // Efeito de digitação (typing effect) - apenas para abas de código
  useEffect(() => {
    if (activeTab === "blocos") {
      setIsTyping(false);
      setDisplayedCode("");
      return;
    }

    setDisplayedCode("");
    setIsTyping(true);

    const currentCode = codes[activeTab];
    let currentIndex = 0;

    /**
     * Função interna que simula digitação de `codes[activeTab]`.
     * Atualiza `displayedCode` caractere a caractere e controla `isTyping`.
     *
     * @private
     * @returns {void}
     */
    const typeCharacter = () => {
      if (currentIndex < currentCode.length) {
        setDisplayedCode(currentCode.substring(0, currentIndex + 1));
        currentIndex++;

        // Auto-scroll para acompanhar o texto
        if (terminalRef.current) {
          terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
        }

        // Velocidade variável para simular digitação humana
        const delay = Math.random() * 30 + 10; // 10-40ms entre caracteres
        typingTimeoutRef.current = setTimeout(typeCharacter, delay);
      } else {
        setIsTyping(false);
      }
    };

    // Pequeno delay antes de começar a digitar
    const startDelay = setTimeout(() => {
      typeCharacter();
    }, 300);

    // Cleanup
    return () => {
      clearTimeout(startDelay);
      if (typingTimeoutRef.current) {
        clearTimeout(typingTimeoutRef.current);
      }
    };
  }, [activeTab]);

  return (
    <section className="relative overflow-hidden">
      {/* Keyframe animation for cursor blink */}
      <style>{`
        @keyframes blink-cursor {
          0%, 49% { opacity: 1; }
          50%, 100% { opacity: 0; }
        }
        .cursor-blink {
          animation: blink-cursor 1s infinite;
        }
      `}</style>

      {/* Background com gradiente igual ao Hero */}
      <div
        className="absolute inset-0 h-full w-full -z-10"
        style={{
          background: "linear-gradient(135deg, #dbeafe 0%, #faf5ff 100%)",
        }}
      ></div>

      {/* Container principal */}
      <div className=" w-full">
        <div className="w-full  overflow-hidden">
          {/* Terminal de Código (Esquerda) */}
          <div className="flex flex-col justify-center text-sm min-w-0">
            <div className="overflow-hidden">
              <div className="relative flex-1 bg-white/50 bg-gray-50/50 backdrop-blur-lg shadow-2xl rounded-xl border border-gray-200 border-gray-200">
                {/* Header do Terminal */}
                <div className="flex items-center justify-between p-3 border-b border-gray-200 border-gray-200">
                  <div className="flex items-center gap-2 pl-2">
                    <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                    <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                    <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                  </div>

                  {/* Tabs */}
                  <div className="flex flex-wrap gap-2">
                    <button
                      onClick={() => setActiveTab("blocos")}
                      className={`px-4 py-1 rounded-md transition-colors font-medium text-sm ${
                        activeTab === "blocos"
                          ? "bg-blue-600 text-white"
                          : "text-gray-600 text-gray-600 hover:bg-blue-600/20 hover:text-blue-600 dark:hover:text-blue-400"
                      }`}
                    >
                      Blocos
                    </button>
                    <button
                      onClick={() => setActiveTab("javascript")}
                      className={`px-4 py-1 rounded-md transition-colors font-medium text-sm ${
                        activeTab === "javascript"
                          ? "bg-blue-600 text-white"
                          : "text-gray-600 text-gray-600 hover:bg-blue-600/20 hover:text-blue-600 dark:hover:text-blue-400"
                      }`}
                    >
                      JavaScript
                    </button>
                    <button
                      onClick={() => setActiveTab("python")}
                      className={`px-4 py-1 rounded-md transition-colors font-medium text-sm ${
                        activeTab === "python"
                          ? "bg-blue-600 text-white"
                          : "text-gray-600 text-gray-600 hover:bg-blue-600/20 hover:text-blue-600 dark:hover:text-blue-400"
                      }`}
                    >
                      Python
                    </button>
                    <button
                      onClick={() => setActiveTab("console")}
                      className={`px-4 py-1 rounded-md transition-colors font-medium text-sm ${
                        activeTab === "console"
                          ? "bg-blue-600 text-white"
                          : "text-gray-600 text-gray-600 hover:bg-blue-600/20 hover:text-blue-600 dark:hover:text-blue-400"
                      }`}
                    >
                      Console
                    </button>
                  </div>
                </div>

                {/* Conteúdo do Terminal */}
                <div
                  ref={terminalRef}
                  className={`relative p-6 h-96 overflow-auto scroll-smooth ${
                    activeTab === "blocos"
                      ? "bg-gradient-to-br from-blue-50 to-purple-50"
                      : "bg-gray-50 dark:bg-gray-900"
                  }`}
                >
                  {activeTab === "blocos" ? (
                    <div className="flex flex-col items-center justify-center h-full">
                      <img
                        src={fatorialSvg}
                        alt="Exemplo de blocos visuais - Cálculo de fatorial"
                        className="w-full max-w-md h-auto object-contain"
                      />
                    </div>
                  ) : (
                    <pre className="text-sm font-mono leading-relaxed whitespace-pre-wrap">
                      <code>
                        {highlightCode(displayedCode, activeTab)}
                        {isTyping && (
                          <span className="inline-block w-2 h-4 ml-0.5 bg-blue-400 cursor-blink"></span>
                        )}
                      </code>
                    </pre>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default CtaPlayground;
