"use client";

// ═══════════════════════════════════════════════════════════════════
//  InviteModal — Zoom-like "Invite people" for a meeting.
//  Creates a PUBLIC invite (no passcode) and shows a shareable link
//  anyone can open, enter their name, and join — no login needed.
// ═══════════════════════════════════════════════════════════════════

import React, { useEffect, useState } from "react";
import { FiCopy, FiCheck, FiX, FiMail, FiLink } from "react-icons/fi";

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "";
const PUBLIC_ORIGIN =
  (typeof window !== "undefined" ? window.location.origin : "") || "https://crm.qrsyst.com";

interface Props {
  meetingId: number;
  meetingTitle?: string;
  roomCode?: string;
  getToken: () => string;
  onClose: () => void;
}

export default function InviteModal({ meetingId, meetingTitle, roomCode, getToken, onClose }: Props) {
  const [link, setLink] = useState("");
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState("");
  const [copied, setCopied] = useState(false);
  const [email, setEmail] = useState("");
  const [sending, setSending] = useState(false);
  const [sentMsg, setSentMsg] = useState("");

  // create a PUBLIC invite → get the shareable link
  const createPublicLink = async () => {
    setLoading(true); setErr("");
    try {
      const res = await fetch(`${API_BASE}/meetings/${meetingId}/invites`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}` },
        body: JSON.stringify({ scope: "PUBLIC", grant_role: "CLIENT" }),
      });
      if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b?.message || "Could not create invite"); }
      const data = await res.json();
      // backend returns { url, token, ... } — prefer a same-origin /j/<token> link
      const tok = data.token || data.url?.split("/j/")?.[1];
      const full = tok ? `${PUBLIC_ORIGIN}/j/${tok}` : data.url;
      setLink(full);
    } catch (e: any) { setErr(e?.message || "Failed to create link"); }
    finally { setLoading(false); }
  };

  useEffect(() => { createPublicLink(); /* eslint-disable-next-line */ }, []);

  const copy = () => { navigator.clipboard.writeText(link); setCopied(true); setTimeout(() => setCopied(false), 1600); };

  const sendEmail = async () => {
    if (!email.trim()) return;
    setSending(true); setSentMsg("");
    try {
      // create a VERIFIED invite to this email (server emails the link+passcode)
      const res = await fetch(`${API_BASE}/meetings/${meetingId}/invites`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}` },
        body: JSON.stringify({ scope: "PUBLIC", grant_role: "CLIENT", recipient_email: email.trim(), send_now: true, channel: "EMAIL" }),
      });
      if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b?.message || "Could not send"); }
      setSentMsg(`Invite sent to ${email.trim()}`);
      setEmail("");
    } catch (e: any) { setSentMsg(e?.message || "Could not send email"); }
    finally { setSending(false); }
  };

  return (
    <div style={s.overlay} onClick={onClose}>
      <div style={s.modal} onClick={(e) => e.stopPropagation()}>
        <div style={s.head}>
          <span>Invite people</span>
          <button style={s.x} onClick={onClose}><FiX size={18} /></button>
        </div>

        <div style={{ padding: 20 }}>
          <div style={s.meetingName}>{meetingTitle || "Meeting"}</div>
          {roomCode && <div style={s.code}>Meeting ID: <b>{roomCode}</b></div>}

          {/* shareable link */}
          <div style={s.label}><FiLink size={13} /> Share this link — anyone can join</div>
          {loading ? (
            <div style={s.linkBox}>Creating link…</div>
          ) : err ? (
            <div style={{ ...s.linkBox, color: "#dc2626" }}>{err} <button onClick={createPublicLink} style={s.retry}>Retry</button></div>
          ) : (
            <div style={s.linkRow}>
              <input readOnly value={link} style={s.linkInput} onFocus={(e) => e.target.select()} />
              <button style={s.copyBtn} onClick={copy}>{copied ? <FiCheck size={15} /> : <FiCopy size={15} />} {copied ? "Copied" : "Copy"}</button>
            </div>
          )}
          <div style={s.hint}>People who open this link just enter their name and join — no account needed.</div>

          {/* email invite */}
          <div style={{ ...s.label, marginTop: 20 }}><FiMail size={13} /> Or email an invite</div>
          <div style={s.linkRow}>
            <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="name@example.com" style={s.linkInput} type="email" onKeyDown={(e) => e.key === "Enter" && sendEmail()} />
            <button style={s.sendBtn} onClick={sendEmail} disabled={sending || !email.trim()}>{sending ? "Sending…" : "Send"}</button>
          </div>
          {sentMsg && <div style={s.sent}>{sentMsg}</div>}
        </div>
      </div>
    </div>
  );
}

const s: Record<string, React.CSSProperties> = {
  overlay: { position: "fixed", inset: 0, background: "rgba(17,24,39,0.55)", backdropFilter: "blur(3px)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 2000, padding: 20 },
  modal: { width: "100%", maxWidth: 460, background: "#fff", borderRadius: 16, overflow: "hidden", fontFamily: "system-ui, sans-serif", boxShadow: "0 20px 50px rgba(0,0,0,0.3)" },
  head: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 20px", borderBottom: "1px solid #eee", fontSize: 16, fontWeight: 700, color: "#111827" },
  x: { border: "none", background: "#f3f4f6", width: 32, height: 32, borderRadius: 8, cursor: "pointer", color: "#6b7280" },
  meetingName: { fontSize: 15, fontWeight: 700, color: "#1a1033", marginBottom: 4 },
  code: { fontSize: 12, color: "#6b7280", marginBottom: 18 },
  label: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 700, color: "#6d28d9", marginBottom: 8 },
  linkBox: { padding: "11px 13px", background: "#f8fafc", border: "1px solid #e5e7eb", borderRadius: 10, fontSize: 13, color: "#6b7280" },
  linkRow: { display: "flex", gap: 8 },
  linkInput: { flex: 1, padding: "11px 13px", border: "1.5px solid #e5e7eb", borderRadius: 10, fontSize: 13, color: "#111827", outline: "none", background: "#f8fafc" },
  copyBtn: { display: "inline-flex", alignItems: "center", gap: 6, padding: "0 16px", border: "none", borderRadius: 10, background: "linear-gradient(135deg,#7c3aed,#4a0080)", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap" },
  sendBtn: { padding: "0 18px", border: "none", borderRadius: 10, background: "#4a0080", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer" },
  retry: { marginLeft: 8, border: "none", background: "none", color: "#6d28d9", fontWeight: 700, cursor: "pointer" },
  hint: { fontSize: 11.5, color: "#9ca3af", marginTop: 7, lineHeight: 1.5 },
  sent: { fontSize: 12, color: "#0f766e", marginTop: 8 },
};
