import { useState, useEffect, useCallback, useRef } from "react";
import { Link } from "react-router-dom";
import api from "../../api/client";
import MailViewModal from "../components/MailViewModal";
import ComposeEmailModal from "../components/ComposeEmailModal";
import { CommTypeIconBadge, CommDirectionIcon } from "../components/CommIcons";

// Display labels for transport types - always lowercase
const TYPE_LABELS = {
  email:     "e-mail",
  whatsapp:  "whatsapp",
  call:      "phonecall",
  sms:       "sms",
  note:      "note",
  in_person: "in person",
};

const COMMS_TYPES = ["email", "whatsapp", "call", "sms", "note", "in_person"];
const DIRECTIONS  = ["inbound", "outbound", "internal"];
const COMM_DATE_FMT = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric" });
const COMM_TIME_FMT = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", hour12: true });

function formatCommDateTime(value) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "";
  return `${COMM_DATE_FMT.format(d)} · ${COMM_TIME_FMT.format(d).toLowerCase()}`;
}

const selectStyle = {
  backgroundColor: "var(--bg-input)",
  borderColor: "var(--border-primary)",
  color: "var(--text-primary)",
  fontSize: 13,
  padding: "6px 10px",
  borderRadius: 6,
  border: "1px solid",
  cursor: "pointer",
};

// Customer search mini modal (replaces the giant dropdown)
function CustomerPickerModal({ open, onClose, customers, value, onChange }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) { setQ(""); setTimeout(() => inputRef.current?.focus(), 60); }
  }, [open]);

  // 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]);

  if (!open) return null;

  const lower = q.trim().toLowerCase();
  const filtered = customers.filter((c) =>
    !lower ||
    (c.name || "").toLowerCase().includes(lower) ||
    (c.surname || "").toLowerCase().includes(lower) ||
    (c.organization || "").toLowerCase().includes(lower) ||
    (c.contacts || []).some((ct) => (ct.value || "").toLowerCase().includes(lower))
  );

  return (
    <div
      style={{ position: "fixed", inset: 0, zIndex: 500, backgroundColor: "rgba(0,0,0,0.45)", display: "flex", alignItems: "center", justifyContent: "center" }}
      onClick={onClose}
    >
      <div
        style={{ backgroundColor: "var(--bg-card)", border: "1px solid var(--border-primary)", borderRadius: 10, width: 380, maxHeight: 460, display: "flex", flexDirection: "column", boxShadow: "0 16px 48px rgba(0,0,0,0.35)", overflow: "hidden" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border-secondary)" }}>
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search customer..."
            style={{ width: "100%", padding: "7px 10px", fontSize: 13, borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "var(--bg-input)", color: "var(--text-primary)", outline: "none" }}
          />
        </div>
        <div style={{ overflowY: "auto", flex: 1 }}>
          {/* All customers option */}
          <div
            onClick={() => { onChange(""); onClose(); }}
            style={{ padding: "9px 14px", fontSize: 13, cursor: "pointer", color: value === "" ? "var(--accent)" : "var(--text-primary)", backgroundColor: value === "" ? "color-mix(in srgb, var(--accent) 8%, var(--bg-card))" : "transparent", fontWeight: value === "" ? 600 : 400 }}
            onMouseEnter={(e) => { if (value !== "") e.currentTarget.style.backgroundColor = "var(--bg-card-hover)"; }}
            onMouseLeave={(e) => { if (value !== "") e.currentTarget.style.backgroundColor = "transparent"; }}
          >
            All customers
          </div>
          {filtered.map((c) => (
            <div
              key={c.id}
              onClick={() => { onChange(c.id); onClose(); }}
              style={{ padding: "9px 14px", fontSize: 13, cursor: "pointer", color: value === c.id ? "var(--accent)" : "var(--text-primary)", backgroundColor: value === c.id ? "color-mix(in srgb, var(--accent) 8%, var(--bg-card))" : "transparent" }}
              onMouseEnter={(e) => { if (value !== c.id) e.currentTarget.style.backgroundColor = "var(--bg-card-hover)"; }}
              onMouseLeave={(e) => { if (value !== c.id) e.currentTarget.style.backgroundColor = value === c.id ? "color-mix(in srgb, var(--accent) 8%, var(--bg-card))" : "transparent"; }}
            >
              <div style={{ fontWeight: 500 }}>{c.name}{c.surname ? ` ${c.surname}` : ""}</div>
              {c.organization && <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 1 }}>{c.organization}</div>}
            </div>
          ))}
          {filtered.length === 0 && q && (
            <div style={{ padding: "16px 14px", textAlign: "center", fontSize: 13, color: "var(--text-muted)" }}>No customers found</div>
          )}
        </div>
      </div>
    </div>
  );
}

