/**
 * MailViewModal
 * Full email view with:
 *  - Dark-themed iframe body
 *  - ESC / click-outside to close
 *  - Save inline images (via JSON endpoint) or attachments (re-fetched from IMAP)
 *    to customer's Nextcloud media folder
 *
 * Props:
 *   open        – boolean
 *   onClose     – () => void
 *   entry       – CommInDB
 *   customer    – customer object | null
 *   onReply     – (defaultTo: string) => void
 */
import { useRef, useEffect, useState } from "react";

const SUBFOLDERS = ["received_media", "documents", "sent_media", "photos"];

// ── Add Customer mini modal ────────────────────────────────────────────────────
function AddCustomerModal({ email, onClose, onCreated }) {
  const [name, setName] = useState("");
  const [surname, setSurname] = useState("");
  const [organization, setOrganization] = useState("");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");

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

  const handleSave = async () => {
    if (!name.trim()) { setErr("Please enter a first name."); return; }
    setSaving(true);
    setErr("");
    try {
      const token = localStorage.getItem("access_token");
      const body = {
        name: name.trim(),
        surname: surname.trim(),
        organization: organization.trim(),
        language: "en",
        contacts: [{ type: "email", label: "Email", value: email, primary: true }],
      };
      const resp = await fetch("/api/crm/customers", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!resp.ok) {
        const e = await resp.json().catch(() => ({}));
        throw new Error(e.detail || `Error ${resp.status}`);
      }
      const data = await resp.json();
      onCreated(data);
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  };

  const inputStyle = {
    backgroundColor: "var(--bg-input)",
    borderColor: "var(--border-primary)",
    color: "var(--text-primary)",
    border: "1px solid",
    borderRadius: 6,
    padding: "6px 10px",
    fontSize: 13,
    width: "100%",
    outline: "none",
  };

  return (
    <div
      style={{
        position: "fixed", inset: 0, zIndex: 1100,
        backgroundColor: "rgba(0,0,0,0.6)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}
      onClick={onClose}
    >
      <div
        style={{
          backgroundColor: "var(--bg-card)",
          border: "1px solid var(--border-primary)",
          borderRadius: 10,
          padding: 24,
          width: 400,
          boxShadow: "0 12px 40px rgba(0,0,0,0.5)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <h3 className="text-sm font-semibold mb-1" style={{ color: "var(--text-heading)" }}>
          Add Customer
        </h3>
        <p className="text-xs mb-4" style={{ color: "var(--text-muted)" }}>
          Adding <strong style={{ color: "var(--accent)" }}>{email}</strong> as a new customer.
        </p>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
          <div>
            <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>First Name *</label>
            <input style={inputStyle} value={name} onChange={(e) => setName(e.target.value)} placeholder="First name" autoFocus />
          </div>
          <div>
            <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>Last Name</label>
            <input style={inputStyle} value={surname} onChange={(e) => setSurname(e.target.value)} placeholder="Last name" />
          </div>
        </div>

        <div className="mb-3">
          <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>Organization</label>
          <input style={inputStyle} value={organization} onChange={(e) => setOrganization(e.target.value)} placeholder="Church, school, etc." />
        </div>

        <div className="mb-4">
          <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>Email</label>
          <input style={{ ...inputStyle, opacity: 0.6, cursor: "not-allowed" }} value={email} readOnly />
        </div>

        {err && <p className="text-xs mb-3" style={{ color: "var(--danger-text)" }}>{err}</p>}

        <div className="flex justify-end gap-2">
          <button
            onClick={onClose}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card)" }}
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90"
            style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: saving ? 0.7 : 1 }}
          >
            {saving ? "Saving..." : "Add Customer"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Save-to-DB mini modal ─────────────────────────────────────────────────────
function SaveModal({ item, commId, onClose }) {
  // item: { type: "inline"|"attachment", filename, mime_type, dataUri?, attachmentIndex? }
  const [filename, setFilename] = useState(item.filename || "file");
  const [subfolder, setSubfolder] = useState("received_media");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");
  const [done, setDone] = useState(false);

  // ESC to close
  useEffect(() => {
    const handler = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [onClose]);

  const handleSave = async () => {
    if (!filename.trim()) { setErr("Please enter a filename."); return; }
    setSaving(true);
    setErr("");
    try {
      const token = localStorage.getItem("access_token");

      if (item.type === "inline") {
        // JSON body — avoids form multipart size limits for large data URIs
        const resp = await fetch(`/api/crm/comms/email/${commId}/save-inline`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            data_uri: item.dataUri,
            filename: filename.trim(),
            subfolder,
            mime_type: item.mime_type,
          }),
        });
        if (!resp.ok) {
          const e = await resp.json().catch(() => ({}));
          throw new Error(e.detail || `Error ${resp.status}`);
        }
      } else {
        // Attachment: re-fetched from IMAP server-side
        const fd = new FormData();
        fd.append("filename", filename.trim());
        fd.append("subfolder", subfolder);
        const resp = await fetch(
          `/api/crm/comms/email/${commId}/save-attachment/${item.attachmentIndex}`,
          {
            method: "POST",
            headers: { Authorization: `Bearer ${token}` },
            body: fd,
          }
        );
        if (!resp.ok) {
          const e = await resp.json().catch(() => ({}));
          throw new Error(e.detail || `Error ${resp.status}`);
        }
      }

      setDone(true);
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  };

  const inputStyle = {
    backgroundColor: "var(--bg-input)",
    borderColor: "var(--border-primary)",
    color: "var(--text-primary)",
    border: "1px solid",
    borderRadius: 6,
    padding: "6px 10px",
    fontSize: 13,
    width: "100%",
    outline: "none",
  };

  return (
    <div
      style={{
        position: "fixed", inset: 0, zIndex: 1100,
        backgroundColor: "rgba(0,0,0,0.6)",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}
      // Do NOT close on backdrop click — user must use Cancel
    >
      <div
        style={{
          backgroundColor: "var(--bg-card)",
          border: "1px solid var(--border-primary)",
          borderRadius: 10,
          padding: 24,
          width: 380,
          boxShadow: "0 12px 40px rgba(0,0,0,0.5)",
        }}
      >
        {done ? (
          <div className="text-center py-4">
            <div style={{ fontSize: 32, marginBottom: 8 }}>✅</div>
            <p className="text-sm font-medium" style={{ color: "var(--text-heading)" }}>Saved successfully</p>
            <p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
              File stored in <strong>{subfolder}/</strong>
            </p>
            <button
              onClick={onClose}
              className="mt-4 px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              Done
            </button>
          </div>
        ) : (
          <>
            <h3 className="text-sm font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
              Save to Customer Media
            </h3>

            <div className="mb-3">
              <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>
                Filename
              </label>
              <input style={inputStyle} value={filename} onChange={(e) => setFilename(e.target.value)} />
            </div>

            <div className="mb-4">
              <label className="text-xs font-medium block mb-1" style={{ color: "var(--text-secondary)" }}>
                Folder
              </label>
              <select value={subfolder} onChange={(e) => setSubfolder(e.target.value)} style={inputStyle}>
                {SUBFOLDERS.map((f) => (
                  <option key={f} value={f}>{f}</option>
                ))}
              </select>
            </div>

            {err && (
              <p className="text-xs mb-3" style={{ color: "var(--danger-text)" }}>{err}</p>
            )}

            <div className="flex justify-end gap-2">
              <button
                onClick={onClose}
                className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
                style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card)" }}
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90"
                style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: saving ? 0.7 : 1 }}
              >
                {saving ? "Saving..." : "Save"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Main modal ────────────────────────────────────────────────────────────────
export default function MailViewModal({ open, onClose, entry, customer, onReply, onCustomerAdded }) {
  const iframeRef = useRef(null);
  const [saveItem, setSaveItem] = useState(null);
  const [inlineImages, setInlineImages] = useState([]);
  const [bodyDark, setBodyDark] = useState(true);
  const [showAddCustomer, setShowAddCustomer] = useState(false);
  const [addedCustomer, setAddedCustomer] = useState(null);

  // ESC to close
  useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);

  // Extract inline images from HTML body
  useEffect(() => {
    if (!entry?.body_html) { setInlineImages([]); return; }
    const parser = new DOMParser();
    const doc = parser.parseFromString(entry.body_html, "text/html");
    const imgs = Array.from(doc.querySelectorAll("img[src^='data:']"));
    const found = imgs.map((img, i) => {
      const src = img.getAttribute("src");
      const mimeMatch = src.match(/^data:([^;]+);/);
      const mime = mimeMatch ? mimeMatch[1] : "image/png";
      const ext = mime.split("/")[1] || "png";
      return {
        type: "inline",
        filename: `inline-image-${i + 1}.${ext}`,
        mime_type: mime,
        dataUri: src,
      };
    });
    setInlineImages(found);
  }, [entry]);

  // Reset dark mode when new entry opens
  useEffect(() => { setBodyDark(true); }, [entry]);

  // Reset addedCustomer when a new entry opens
  useEffect(() => { setAddedCustomer(null); }, [entry]);

  if (!open || !entry) return null;

  const isInbound = entry.direction === "inbound";
  const fromLabel = isInbound
    ? (entry.from_addr || customer?.name || "Unknown Sender")
    : "Me";
  const toLabel = Array.isArray(entry.to_addrs)
    ? entry.to_addrs.join(", ")
    : (entry.to_addrs || "");

  const hasHtml = !!entry.body_html && entry.body_html.trim().length > 0;
  const attachments = Array.isArray(entry.attachments) ? entry.attachments : [];
  const canSave = !!entry.customer_id;

  const handleReply = () => {
    const replyTo = isInbound ? (entry.from_addr || "") : toLabel;
    if (onReply) onReply(replyTo, entry.mail_account || "");
    onClose();
  };

  const iframeDoc = hasHtml
    ? entry.body_html
    : `<pre style="font-family:inherit;white-space:pre-wrap;margin:0">${(entry.body || "").replace(/</g, "&lt;")}</pre>`;

  return (
    <>
      {/* Backdrop — click outside closes */}
      <div
        style={{
          position: "fixed", inset: 0, zIndex: 1000,
          backgroundColor: "rgba(0,0,0,0.55)",
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: 60,
        }}
        onClick={onClose}
      >
        {/* Modal box */}
        <div
          style={{
            backgroundColor: "var(--bg-card)",
            border: "1px solid var(--border-primary)",
            borderRadius: 12,
            width: "100%",
            height: "100%",
            display: "flex",
            flexDirection: "column",
            overflow: "hidden",
            boxShadow: "0 20px 60px rgba(0,0,0,0.4)",
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div
            className="flex items-center justify-between px-5 py-4"
            style={{ borderBottom: "1px solid var(--border-primary)", flexShrink: 0 }}
          >
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 className="text-base font-semibold truncate" style={{ color: "var(--text-heading)" }}>
                {entry.subject || <span style={{ color: "var(--text-muted)", fontStyle: "italic" }}>(no subject)</span>}
              </h2>
              <p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
                {entry.occurred_at ? new Date(entry.occurred_at).toLocaleString() : ""}
              </p>
            </div>
            <button
              type="button"
              onClick={onClose}
              className="cursor-pointer hover:opacity-70 ml-4 flex-shrink-0"
              style={{ color: "var(--text-muted)", background: "none", border: "none", fontSize: 22, lineHeight: 1 }}
            >
              ×
            </button>
          </div>

          {/* Meta row */}
          <div className="px-5 py-3" style={{ borderBottom: "1px solid var(--border-secondary)", backgroundColor: "var(--bg-primary)", flexShrink: 0 }}>
            <div className="flex flex-wrap items-center gap-y-1 text-xs" style={{ gap: "0 0" }}>
              <span style={{ paddingRight: 12 }}>
                <span style={{ color: "var(--text-muted)" }}>From: </span>
                <span style={{ color: "var(--text-primary)" }}>{fromLabel}</span>
                {isInbound && entry.from_addr && customer && (
                  <span style={{ color: "var(--text-muted)", marginLeft: 4 }}>({entry.from_addr})</span>
                )}
              </span>
              {toLabel && (
                <>
                  <span style={{ color: "var(--border-primary)", paddingRight: 12 }}>|</span>
                  <span style={{ paddingRight: 12 }}>
                    <span style={{ color: "var(--text-muted)" }}>To: </span>
                    <span style={{ color: "var(--text-primary)" }}>{toLabel}</span>
                  </span>
                </>
              )}
              {customer && (
                <>
                  <span style={{ color: "var(--border-primary)", paddingRight: 12 }}>|</span>
                  <span style={{ paddingRight: 12 }}>
                    <span style={{ color: "var(--text-muted)" }}>Customer: </span>
                    <span style={{ color: "var(--accent)" }}>{customer.name}</span>
                    {customer.organization && (
                      <span style={{ color: "var(--text-muted)" }}> · {customer.organization}</span>
                    )}
                  </span>
                </>
              )}
              <span style={{ color: "var(--border-primary)", paddingRight: 12 }}>|</span>
              <span
                className="px-2 py-0.5 rounded-full capitalize"
                style={{
                  backgroundColor: isInbound ? "var(--danger-bg)" : "#dcfce7",
                  color: isInbound ? "var(--danger-text)" : "#166534",
                }}
              >
                {entry.direction}
              </span>
            </div>
          </div>

          {/* Body — dark iframe with dark/light toggle */}
          <div className="flex-1 overflow-hidden" style={{ position: "relative" }}>
            {/* Dark / Light toggle */}
            <div style={{ position: "absolute", top: 8, right: 20, zIndex: 10 }}>
              <button
                type="button"
                onClick={() => setBodyDark((v) => !v)}
                title={bodyDark ? "Switch to light mode" : "Switch to dark mode"}
                style={{
                  padding: "4px 10px", fontSize: 11, borderRadius: 6, cursor: "pointer",
                  border: "1px solid rgba(128,128,128,0.4)",
                  backgroundColor: bodyDark ? "rgba(0,0,0,0.55)" : "rgba(255,255,255,0.7)",
                  color: bodyDark ? "#e0e0e0" : "#333",
                  backdropFilter: "blur(4px)",
                  transition: "all 0.15s",
                }}
              >
                {bodyDark ? "☀ Light" : "🌙 Dark"}
              </button>
            </div>
            <iframe
              ref={iframeRef}
              sandbox="allow-same-origin allow-popups"
              referrerPolicy="no-referrer"
              style={{ width: "100%", height: "100%", border: "none", display: "block" }}
              srcDoc={`<!DOCTYPE html><html><head>
                <meta charset="utf-8">
                <style>
                  html, body { margin: 0; padding: 0; background: ${bodyDark ? "#1a1a1a" : "#ffffff"}; color: ${bodyDark ? "#e0e0e0" : "#1a1a1a"}; }
                  body { padding: 16px 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; line-height: 1.6; }
                  img { max-width: 100%; height: auto; display: inline-block; }
                  pre { white-space: pre-wrap; word-break: break-word; }
                  a { color: ${bodyDark ? "#60a5fa" : "#1d4ed8"}; }
                  blockquote { border-left: 3px solid ${bodyDark ? "#404040" : "#d1d5db"}; margin: 8px 0; padding-left: 12px; color: ${bodyDark ? "#9ca3af" : "#6b7280"}; }
                  table { color: ${bodyDark ? "#e0e0e0" : "#1a1a1a"}; }
                  * { box-sizing: border-box; }
                </style>
              </head><body>${iframeDoc}</body></html>`}
            />
          </div>

          {/* Inline images */}
          {inlineImages.length > 0 && (
            <div
              className="px-5 py-3 flex flex-wrap gap-2"
              style={{ borderTop: "1px solid var(--border-secondary)", backgroundColor: "var(--bg-primary)", flexShrink: 0 }}
            >
              <span className="text-xs font-medium w-full mb-1" style={{ color: "var(--text-secondary)" }}>
                Inline Images ({inlineImages.length})
              </span>
              {inlineImages.map((img, i) => (
                <div
                  key={i}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs"
                  style={{ backgroundColor: "var(--bg-card)", border: "1px solid var(--border-primary)", color: "var(--text-primary)" }}
                >
                  <span>🖼️</span>
                  <span className="truncate" style={{ maxWidth: 160 }}>{img.filename}</span>
                  {canSave && (
                    <button
                      type="button"
                      onClick={() => setSaveItem(img)}
                      className="cursor-pointer hover:opacity-80 text-xs px-2 py-0.5 rounded"
                      style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", border: "none", marginLeft: 4 }}
                    >
                      Save
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}

          {/* Attachments */}
          {attachments.length > 0 && (
            <div
              className="px-5 py-3 flex flex-wrap gap-2"
              style={{ borderTop: "1px solid var(--border-secondary)", backgroundColor: "var(--bg-primary)", flexShrink: 0 }}
            >
              <span className="text-xs font-medium w-full mb-1" style={{ color: "var(--text-secondary)" }}>
                Attachments ({attachments.length})
              </span>
              {attachments.map((a, i) => {
                const name = a.filename || a.name || "file";
                const ct = a.content_type || "";
                const kb = a.size ? ` · ${Math.ceil(a.size / 1024)} KB` : "";
                const icon = ct.startsWith("image/") ? "🖼️" : ct === "application/pdf" ? "📑" : ct.startsWith("video/") ? "🎬" : "📎";
                return (
                  <div
                    key={i}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs"
                    style={{ backgroundColor: "var(--bg-card)", border: "1px solid var(--border-primary)", color: "var(--text-primary)" }}
                  >
                    <span>{icon}</span>
                    <span className="truncate" style={{ maxWidth: 200 }}>{name}{kb}</span>
                    {canSave && (
                      <button
                        type="button"
                        onClick={() => setSaveItem({ type: "attachment", filename: name, mime_type: ct, attachmentIndex: i })}
                        className="cursor-pointer hover:opacity-80 text-xs px-2 py-0.5 rounded"
                        style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", border: "none", marginLeft: 4 }}
                      >
                        Save
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          )}

          {/* Unknown sender banner */}
          {isInbound && !customer && !addedCustomer && entry.from_addr && (
            <div
              className="px-5 py-3 flex items-center gap-2 text-xs"
              style={{ borderTop: "1px solid var(--border-secondary)", backgroundColor: "var(--bg-primary)", flexShrink: 0 }}
            >
              <span style={{ color: "var(--text-muted)" }}>
                <strong style={{ color: "var(--text-secondary)" }}>{entry.from_addr}</strong> is not in your Customer&apos;s list.{" "}
                <button
                  type="button"
                  onClick={() => setShowAddCustomer(true)}
                  className="cursor-pointer hover:underline"
                  style={{ background: "none", border: "none", padding: 0, color: "var(--accent)", fontWeight: 500, fontSize: "inherit" }}
                >
                  Click here to add them.
                </button>
              </span>
            </div>
          )}
          {isInbound && addedCustomer && (
            <div
              className="px-5 py-3 flex items-center gap-2 text-xs"
              style={{ borderTop: "1px solid var(--border-secondary)", backgroundColor: "var(--bg-primary)", flexShrink: 0 }}
            >
              <span style={{ color: "var(--success-text, #16a34a)" }}>
                ✓ <strong>{addedCustomer.name}</strong> has been added as a customer.
              </span>
            </div>
          )}

          {/* Footer */}
          <div
            className="flex items-center justify-end gap-3 px-5 py-4"
            style={{ borderTop: "1px solid var(--border-primary)", flexShrink: 0 }}
          >
            <button
              type="button"
              onClick={onClose}
              className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
              style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card)" }}
            >
              Close
            </button>
            {onReply && (
              <button
                type="button"
                onClick={handleReply}
                className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
                style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card)" }}
              >
                ↩ Reply
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Save sub-modal */}
      {saveItem && (
        <SaveModal
          item={saveItem}
          commId={entry.id}
          onClose={() => setSaveItem(null)}
        />
      )}

      {/* Add Customer sub-modal */}
      {showAddCustomer && entry?.from_addr && (
        <AddCustomerModal
          email={entry.from_addr}
          onClose={() => setShowAddCustomer(false)}
          onCreated={(newCustomer) => {
            setAddedCustomer(newCustomer);
            setShowAddCustomer(false);
            if (onCustomerAdded) onCustomerAdded(newCustomer);
          }}
        />
      )}
    </>
  );
}
