import { useState, useCallback, useMemo } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import * as Tabs from "@radix-ui/react-tabs";
import { Cross2Icon, CopyIcon, CheckIcon, CodeIcon, FileTextIcon, ComponentInstanceIcon } from "@radix-ui/react-icons";
import { motion } from "motion/react";
import { useCanvasStore } from "@/stores/canvasStore";
import { exportLayout, availablePlaceholders } from "@/utils/layoutExporter";

interface ExportModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

type TabValue = "html" | "css" | "webcomponent";

export function ExportModal({ open, onOpenChange }: ExportModalProps) {
  const elements = useCanvasStore((state) => state.elements);
  const containerSettings = useCanvasStore((state) => state.containerSettings);
  const [activeTab, setActiveTab] = useState<TabValue>("html");
  const [copied, setCopied] = useState<TabValue | null>(null);

  // Generate export data
  const exportData = useMemo(() => {
    return exportLayout(elements, containerSettings);
  }, [elements, containerSettings]);

  // Handle copy to clipboard
  const handleCopy = useCallback(
    async (tab: TabValue) => {
      let content = "";
      switch (tab) {
        case "html":
          content = exportData.html;
          break;
        case "css":
          content = exportData.css;
          break;
        case "webcomponent":
          content = exportData.webComponentHtml;
          break;
      }

      try {
        await navigator.clipboard.writeText(content);
        setCopied(tab);
        setTimeout(() => setCopied(null), 2000);
      } catch (err) {
        console.error("Failed to copy:", err);
      }
    },
    [exportData]
  );

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay asChild>
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 bg-black/50 z-50" />
        </Dialog.Overlay>
        <Dialog.Content asChild>
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            transition={{ duration: 0.2 }}
            className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-50
                       w-[90vw] max-w-3xl max-h-[85vh]
                       bg-surface rounded-xl shadow-2xl overflow-hidden
                       flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-border">
              <Dialog.Title className="text-lg font-semibold text-text">Export Layout</Dialog.Title>
              <Dialog.Close asChild>
                <button className="p-2 text-text-muted hover:text-text rounded-lg hover:bg-surface-secondary transition-colors">
                  <Cross2Icon className="w-5 h-5" />
                </button>
              </Dialog.Close>
            </div>

            {/* Tabs */}
            <Tabs.Root value={activeTab} onValueChange={(v) => setActiveTab(v as TabValue)} className="flex-1 flex flex-col min-h-0">
              <Tabs.List className="flex gap-1 px-6 py-2 border-b border-border bg-surface-secondary/50">
                <Tabs.Trigger
                  value="html"
                  className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors
                             ${
                               activeTab === "html" ? "bg-primary text-white" : "text-text-muted hover:text-text hover:bg-surface-secondary"
                             }`}
                >
                  <FileTextIcon className="w-4 h-4" />
                  HTML
                </Tabs.Trigger>
                <Tabs.Trigger
                  value="css"
                  className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors
                             ${
                               activeTab === "css" ? "bg-primary text-white" : "text-text-muted hover:text-text hover:bg-surface-secondary"
                             }`}
                >
                  <CodeIcon className="w-4 h-4" />
                  CSS
                </Tabs.Trigger>
                <Tabs.Trigger
                  value="webcomponent"
                  className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors
                             ${
                               activeTab === "webcomponent"
                                 ? "bg-primary text-white"
                                 : "text-text-muted hover:text-text hover:bg-surface-secondary"
                             }`}
                >
                  <ComponentInstanceIcon className="w-4 h-4" />
                  Web Component
                </Tabs.Trigger>
              </Tabs.List>

              {/* Tab content */}
              <div className="flex-1 overflow-hidden flex flex-col min-h-0">
                <Tabs.Content value="html" className="flex-1 flex flex-col min-h-0 data-[state=inactive]:hidden">
                  <CodePreview code={exportData.html} language="html" onCopy={() => handleCopy("html")} copied={copied === "html"} />
                </Tabs.Content>
                <Tabs.Content value="css" className="flex-1 flex flex-col min-h-0 data-[state=inactive]:hidden">
                  <CodePreview code={exportData.css} language="css" onCopy={() => handleCopy("css")} copied={copied === "css"} />
                </Tabs.Content>
                <Tabs.Content value="webcomponent" className="flex-1 flex flex-col min-h-0 data-[state=inactive]:hidden">
                  <CodePreview
                    code={exportData.webComponentHtml}
                    language="html"
                    onCopy={() => handleCopy("webcomponent")}
                    copied={copied === "webcomponent"}
                  />
                </Tabs.Content>
              </div>
            </Tabs.Root>

            {/* Placeholders info */}
            <div className="px-6 py-4 border-t border-border bg-surface-secondary/30">
              <details className="group">
                <summary className="flex items-center gap-2 cursor-pointer text-sm text-text-muted hover:text-text">
                  <svg className="w-4 h-4 transition-transform group-open:rotate-90" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                  Available Placeholders
                </summary>
                <div className="mt-3 grid grid-cols-2 md:grid-cols-3 gap-2">
                  {availablePlaceholders.map((p) => (
                    <div key={p.key} className="flex items-center gap-2 text-xs">
                      <code className="px-1.5 py-0.5 bg-surface-secondary rounded text-primary font-mono">{p.key}</code>
                      <span className="text-text-muted truncate">{p.description}</span>
                    </div>
                  ))}
                </div>
              </details>
            </div>

            {/* Footer */}
            <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
              <Dialog.Close asChild>
                <button className="px-4 py-2 text-sm font-medium text-text-muted hover:text-text rounded-lg hover:bg-surface-secondary transition-colors">
                  Close
                </button>
              </Dialog.Close>
              <button
                onClick={() => handleCopy(activeTab)}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors"
              >
                {copied === activeTab ? (
                  <>
                    <CheckIcon className="w-4 h-4" />
                    Copied!
                  </>
                ) : (
                  <>
                    <CopyIcon className="w-4 h-4" />
                    Copy {activeTab.toUpperCase()}
                  </>
                )}
              </button>
            </div>
          </motion.div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

// Code preview component with syntax highlighting placeholder
interface CodePreviewProps {
  code: string;
  language: string;
  onCopy: () => void;
  copied: boolean;
}

function CodePreview({ code, language, onCopy, copied }: CodePreviewProps) {
  // Count lines for line numbers
  const lines = code.split("\n");

  return (
    <div className="flex-1 flex flex-col min-h-0">
      {/* Toolbar */}
      <div className="flex items-center justify-between px-4 py-2 bg-[#1e1e1e] border-b border-[#333]">
        <span className="text-xs text-gray-400 uppercase tracking-wider">{language}</span>
        <button
          onClick={onCopy}
          className="flex items-center gap-1.5 px-2 py-1 text-xs text-gray-400 hover:text-white rounded hover:bg-white/10 transition-colors"
        >
          {copied ? (
            <>
              <CheckIcon className="w-3.5 h-3.5" />
              Copied
            </>
          ) : (
            <>
              <CopyIcon className="w-3.5 h-3.5" />
              Copy
            </>
          )}
        </button>
      </div>

      {/* Code area */}
      <div className="flex-1 overflow-auto bg-[#1e1e1e]">
        <div className="flex min-h-full">
          {/* Line numbers */}
          <div className="flex-shrink-0 py-4 pr-4 text-right bg-[#252525] select-none">
            {lines.map((_, i) => (
              <div key={i} className="px-3 text-xs leading-6 text-gray-500 font-mono">
                {i + 1}
              </div>
            ))}
          </div>

          {/* Code content */}
          <pre className="flex-1 p-4 text-sm leading-6 text-gray-300 font-mono overflow-x-auto">
            <code>{code}</code>
          </pre>
        </div>
      </div>
    </div>
  );
}
