import React, { useState, useRef, useEffect } from "react";
import { Eye, EyeOff, Smartphone, Monitor, Tablet, Maximize2, Minimize2, Code2, Copy, Check, ExternalLink } from "lucide-react";

const VIEWPORT_SIZES = {
  mobile: { width: 375, height: 667, label: "Mobile", icon: Smartphone },
  tablet: { width: 768, height: 1024, label: "Tablet", icon: Tablet },
  desktop: { width: "100%", height: 600, label: "Desktop", icon: Monitor },
};

export default function LivePreview({ html, css, js, title }) {
  const [viewport, setViewport] = useState("desktop");
  const [expanded, setExpanded] = useState(false);
  const [showCode, setShowCode] = useState(false);
  const [copied, setCopied] = useState(false);
  const iframeRef = useRef(null);

  const fullHtml = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"><\/script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Inter', system-ui, sans-serif; }
    ${css || ""}
  </style>
</head>
<body>
  ${html || ""}
  ${js ? `<script>${js}<\/script>` : ""}
</body>
</html>`;

  useEffect(() => {
    if (iframeRef.current) {
      const doc = iframeRef.current.contentDocument;
      if (doc) {
        doc.open();
        doc.write(fullHtml);
        doc.close();
      }
    }
  }, [fullHtml, viewport]);

  const vp = VIEWPORT_SIZES[viewport];
  const iframeWidth = vp.width === "100%" ? "100%" : `${vp.width}px`;

  function handleCopy() {
    navigator.clipboard.writeText(fullHtml);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  function openInNewTab() {
    const blob = new Blob([fullHtml], { type: "text/html" });
    const url = URL.createObjectURL(blob);
    window.open(url, "_blank");
    setTimeout(() => URL.revokeObjectURL(url), 5000);
  }

  return (
    <div className={`rounded-xl border border-anton-border overflow-hidden bg-anton-card ${expanded ? "fixed inset-4 z-50" : ""}`}>
      {/* Toolbar */}
      <div className="flex items-center justify-between px-3 py-2 bg-anton-surface border-b border-anton-border">
        <div className="flex items-center gap-2">
          <Eye size={14} className="text-green-400" />
          <span className="text-xs font-medium text-white">{title || "Live Preview"}</span>
        </div>

        <div className="flex items-center gap-1">
          {/* Viewport Switcher */}
          {Object.entries(VIEWPORT_SIZES).map(([key, val]) => {
            const Icon = val.icon;
            return (
              <button key={key} onClick={() => setViewport(key)}
                className={`p-1.5 rounded transition ${viewport === key ? "bg-anton-accent/20 text-anton-accent" : "text-anton-muted hover:text-white"}`}
                title={val.label}>
                <Icon size={14} />
              </button>
            );
          })}

          <div className="w-px h-4 bg-anton-border mx-1" />

          <button onClick={() => setShowCode(!showCode)}
            className={`p-1.5 rounded transition ${showCode ? "bg-blue-500/20 text-blue-400" : "text-anton-muted hover:text-white"}`}
            title="Toggle code">
            <Code2 size={14} />
          </button>

          <button onClick={handleCopy} className="p-1.5 rounded text-anton-muted hover:text-white transition" title="Copy HTML">
            {copied ? <Check size={14} className="text-green-400" /> : <Copy size={14} />}
          </button>

          <button onClick={openInNewTab} className="p-1.5 rounded text-anton-muted hover:text-white transition" title="Open in new tab">
            <ExternalLink size={14} />
          </button>

          <button onClick={() => setExpanded(!expanded)}
            className="p-1.5 rounded text-anton-muted hover:text-white transition"
            title={expanded ? "Minimize" : "Fullscreen"}>
            {expanded ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
          </button>
        </div>
      </div>

      {/* Preview Area */}
      <div className="flex justify-center bg-[#1a1a2e] p-4 overflow-auto" style={{ minHeight: expanded ? "calc(100vh - 120px)" : "400px" }}>
        <div style={{ width: iframeWidth, maxWidth: "100%" }} className="bg-white rounded-lg shadow-2xl overflow-hidden transition-all duration-300">
          <iframe
            ref={iframeRef}
            title="preview"
            sandbox="allow-scripts allow-same-origin"
            className="w-full border-0"
            style={{ height: expanded ? "calc(100vh - 160px)" : `${typeof vp.height === "number" ? vp.height : 500}px` }}
          />
        </div>
      </div>

      {/* Code Panel */}
      {showCode && (
        <div className="border-t border-anton-border bg-[#0d1117] p-3 max-h-60 overflow-auto">
          <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap">{fullHtml}</pre>
        </div>
      )}
    </div>
  );
}