import { useMemo, useState } from "react";
import Editor from "@monaco-editor/react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Play, Download } from "lucide-react";
import { AeThexCompiler, type CompileTarget } from "@/lib/aethex/compiler";
import { useToast } from "@/hooks/use-toast";

const sampleFiles = [
  {
    name: "main.tsx",
    path: "src/main.tsx",
    language: "typescript",
    content: `import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
import "./index.css"

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)
`,
  },
  {
    name: "server.ts",
    path: "server/index.ts",
    language: "typescript",
    content: `import express from "express"

const app = express()
app.get("/health", (_req, res) => res.json({ ok: true }))
app.listen(3000, () => console.log("Server listening on :3000"))
`,
  },
  {
    name: "styles.css",
    path: "src/styles.css",
    language: "css",
    content: `:root { --accent: #00d9ff; }
body { margin: 0; font-family: system-ui, sans-serif; }
`,
  },
  {
    name: "hello.aethex",
    path: "src/hello.aethex",
    language: "aethex",
    content: `# AeThex Language Example
# Cross-platform metaverse development

reality HelloWorld {
    platforms: [roblox, web]
}

journey Welcome(username) {
    platform: all

    notify "Welcome to AeThex, " + username + "!"

    when username === "admin" {
        notify "Admin access granted"
    } otherwise {
        notify "Guest mode activated"
    }
}
`,
  },
  {
    name: "auth.aethex",
    path: "src/auth.aethex",
    language: "aethex",
    content: `# AeThex Authentication Example
import { Passport, SafeInput, Compliance } from "@aethex/core"

reality SecureAuth {
    platforms: [roblox, uefn, web]
}

journey Login(username, age) {
    platform: all

    # COPPA compliance check
    when !Compliance.isCOPPACompliant(age) {
        notify "User must be 13+ to login"
        return
    }

    # PII validation
    let validation = SafeInput.validate(username)

    when !validation.valid {
        notify "Invalid username: " + validation.message
        return
    }

    # Create passport
    let passport = new Passport(username)

    when passport.verify() {
        sync passport across [roblox, uefn, web]
        notify "Logged in successfully!"
        reveal passport
    }
}
`,
  },
];

export default function IdePage() {
  const [activePath, setActivePath] = useState(sampleFiles[0].path);
  const [contents, setContents] = useState<Record<string, string>>(() => {
    const initial: Record<string, string> = {};
    sampleFiles.forEach((file) => {
      initial[file.path] = file.content;
    });
    return initial;
  });
  const [compileTarget, setCompileTarget] = useState<CompileTarget>('javascript');
  const [compiledCode, setCompiledCode] = useState<string>('');
  const { toast } = useToast();

  const activeFile = useMemo(() => sampleFiles.find((f) => f.path === activePath)!, [activePath]);
  const isAeThexFile = activeFile.language === 'aethex';

  const handleCompile = () => {
    if (!isAeThexFile) {
      toast({
        title: "Not an AeThex file",
        description: "Select a .aethex file to compile",
        variant: "destructive"
      });
      return;
    }

    const compiler = new AeThexCompiler({ target: compileTarget, sourceFile: activeFile.path });
    const result = compiler.compile(contents[activeFile.path]);

    if (result.errors.length > 0) {
      toast({
        title: "Compilation Failed",
        description: result.errors.map(e => `Line ${e.line}: ${e.message}`).join('\n'),
        variant: "destructive"
      });
      return;
    }

    if (result.warnings.length > 0) {
      toast({
        title: "Compilation Warnings",
        description: result.warnings.map(w => `Line ${w.line}: ${w.message}`).join('\n'),
      });
    }

    setCompiledCode(result.code);
    toast({
      title: "Compiled Successfully",
      description: `Compiled to ${compileTarget}`,
    });
  };

  const handleDownload = () => {
    if (!compiledCode) {
      toast({
        title: "Nothing to download",
        description: "Compile your code first",
        variant: "destructive"
      });
      return;
    }

    const ext = compileTarget === 'javascript' ? 'js' : compileTarget === 'roblox' ? 'lua' : 'txt';
    const blob = new Blob([compiledCode], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${activeFile.name.replace('.aethex', '')}.${ext}`;
    a.click();
    URL.revokeObjectURL(url);

    toast({
      title: "Downloaded",
      description: `${a.download} saved`,
    });
  };

  return (
    <div className="flex h-screen w-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 text-slate-100">
      <aside className="w-64 border-r border-white/10 bg-slate-950/60 backdrop-blur">
        <div className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-cyan-300">Workspace</div>
        <nav className="px-2 pb-4 space-y-1">
          {sampleFiles.map((file) => {
            const isActive = file.path === activePath;
            return (
              <button
                key={file.path}
                onClick={() => setActivePath(file.path)}
                className={cn(
                  "w-full rounded-md px-3 py-2 text-left text-sm transition",
                  isActive ? "bg-cyan-500/20 text-cyan-100 border border-cyan-500/40" : "hover:bg-white/5 text-slate-200"
                )}
              >
                <div className="text-sm font-medium">{file.name}</div>
                <div className="text-[11px] text-slate-400">{file.path}</div>
              </button>
            );
          })}
        </nav>
      </aside>

      <main className="flex-1 flex flex-col">
        <header className="flex items-center justify-between border-b border-white/10 bg-slate-950/60 px-4 py-2 backdrop-blur">
          <div>
            <div className="text-sm font-semibold text-cyan-200">AeThex IDE (Monaco)</div>
            <div className="text-xs text-slate-400">Active file: {activeFile.path}</div>
          </div>
          <div className="flex gap-2 items-center">
            {isAeThexFile && (
              <>
                <select
                  value={compileTarget}
                  onChange={(e) => setCompileTarget(e.target.value as CompileTarget)}
                  className="bg-slate-800 border border-white/10 rounded px-2 py-1 text-xs text-slate-200"
                >
                  <option value="javascript">JavaScript</option>
                  <option value="roblox">Roblox (Lua)</option>
                  <option value="uefn">UEFN (Verse)</option>
                  <option value="unity">Unity (C#)</option>
                </select>
                <Button
                  size="sm"
                  onClick={handleCompile}
                  className="bg-cyan-600 hover:bg-cyan-700 text-white"
                >
                  <Play className="w-3 h-3 mr-1" />
                  Compile
                </Button>
                {compiledCode && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={handleDownload}
                    className="border-white/10"
                  >
                    <Download className="w-3 h-3 mr-1" />
                    Download
                  </Button>
                )}
              </>
            )}
            <span className="rounded border border-white/10 px-2 py-1 text-xs text-slate-400">Monaco powered</span>
          </div>
        </header>

        <section className="flex-1 min-h-0">
          <Editor
            path={activeFile.path}
            language={activeFile.language}
            theme="vs-dark"
            value={contents[activeFile.path]}
            onChange={(val) => {
              setContents((prev) => ({ ...prev, [activeFile.path]: val ?? "" }));
            }}
            options={{
              fontSize: 14,
              minimap: { enabled: false },
              smoothScrolling: true,
              scrollBeyondLastLine: false,
              wordWrap: "on",
              automaticLayout: true,
            }}
            loading={<div className="p-6 text-slate-300">Loading Monaco editor...</div>}
          />
        </section>
      </main>
    </div>
  );
}