export default function CommsPage() {
  const [entries, setEntries]           = useState([]);
  const [customers, setCustomers]       = useState({});
  const [loading, setLoading]           = useState(true);
  const [error, setError]               = useState("");
  const [typeFilter, setTypeFilter]     = useState("");
  const [dirFilter, setDirFilter]       = useState("");
  const [custFilter, setCustFilter]     = useState("");
  const [expandedId, setExpandedId]     = useState(null); // only 1 at a time
  const [syncing, setSyncing]           = useState(false);
  const [syncResult, setSyncResult]     = useState(null);
  const [custPickerOpen, setCustPickerOpen] = useState(false);

  // Modals
  const [viewEntry, setViewEntry]       = useState(null);
  const [composeOpen, setComposeOpen]   = useState(false);
  const [composeTo, setComposeTo]       = useState("");
  const [composeFromAccount, setComposeFromAccount] = useState("");

  const loadAll = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams({ limit: 200 });
      if (typeFilter) params.set("type", typeFilter);
      if (dirFilter)  params.set("direction", dirFilter);
      const [commsData, custsData] = await Promise.all([
        api.get(`/crm/comms/all?${params}`),
        api.get("/crm/customers"),
      ]);
      setEntries(commsData.entries || []);
      const map = {};
      for (const c of custsData.customers || []) map[c.id] = c;
      setCustomers(map);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [typeFilter, dirFilter]);

  useEffect(() => { loadAll(); }, [loadAll]);

  const syncEmails = async () => {
    setSyncing(true);
    setSyncResult(null);
    try {
      const data = await api.post("/crm/comms/email/sync", {});
      setSyncResult(data);
      await loadAll();
    } catch (err) {
      setSyncResult({ error: err.message });
    } finally {
      setSyncing(false);
    }
  };

  // Toggle expand — only one at a time
  const toggleExpand = (id) =>
    setExpandedId((prev) => (prev === id ? null : id));

  const openReply = (entry) => {
    const toAddr = entry.direction === "inbound"
      ? (entry.from_addr || "")
      : (Array.isArray(entry.to_addrs) ? entry.to_addrs[0] : "");
    setViewEntry(null);
    setComposeTo(toAddr);
    setComposeOpen(true);
  };

  const filtered = custFilter
    ? entries.filter((e) => e.customer_id === custFilter)
    : entries;
  const sortedFiltered = [...filtered].sort((a, b) => {
    const ta = Date.parse(a?.occurred_at || a?.created_at || "") || 0;
    const tb = Date.parse(b?.occurred_at || b?.created_at || "") || 0;
    if (tb !== ta) return tb - ta;
    return String(b?.id || "").localeCompare(String(a?.id || ""));
  });

  const customerOptions = Object.values(customers).sort((a, b) =>
    (a.name || "").localeCompare(b.name || "")
  );

  const selectedCustomerLabel = custFilter && customers[custFilter]
    ? customers[custFilter].name + (customers[custFilter].organization ? ` — ${customers[custFilter].organization}` : "")
    : "All customers";

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-5">
        <div>
          <h1 className="text-xl font-bold" style={{ color: "var(--text-heading)" }}>Activity Log</h1>
          <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
            All customer communications across all channels
          </p>
        </div>
        <div className="flex items-center gap-2">
          {syncResult && (
            <span className="text-xs" style={{ color: syncResult.error ? "var(--danger-text)" : "var(--success-text)" }}>
              {syncResult.error
                ? syncResult.error
                : `${syncResult.new_count} new email${syncResult.new_count !== 1 ? "s" : ""}`}
            </span>
          )}
          <button
            onClick={syncEmails}
            disabled={syncing || loading}
            title="Connect to mail server and download new emails into the log"
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid", borderColor: "var(--border-primary)", color: "var(--text-secondary)", opacity: (syncing || loading) ? 0.6 : 1 }}
          >
            {syncing ? "Syncing..." : "Sync Emails"}
          </button>
          <button
            onClick={loadAll}
            disabled={loading}
            title="Reload from local database"
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ border: "1px solid", borderColor: "var(--border-primary)", color: "var(--text-secondary)", opacity: loading ? 0.6 : 1 }}
          >
            Refresh
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 mb-5">
        <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)} style={selectStyle}>
          <option value="">All types</option>
          {COMMS_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABELS[t] || t}</option>)}
        </select>
        <select value={dirFilter} onChange={(e) => setDirFilter(e.target.value)} style={selectStyle}>
          <option value="">All directions</option>
          {DIRECTIONS.map((d) => <option key={d} value={d}>{d}</option>)}
        </select>

        {/* Customer picker button */}
        <button
          type="button"
          onClick={() => setCustPickerOpen(true)}
          style={{
            ...selectStyle,
            minWidth: 180,
            textAlign: "left",
            color: custFilter ? "var(--accent)" : "var(--text-primary)",
            fontWeight: custFilter ? 600 : 400,
          }}
        >
          {selectedCustomerLabel} ▾
        </button>

        {(typeFilter || dirFilter || custFilter) && (
          <button
            onClick={() => { setTypeFilter(""); setDirFilter(""); setCustFilter(""); }}
            className="px-3 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-80"
            style={{ color: "var(--danger-text)", backgroundColor: "var(--danger-bg)", borderRadius: 6 }}
          >
            Clear filters
          </button>
        )}
      </div>

      {error && (
        <div className="text-sm rounded-md p-3 mb-4 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-12" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : sortedFiltered.length === 0 ? (
        <div className="rounded-lg p-10 text-center text-sm border" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}>
          No communications found.
        </div>
      ) : (
        <div>
          <div className="text-xs mb-3" style={{ color: "var(--text-muted)" }}>
            {sortedFiltered.length} entr{sortedFiltered.length !== 1 ? "ies" : "y"}
          </div>

          <div style={{ position: "relative" }}>
            {/* Connector line */}
            <div style={{
              position: "absolute", left: 19, top: 12, bottom: 12,
              width: 2, backgroundColor: "var(--border-secondary)", zIndex: 0,
            }} />

            <div className="space-y-2">
              {sortedFiltered.map((entry) => {
                const customer = customers[entry.customer_id];
                const isExpanded = expandedId === entry.id;
                const isEmail = entry.type === "email";

                return (
                  <div key={entry.id} style={{ position: "relative", paddingLeft: 44 }}>
                    {/* Type icon marker */}
                    <div style={{ position: "absolute", left: 8, top: 11, zIndex: 1 }}>
                      <CommTypeIconBadge type={entry.type} />
                    </div>

                    <div
                      className="rounded-lg border"
                      style={{
                        backgroundColor: "var(--bg-card)",
                        borderColor: "var(--border-primary)",
                        cursor: entry.body ? "pointer" : "default",
                      }}
                      onClick={() => entry.body && toggleExpand(entry.id)}
                    >
                      {/* Entry header */}
                      <div className="flex items-center gap-2 px-4 py-3 flex-wrap">
                        <CommDirectionIcon direction={entry.direction} />
                        {customer ? (
                          <Link
                            to={`/crm/customers/${entry.customer_id}`}
                            className="text-xs font-medium hover:underline"
                            style={{ color: "var(--accent)" }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            {customer.name}
                            {customer.organization ? ` · ${customer.organization}` : ""}
                          </Link>
                        ) : (
                          <span className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>
                            {entry.from_addr || entry.customer_id || "—"}
                          </span>
                        )}

                        {entry.subject && (
                          <span className="text-sm font-medium truncate" style={{ color: "var(--text-heading)", maxWidth: 280 }}>
                            {entry.subject}
                          </span>
                        )}

                        <div className="ml-auto flex items-center gap-2">
                        {/* Full View button (for email entries) */}
                        {isEmail && (
                          <button
                            type="button"
                            onClick={(e) => { e.stopPropagation(); setViewEntry(entry); }}
                            className="text-xs px-2 py-0.5 rounded cursor-pointer hover:opacity-80 flex-shrink-0"
                            style={{ border: "1px solid var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-primary)" }}
                          >
                            Full View
                          </button>
                        )}
                        <span className="text-xs flex-shrink-0" style={{ color: "var(--text-muted)" }}>
                          {formatCommDateTime(entry.occurred_at)}
                        </span>

                        {entry.body && (
                          <span className="text-xs flex-shrink-0" style={{ color: "var(--text-muted)" }}>
                            {isExpanded ? "▲" : "▼"}
                          </span>
                        )}
                        </div>
                      </div>

                      {/* Body */}
                      {entry.body && (
                        <div className="pb-3" style={{ paddingLeft: 16, paddingRight: 16 }}>
                          <div style={{ borderTop: "1px solid var(--border-secondary)", marginLeft: 0, marginRight: 0 }} />
                          <p
                            className="text-sm mt-2"
                            style={{
                              color: "var(--text-primary)",
                              display: "-webkit-box",
                              WebkitLineClamp: isExpanded ? "unset" : 2,
                              WebkitBoxOrient: "vertical",
                              overflow: isExpanded ? "visible" : "hidden",
                              whiteSpace: "pre-wrap",
                            }}
                          >
                            {entry.body}
                          </p>
                        </div>
                      )}

                      {/* Footer: logged_by + attachments + Quick Reply */}
                      {(entry.logged_by || (entry.attachments?.length > 0) || (isExpanded && isEmail)) && (
                        <div className="px-4 pb-3 flex items-center gap-3 flex-wrap">
                          {entry.logged_by && (
                            <span className="text-xs" style={{ color: "var(--text-muted)" }}>
                              by {entry.logged_by}
                            </span>
                          )}
                          {entry.attachments?.length > 0 && (
                            <span className="text-xs" style={{ color: "var(--text-muted)" }}>
                              📎 {entry.attachments.length} attachment{entry.attachments.length !== 1 ? "s" : ""}
                            </span>
                          )}
                          {isExpanded && isEmail && (
                            <button
                              type="button"
                              onClick={(e) => { e.stopPropagation(); openReply(entry); }}
                              className="ml-auto text-xs px-2 py-1 rounded-md cursor-pointer hover:opacity-90"
                              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", border: "none" }}
                            >
                              ↩ Quick Reply
                            </button>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}

      {/* Customer Picker Modal */}
      <CustomerPickerModal
        open={custPickerOpen}
        onClose={() => setCustPickerOpen(false)}
        customers={customerOptions}
        value={custFilter}
        onChange={setCustFilter}
      />

      {/* Mail View Modal */}
      <MailViewModal
        open={!!viewEntry}
        onClose={() => setViewEntry(null)}
        entry={viewEntry}
        customerName={viewEntry ? customers[viewEntry.customer_id]?.name : null}
        onReply={(toAddr, sourceAccount) => {
          setViewEntry(null);
          setComposeTo(toAddr);
          setComposeFromAccount(sourceAccount || "");
          setComposeOpen(true);
        }}
      />

      {/* Compose Modal */}
      <ComposeEmailModal
        open={composeOpen}
        onClose={() => { setComposeOpen(false); setComposeFromAccount(""); }}
        defaultTo={composeTo}
        defaultFromAccount={composeFromAccount}
        requireFromAccount={true}
        onSent={() => loadAll()}
      />
    </div>
  );
}
