import { useMemo, useState } from "react";
import {
  MessageSquare,
  Archive,
  Lock,
  X,
  ArrowRight,
  CircleDot,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

export type Thread = {
  id: string;
  room: string;
  seq: number;
  parent_seq: number;
  title: string;
  created_by: { id: string; display_name: string; username: string };
  archived: boolean;
  locked: boolean;
  last_message_at: string | null;
  last_message_preview?: string | null;
  created_at: string;
};

type Props = {
  threads: Thread[];
  onSelect?: (thread: Thread) => void;
  onClose?: () => void;
};

function formatTime(iso: string) {
  const d = new Date(iso);
  const now = new Date();
  const diffMs = now.getTime() - d.getTime();
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return "now";
  if (diffMin < 60) return `${diffMin}m`;
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h`;
  return d.toLocaleDateString([], { month: "short", day: "numeric" });
}

function ThreadStatusDot({
  thread,
}: {
  thread: Thread;
}) {
  if (thread.locked) {
    return (
      <span className="flex items-center gap-1 rounded-full bg-primary/[0.05] px-1.5 py-[1px] text-[10px] font-medium text-primary/50">
        <Lock className="size-2.5" />
        Resolved
      </span>
    );
  }
  if (thread.archived) {
    return (
      <span className="flex items-center gap-1 rounded-full bg-muted/40 px-1.5 py-[1px] text-[10px] font-medium text-muted-foreground/40">
        <Archive className="size-2.5" />
        Archived
      </span>
    );
  }
  return (
    <span className="flex items-center gap-1 rounded-full bg-emerald-500/[0.06] px-1.5 py-[1px] text-[10px] font-medium text-emerald-600/70">
      <CircleDot className="size-2.5" />
      Active
    </span>
  );
}

export default function ThreadSidebar({
  threads,
  onSelect,
  onClose,
}: Props) {
  const [filter, setFilter] = useState<"all" | "active" | "resolved">("all");

  const filtered = threads.filter((t) => {
    if (filter === "active") return !t.archived && !t.locked;
    if (filter === "resolved") return t.locked || t.archived;
    return true;
  });

  const counts = useMemo(() => {
    return {
      all: threads.length,
      active: threads.filter((t) => !t.archived && !t.locked).length,
      resolved: threads.filter((t) => t.locked || t.archived).length,
    };
  }, [threads]);

  return (
    <aside className="flex h-full w-full flex-col bg-card">
      {/* Header */}
      <div className="flex h-[52px] shrink-0 items-center justify-between border-b border-border/40 px-4">
        <div className="flex items-center gap-2">
          <span className="grid size-8 place-items-center rounded-lg bg-gradient-to-br from-primary/10 to-primary/[0.03] ring-1 ring-primary/[0.08]">
            <MessageSquare className="size-[15px] text-primary/60" />
          </span>
          <h3 className="text-[15px] font-semibold text-foreground tracking-tight">
            Threads
          </h3>
          <span className="text-[11px] font-medium text-muted-foreground/30 tabular-nums">
            {threads.length}
          </span>
        </div>
        {onClose && (
          <Button
            className="size-8 cursor-pointer rounded-lg text-muted-foreground/30 hover:bg-accent/50 hover:text-foreground"
            onClick={onClose}
            size="icon"
            variant="ghost"
          >
            <X className="size-4" />
          </Button>
        )}
      </div>

      {/* Filter tabs with counts */}
      <div className="flex gap-0.5 border-b border-border/30 px-3 py-2">
        {([
          { key: "all", label: "All" },
          { key: "active", label: "Active" },
          { key: "resolved", label: "Resolved" },
        ] as const).map((f) => {
          const isActive = filter === f.key;
          const count =
            f.key === "all"
              ? counts.all
              : f.key === "active"
                ? counts.active
                : counts.resolved;
          return (
            <button
              className={cn(
                "relative flex-1 cursor-pointer rounded-md px-2 py-1.5 text-[11px] font-medium transition-[background-color,border-color,color,opacity,box-shadow,transform] duration-150",
                isActive
                  ? "text-primary"
                  : "text-muted-foreground/40 hover:text-muted-foreground/70",
              )}
              key={f.key}
              onClick={() => setFilter(f.key)}
              type="button"
            >
              <span className="flex items-center justify-center gap-1.5">
                {f.label}
                <span
                  className={cn(
                    "text-[10px] tabular-nums transition-colors",
                    isActive
                      ? "text-primary/50"
                      : "text-muted-foreground/20",
                  )}
                >
                  {count}
                </span>
              </span>
              {isActive && (
                <span className="absolute inset-x-2 -bottom-[2px] h-[2px] rounded-full bg-primary/60" />
              )}
            </button>
          );
        })}
      </div>

      {/* Thread list */}
      <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
        {filtered.length === 0 && (
          <div className="flex flex-col items-center justify-center py-20">
            <div className="grid size-12 place-items-center rounded-2xl bg-muted/20 ring-1 ring-border/20">
              <MessageSquare className="size-5 text-muted-foreground/20" />
            </div>
            <p className="mt-3 text-sm font-medium text-muted-foreground/40">
              No threads yet
            </p>
            <p className="mt-1 text-[11px] text-muted-foreground/30">
              Start a thread from any message
            </p>
          </div>
        )}
        {filtered.map((thread) => {
          const creatorName =
            thread.created_by.display_name || thread.created_by.username;
          const initials = creatorName
            .split(" ")
            .map((w) => w[0])
            .join("")
            .slice(0, 2)
            .toUpperCase();

          return (
            <button
              className="group flex w-full cursor-pointer gap-3 border-b border-border/[0.06] px-4 py-3 text-left transition-[background-color,border-color,color,opacity,box-shadow,transform] duration-150 hover:bg-accent/[0.03] active:bg-accent/[0.06]"
              key={thread.id}
              onClick={() => onSelect?.(thread)}
              type="button"
            >
              {/* Avatar */}
              <div className="mt-0.5 shrink-0">
                <div className="grid size-9 place-items-center rounded-full bg-gradient-to-br from-muted-foreground/10 to-muted-foreground/5 text-xs font-semibold text-muted-foreground/50">
                  {initials}
                </div>
              </div>

              {/* Content */}
              <div className="min-w-0 flex-1">
                {/* Title + status */}
                <div className="flex items-center gap-2">
                  <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
                    {thread.title || `Thread #${thread.seq}`}
                  </span>
                  <ThreadStatusDot thread={thread} />
                </div>

                {/* Author + time */}
                <div className="mt-0.5 flex items-center gap-1.5">
                  <span className="text-[11px] text-muted-foreground/40">
                    {creatorName}
                  </span>
                  <span className="text-[10px] text-muted-foreground/20">
                    ·
                  </span>
                  <span className="text-[11px] text-muted-foreground/30">
                    {thread.last_message_at
                      ? formatTime(thread.last_message_at)
                      : formatTime(thread.created_at)}
                  </span>
                </div>

                {/* Preview */}
                {thread.last_message_preview && (
                  <p className="mt-1 line-clamp-2 text-[12px] leading-relaxed text-muted-foreground/35 group-hover:text-muted-foreground/50 transition-colors">
                    {thread.last_message_preview}
                  </p>
                )}
              </div>

              {/* Arrow on hover */}
              <div className="flex shrink-0 items-center self-center opacity-0 transition-opacity duration-150 group-hover:opacity-100">
                <ArrowRight className="size-4 text-muted-foreground/30" />
              </div>
            </button>
          );
        })}
      </div>
    </aside>
  );
}
