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

import React from "react";
import {
  X,
  BookOpen,
  Play,
  Hash,
  User,
  RotateCw,
  Plus,
  Dices,
  BarChart3,
  Thermometer,
  Calculator,
} from "lucide-react";

const ExamplesModal = ({ isOpen, onClose, onSelectExample }) => {
  if (!isOpen) return null;

  const examples = [
    {
      id: "contador",
      name: "Contador de 1 a 10",
      description: "Um loop que conta de 1 a 10 e imprime cada valor",
      file: "/examples/contador.json",
      icon: Hash,
    },
    {
      id: "nome",
      name: "Imprimir Texto",
      description: "Um programa simples que imprime um texto",
      file: "/examples/nome.json",
      icon: User,
    },
    {
      id: "fibonacci",
      name: "Fibonacci",
      description: "Um exemplo de sequência de Fibonacci em blocos",
      file: "/examples/fibonacci.json",
      icon: RotateCw,
    },
    {
      id: "soma-lista",
      name: "Soma de Lista",
      description: "Percorre uma lista de números e calcula a soma total",
      file: "/examples/soma-lista.json",
      icon: Plus,
    },
    {
      id: "par-impar",
      name: "Par ou Ímpar",
      description:
        "Verifica se um número é par ou ímpar usando operador módulo",
      file: "/examples/par-impar.json",
      icon: Dices,
    },
    {
      id: "maior-numero",
      name: "Maior Número",
      description: "Encontra o maior número em uma lista usando comparação",
      file: "/examples/maior-numero.json",
      icon: BarChart3,
    },
    {
      id: "temperatura",
      name: "Conversor de Temperatura",
      description: "Converte temperatura de Celsius para Fahrenheit",
      file: "/examples/temperatura.json",
      icon: Thermometer,
    },
    {
      id: "fatorial",
      name: "Cálculo Fatorial",
      description: "Calcula o fatorial de um número usando loop",
      file: "/examples/fatorial.json",
      icon: Calculator,
    },
  ];

  const handleExampleClick = async (example) => {
    try {
      const response = await fetch(example.file);
      if (!response.ok) {
        throw new Error("Erro ao carregar exemplo");
      }
      const data = await response.json();

      // Extrair apenas os dados do workspace (blocks e variables)
      const workspaceData = {
        blocks: data.blocks,
        ...(data.variables && { variables: data.variables }),
      };

      onSelectExample(workspaceData);
      onClose();
    } catch (error) {
      console.error("Erro ao carregar exemplo:", error);
      alert("Erro ao carregar exemplo. Tente novamente.");
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white/95 backdrop-blur-sm border border-white/30 rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-white/20">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-gradient-to-br from-purple-400 to-pink-500 rounded-lg flex items-center justify-center text-white">
              <BookOpen className="w-5 h-5" />
            </div>
            <h3 className="text-xl font-bold text-gray-800">Exemplos</h3>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-gray-200 hover:bg-gray-300 flex items-center justify-center text-gray-600 transition-colors"
            aria-label="Fechar"
            data-modal-close
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="grid gap-4">
            {examples.map((example) => {
              const IconComponent = example.icon;
              return (
                <button
                  key={example.id}
                  onClick={() => handleExampleClick(example)}
                  className="group relative flex items-start gap-4 p-5 bg-white/80 backdrop-blur-sm border border-white/30 rounded-xl shadow-lg hover:border-green-300 transition-all duration-200 text-left"
                >
                  {/* Icon */}
                  <div className="flex-shrink-0 w-10 h-10 bg-gradient-to-br from-purple-400 to-pink-500 rounded-lg flex items-center justify-center text-white">
                    <IconComponent className="w-5 h-5" />
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <h3 className="text-base font-semibold text-gray-800 mb-1 group-hover:text-green-600 transition-colors">
                      {example.name}
                    </h3>
                    <p className="text-sm text-gray-600">
                      {example.description}
                    </p>
                  </div>

                  {/* Arrow Icon */}
                  <div className="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Play className="w-5 h-5 text-green-500" />
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExamplesModal;
