"use client";

// ============================================================
// Inbox — the ONE unified communication surface. It lists everything
// IIOS surfaces for you (mentions, needs-reply, system alerts, support
// updates, …) AND the mail behind them: click an item tied to a thread
// and its conversation opens on the right to read + reply. Compose new
// mail from here too. Items come from crm.inbox.*; threads from crm.mail.*.
// ============================================================

import { useEffect, useState } from "react";
import { Btn, Icon, PageHead, Pill, useToast } from "./ui";
import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api";
import { MailReader, NewMailModal } from "./mail";

const KIND_LABEL: Record<string, string> = {
  MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval",
  SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner",
};
const FILTERS: { value: InboxState; label: string }[] = [
  { value: "OPEN", label: "Open" }, { value: "SNOOZED", label: "Snoozed" }, { value: "DONE", label: "Done" }, { value: "ARCHIVED", label: "Archived" },
];

export function Inbox() {
  const [filter, setFilter] = useState<InboxState>("OPEN");
  const inbox = useInboxData(filter);
  const toast = useToast();
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [newOpen, setNewOpen] = useState(false);

  useEffect(() => {
    if ((!selectedId || !inbox.items.some((i) => i.id === selectedId)) && inbox.items[0]) setSelectedId(inbox.items[0].id);
  }, [inbox.items, selectedId]);

  const selected = inbox.items.find((i) => i.id === selectedId) ?? null;

  return (
    <div className="view">
      <PageHead
        eyebrow="Communication" title="Inbox" subtitle="Mentions, messages, system alerts and mail — all in one place" icon="bell"
        actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New mail</Btn>}
      />
      {!inbox.live && (
        <div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
          Demo mode — running on mock data. It goes live once the Shell + be-crm are connected.
        </div>
      )}

      <div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
        {FILTERS.map((f) => (
          <Btn key={f.value} variant={filter === f.value ? "primary" : "outline"} onClick={() => setFilter(f.value)}>{f.label}</Btn>
        ))}
      </div>

      <div className="card" style={{ display: "flex", height: 620, padding: 0, overflow: "hidden" }}>
        {/* Left — the unified item list */}
        <aside style={{ width: 360, borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--panel)" }}>
          {inbox.loading && <div style={{ padding: 20, color: "var(--muted)" }}>Loading…</div>}
          {!inbox.loading && inbox.items.length === 0 && (
            <div style={{ padding: 28, color: "var(--muted)", textAlign: "center" }}>Nothing here — you&apos;re all caught up 🎉</div>
          )}
          {inbox.items.map((it) => (
            <ItemRow key={it.id} it={it} active={it.id === selectedId} onClick={() => setSelectedId(it.id)} />
          ))}
        </aside>

        {/* Right — read the mail behind the item, or the item detail */}
        <section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "var(--bg)" }}>
          {selected ? (
            <Detail
              it={selected}
              onError={(m) => toast.push({ tone: "error", title: "Failed", desc: m })}
              onDone={() => inbox.transition(selected.id, "DONE")}
              onSnooze={() => inbox.transition(selected.id, "SNOOZED")}
              onArchive={() => inbox.transition(selected.id, "ARCHIVED")}
            />
          ) : (
            <div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
              <Icon name="bell" size={38} /><p>Select an item to read</p>
            </div>
          )}
        </section>
      </div>

      <NewMailModal
        open={newOpen} onClose={() => setNewOpen(false)}
        onSent={() => { setNewOpen(false); inbox.refetch(); toast.push({ tone: "success", title: "Sent" }); }}
        onError={(m) => toast.push({ tone: "error", title: "Couldn't send", desc: m })}
      />
    </div>
  );
}

function ItemRow({ it, active, onClick }: { it: UiInboxItem; active: boolean; onClick: () => void }) {
  const isMention = it.kind === "MENTION";
  return (
    <button
      onClick={onClick}
      style={{
        display: "flex", gap: 10, alignItems: "flex-start", width: "100%", textAlign: "left",
        padding: "13px 16px", border: "none", borderBottom: "1px solid var(--border)", cursor: "pointer",
        background: active ? "var(--panel-2)" : "transparent", color: "var(--text)",
      }}
    >
      <span style={{ marginTop: 2, color: isMention ? "var(--orange)" : "var(--text-2)", flexShrink: 0 }}>
        <Icon name={it.threadId ? "chat" : isMention ? "chat" : "bell"} size={18} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
          <Pill tone={isMention ? "warn" : "muted"}>{KIND_LABEL[it.kind] ?? it.kind}</Pill>
          <span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.title}</span>
        </div>
        {it.summary && <div style={{ color: "var(--muted)", fontSize: 12.5, marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.summary}</div>}
      </div>
      {it.state !== "OPEN" && <Pill tone="muted">{it.state.toLowerCase()}</Pill>}
    </button>
  );
}

function Detail({ it, onError, onDone, onSnooze, onArchive }: {
  it: UiInboxItem; onError: (m: string) => void; onDone: () => void; onSnooze: () => void; onArchive: () => void;
}) {
  return (
    <>
      {/* Item actions bar (works for every item, threaded or not) */}
      {it.state === "OPEN" && (
        <div style={{ display: "flex", gap: 6, padding: "10px 16px", borderBottom: "1px solid var(--border)", justifyContent: "flex-end" }}>
          <Btn variant="ghost" icon="clock" onClick={onSnooze}>Snooze</Btn>
          <Btn variant="outline" icon="check" onClick={onDone}>Done</Btn>
          <Btn variant="ghost" icon="x" onClick={onArchive}>Archive</Btn>
        </div>
      )}

      {it.threadId ? (
        // A message/mail item → open the conversation to read + reply.
        <div style={{ flex: 1, minHeight: 0 }}>
          <MailReader threadId={it.threadId} subject={it.title} onError={onError} />
        </div>
      ) : (
        // A non-threaded item (e.g. a system alert) → show its detail.
        <div style={{ flex: 1, overflowY: "auto", padding: 22 }}>
          <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 6 }}>{it.title}</div>
          {it.summary && <div style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.55 }}>{it.summary}</div>}
        </div>
      )}
    </>
  );
}
