"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useInbox, useSdk, type InboxItem, type InboxKind, type InboxState } from "@lynkd/messaging-inbox-sdk";
import { Header } from "@/components/nav/Header";
import { Avatar, Chip } from "@/components/ui/primitives";
import { relativeTime } from "@/lib/format";
import clsx from "clsx";
import {
  AtSign,
  Heart,
  MessageSquare,
  Bookmark,
  LifeBuoy,
  CalendarClock,
  Bot,
  Reply,
  Check,
  Clock,
  Archive,
  ArrowRight,
} from "lucide-react";

const kindMeta: Record<InboxKind, { icon: typeof AtSign; label: string; tone: string }> = {
  NEEDS_REPLY: { icon: Reply, label: "Needs reply", tone: "text-accent" },
  MENTION: { icon: AtSign, label: "Mention", tone: "text-info" },
  REACTION: { icon: Heart, label: "Reaction", tone: "text-danger" },
  THREAD_REPLY: { icon: MessageSquare, label: "Thread", tone: "text-info" },
  SAVED: { icon: Bookmark, label: "Saved", tone: "text-warning" },
  APP: { icon: Bot, label: "App", tone: "text-muted" },
  SUPPORT_UPDATE: { icon: LifeBuoy, label: "Support", tone: "text-success" },
  MEETING_FOLLOWUP: { icon: CalendarClock, label: "Follow-up", tone: "text-info" },
};

const STATES: InboxState[] = ["OPEN", "SNOOZED", "DONE", "ARCHIVED"];

export function InboxView() {
  const { items, state, setState, loading, markDone, snooze, archive } = useInbox("OPEN");
  const [filter, setFilter] = useState<InboxKind | "ALL">("ALL");
  const shown = items.filter((i) => filter === "ALL" || i.kind === filter);

  const kinds: (InboxKind | "ALL")[] = ["ALL", "NEEDS_REPLY", "MENTION", "REACTION", "THREAD_REPLY", "SUPPORT_UPDATE", "SAVED"];

  return (
    <div className="flex min-w-0 flex-1 flex-col">
      <Header eyebrow="Workspace" title="Inbox" subtitle="Everything that needs your attention, in one queue" />

      {/* state tabs */}
      <div className="flex shrink-0 items-center gap-1 border-b border-border px-4 py-2">
        {STATES.map((s) => (
          <button
            key={s}
            onClick={() => setState(s)}
            className={clsx(
              "shrink-0 rounded-control px-3 py-1.5 text-[13px] font-semibold capitalize transition-colors",
              state === s ? "bg-accent-soft text-accent" : "text-muted hover:bg-hover hover:text-ink",
            )}
          >
            {s.toLowerCase()}
          </button>
        ))}
        <div className="ml-auto flex min-w-0 gap-1 overflow-x-auto no-scrollbar">
          {kinds.map((k) => (
            <button
              key={k}
              onClick={() => setFilter(k)}
              className={clsx(
                "shrink-0 whitespace-nowrap rounded-pill border px-2.5 py-1 text-[11.5px] font-medium transition-colors",
                filter === k ? "border-accent text-accent" : "border-border text-muted hover:text-ink",
              )}
            >
              {k === "ALL" ? "All" : kindMeta[k].label}
            </button>
          ))}
        </div>
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto p-4">
        {loading && <div className="py-10 text-center text-muted">Loading…</div>}
        {!loading && shown.length === 0 && (
          <div className="flex flex-col items-center gap-2 py-20 text-muted">
            <Check size={36} className="text-success" />
            <div className="text-[15px] font-semibold text-ink">You're all caught up</div>
            <div className="text-[13px]">Nothing in “{state.toLowerCase()}”.</div>
          </div>
        )}
        <div className="mx-auto max-w-3xl space-y-2">
          {shown.map((item) => (
            <InboxRow
              key={item.id}
              item={item}
              onDone={() => markDone(item.id)}
              onSnooze={() => snooze(item.id)}
              onArchive={() => archive(item.id)}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

function InboxRow({
  item,
  onDone,
  onSnooze,
  onArchive,
}: {
  item: InboxItem;
  onDone: () => void;
  onSnooze: () => void;
  onArchive: () => void;
}) {
  const { userById } = useSdk();
  const router = useRouter();
  const meta = kindMeta[item.kind];
  const actor = item.actorId ? userById(item.actorId) : undefined;

  return (
    <div className="group flex items-start gap-3 rounded-card border border-border bg-panel p-3.5 transition-colors hover:border-border-strong">
      <span className={clsx("mt-0.5 grid h-9 w-9 shrink-0 place-items-center rounded-control bg-hover", meta.tone)}>
        <meta.icon size={17} />
      </span>

      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-2">
          <span className="min-w-0 truncate text-[14px] font-semibold">{item.title}</span>
          {item.priority === "urgent" && <Chip tone="danger">urgent</Chip>}
          {item.priority === "high" && <Chip tone="warning">high</Chip>}
          <span className="ml-auto shrink-0 text-[11px] text-dim">{relativeTime(item.ts)}</span>
        </div>
        <div className="mt-0.5 truncate text-[13px] text-muted">{item.preview}</div>
        <div className="mt-2 flex items-center gap-2">
          {actor && (
            <span className="flex items-center gap-1.5 text-[11px] text-dim">
              <Avatar user={actor} size={16} showPresence={false} rounded="5px" /> {actor.name}
            </span>
          )}
          <Chip>{meta.label}</Chip>
          {item.dueAt && (
            <span className="flex items-center gap-1 text-[11px] text-info">
              <Clock size={11} /> due {relativeTime(item.dueAt)}
            </span>
          )}
        </div>
      </div>

      {/* actions — always visible on touch, hover/focus-reveal on desktop */}
      <div className="flex items-center gap-1 opacity-100 transition-opacity md:pointer-events-none md:opacity-0 md:group-hover:pointer-events-auto md:group-hover:opacity-100 md:group-focus-within:pointer-events-auto md:group-focus-within:opacity-100">
        <RowBtn title="Open" icon={ArrowRight} onClick={() => (item.channelId ? router.push(`/c/${item.channelId}`) : router.push("/support"))} />
        <RowBtn title="Snooze" icon={Clock} onClick={onSnooze} />
        <RowBtn title="Archive" icon={Archive} onClick={onArchive} />
        <RowBtn title="Mark done" icon={Check} accent onClick={onDone} />
      </div>
    </div>
  );
}

function RowBtn({
  title,
  icon: Icon,
  onClick,
  accent,
}: {
  title: string;
  icon: typeof Check;
  onClick: () => void;
  accent?: boolean;
}) {
  return (
    <button
      title={title}
      onClick={onClick}
      className={clsx(
        "grid h-8 w-8 place-items-center rounded-control border border-border transition-colors hover:bg-hover",
        accent ? "text-accent hover:border-accent" : "text-muted hover:text-ink",
      )}
    >
      <Icon size={15} />
    </button>
  );
}
