import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { motion, AnimatePresence } from "framer-motion";
import { FaCopy, FaCheck, FaExternalLinkAlt, FaTimes } from "react-icons/fa";
import { useTranslation } from "react-i18next";

interface Props {
  opened: boolean;
  onClose: () => void;
}

function CredRow({ label, value }: { label: string; value: string }) {
  const { t } = useTranslation("home");
  const [copied, setCopied] = useState(false);

  const copy = () => {
    navigator.clipboard.writeText(value).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "0.65rem 1rem", borderRadius: "0.6rem",
      background: "color-mix(in hsl, var(--c-background), transparent 15%)",
      border: "1px solid color-mix(in hsl, var(--c-lines), transparent 70%)",
    }}>
      <div>
        <span style={{ fontSize: "0.7rem", color: "color-mix(in hsl, var(--c-text), transparent 50%)", textTransform: "uppercase", letterSpacing: "0.08em", display: "block", marginBottom: "0.15rem" }}>
          {label}
        </span>
        <code style={{ fontSize: "1rem", fontWeight: 700, color: "var(--c-text)", fontFamily: "monospace" }}>
          {value}
        </code>
      </div>
      <button
        onClick={copy}
        title={copied ? t("demoModal.copied") : t("demoModal.copy")}
        style={{
          background: copied ? "color-mix(in hsl, var(--c-other), transparent 70%)" : "color-mix(in hsl, var(--c-background-light), transparent 30%)",
          border: "1px solid color-mix(in hsl, var(--c-lines), transparent 60%)",
          borderRadius: "0.5rem",
          padding: "0.35em 0.6em",
          color: copied ? "var(--c-other)" : "color-mix(in hsl, var(--c-text), transparent 30%)",
          cursor: "pointer",
          fontSize: "0.85rem",
          transition: "all 0.2s ease",
        }}
      >
        {copied ? <FaCheck /> : <FaCopy />}
      </button>
    </div>
  );
}

export default function DemoModal({ opened, onClose }: Props) {
  const { t } = useTranslation("home");

  useEffect(() => {
    if (!opened) return;
    const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [opened, onClose]);

  useEffect(() => {
    document.body.style.overflow = opened ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [opened]);

  return createPortal(
    <AnimatePresence>
      {opened && (
        <>
          {/* Backdrop */}
          <motion.div
            key="backdrop"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            onClick={onClose}
            style={{
              position: "fixed", inset: 0, zIndex: 9000,
              background: "rgba(3,29,68,0.78)",
              backdropFilter: "blur(8px)",
              WebkitBackdropFilter: "blur(8px)",
            }}
          />

          {/* Panel */}
          <motion.div
            key="modal"
            initial={{ opacity: 0, scale: 0.9, y: 24 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.92, y: 10 }}
            transition={{ duration: 0.25, ease: "easeOut" }}
            style={{
              position: "fixed",
              top: "50%", left: "50%",
              transform: "translate(-50%, -50%)",
              zIndex: 9001,
              width: "min(92vw, 420px)",
              background: "var(--c-background-light)",
              border: "1px solid color-mix(in hsl, var(--c-lines), transparent 60%)",
              borderRadius: "1.25rem",
              boxShadow: "0 24px 64px rgba(0,0,0,0.6)",
              overflow: "hidden",
            }}
          >
            {/* Header */}
            <div style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "1.1rem 1.4rem",
              borderBottom: "1px solid color-mix(in hsl, var(--c-lines), transparent 70%)",
            }}>
              <span style={{ fontWeight: 800, fontSize: "1.05rem" }}>{t("demoModal.title")}</span>
              <button
                onClick={onClose}
                aria-label={t("demoModal.close")}
                style={{
                  background: "none", border: "none",
                  color: "color-mix(in hsl, var(--c-text), transparent 40%)",
                  cursor: "pointer", fontSize: "1rem", padding: "0.25em",
                  borderRadius: "0.4rem", display: "flex",
                  transition: "color 0.15s ease",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.color = "var(--c-text)")}
                onMouseLeave={(e) => (e.currentTarget.style.color = "color-mix(in hsl, var(--c-text), transparent 40%)")}
              >
                <FaTimes />
              </button>
            </div>

            {/* Body */}
            <div style={{ padding: "1.4rem", display: "flex", flexDirection: "column", gap: "1rem" }}>
              <p style={{ margin: 0, color: "color-mix(in hsl, var(--c-text), transparent 30%)", fontSize: "0.88rem", lineHeight: 1.65 }}>
                {t("demoModal.description")}
              </p>

              <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                <CredRow label={t("demoModal.usernameLabel")} value="vontorCZ" />
                <CredRow label={t("demoModal.passwordLabel")} value="VontorCZ1234" />
              </div>

              <div style={{
                padding: "0.7rem 0.9rem", borderRadius: "0.6rem",
                background: "color-mix(in hsl, var(--c-other), transparent 87%)",
                border: "1px solid color-mix(in hsl, var(--c-other), transparent 58%)",
                fontSize: "0.8rem", color: "var(--c-other)",
                display: "flex", gap: "0.5rem", alignItems: "flex-start",
              }}>
                <span style={{ flexShrink: 0 }}>ℹ️</span>
                <span>{t("demoModal.notice")}</span>
              </div>

              <a
                href="/admin"
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  gap: "0.5rem", padding: "0.75em 1.5em", borderRadius: "9999px",
                  background: "linear-gradient(135deg, var(--c-other), color-mix(in hsl, var(--c-other), var(--c-boxes) 50%))",
                  color: "#031D44", fontWeight: 700, fontSize: "0.88rem", textDecoration: "none",
                  transition: "transform 0.2s ease, box-shadow 0.2s ease",
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = "scale(1.03)";
                  e.currentTarget.style.boxShadow = "0 0 1.2rem color-mix(in hsl, var(--c-other), transparent 45%)";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = "scale(1)";
                  e.currentTarget.style.boxShadow = "none";
                }}
              >
                {t("demoModal.openAdmin")} <FaExternalLinkAlt style={{ fontSize: "0.75rem" }} />
              </a>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>,
    document.body,
  );
}
