import React from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import CodeBlock from "./CodeBlock";

export default function CodeModal({ isOpen, onClose, code, language = "python" }) {
  if (!isOpen) return null;

  let codeString = "";
  if (typeof code === "string") {
    codeString = code;
  } else if (code && typeof code === "object") {
    codeString = code.code || JSON.stringify(code, null, 2);
  }

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
        onClick={onClose}
      >
        <motion.div
          initial={{ scale: 0.9, opacity: 0, y: 30 }}
          animate={{ scale: 1, opacity: 1, y: 0 }}
          exit={{ scale: 0.9, opacity: 0, y: 30 }}
          transition={{ duration: 0.3, ease: "easeInOut" }}
          className="w-full max-w-4xl"
          onClick={(e) => e.stopPropagation()}
        >
          <Card className="border-0 shadow-2xl bg-gray-900/80 backdrop-blur-lg border-purple-500/30 text-white">
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-purple-400">
                Generated Training Script
              </CardTitle>
              <Button variant="ghost" size="icon" onClick={onClose}>
                <X className="w-5 h-5 text-gray-400" />
              </Button>
            </CardHeader>
            <CardContent>
              <p className="text-gray-300 mb-4 text-sm">
                This is the complete PyTorch training script generated by the AI based on your configuration. It's ready to be executed by the training monitor.
              </p>
              <div className="max-h-[60vh] overflow-y-auto rounded-lg">
                <CodeBlock code={codeString} language={language} />
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}