"use client";

import clsx from "clsx";
import { Search } from "lucide-react";
import { Select, Skeleton } from "@/components/ui/kit";
import { initials } from "@/lib/format";
import type { ConversationSummary } from "@/lib/types";

export type Tab = "all" | "mine" | "unassigned";

export function shortTime(iso: string | null) {
  if (!iso) return "";
  const d = new Date(iso);
  const now = new Date();
  if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString("en-IN", { hour: "numeric", minute: "2-digit" });
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (d.toDateString() === yesterday.toDateString()) return "Yesterday";
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short" });
}

export function ConversationList({
  items,
  counts,
  tab,
  onTab,
  status,
  onStatus,
  search,
  onSearch,
  selectedId,
  onSelect,
}: {
  items: ConversationSummary[] | null;
  counts: Record<string, number> | null;
  tab: Tab;
  onTab: (t: Tab) => void;
  status: "open" | "closed";
  onStatus: (s: "open" | "closed") => void;
  search: string;
  onSearch: (s: string) => void;
  selectedId: number | null;
  onSelect: (id: number) => void;
}) {
  const tabs: [Tab, string][] = [
    ["all", "All"],
    ["mine", "Mine"],
    ["unassigned", "Unassigned"],
  ];
  return (
    <div className="flex h-full min-h-0 flex-col border-r border-line bg-white">
      <div className="space-y-2.5 border-b border-line p-3">
        <div className="flex items-center justify-between gap-2">
          <h1 className="text-lg font-semibold text-ink">Inbox</h1>
          <Select aria-label="Conversation status" className="!h-8 w-auto text-[13px]" value={status} onChange={(e) => onStatus(e.target.value as "open" | "closed")}>
            <option value="open">Open</option>
            <option value="closed">Closed</option>
          </Select>
        </div>
        <div role="tablist" aria-label="Conversations" className="grid grid-cols-3 gap-1 rounded-lg bg-paper p-1">
          {tabs.map(([key, label]) => (
            <button
              key={key}
              role="tab"
              aria-selected={tab === key}
              onClick={() => onTab(key)}
              className={clsx("flex items-center justify-center gap-1.5 rounded-md py-1.5 text-[13px] font-medium", tab === key ? "bg-white text-ink shadow-sm" : "text-muted hover:text-text")}
            >
              {label}
              {counts && counts[`${key}_unread`] > 0 && <span className="tabular rounded-full bg-mint px-1.5 text-[11px] font-semibold text-ink">{counts[`${key}_unread`]}</span>}
            </button>
          ))}
        </div>
        <label className="relative block">
          <span className="sr-only">Search conversations</span>
          <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
          <input
            value={search}
            onChange={(e) => onSearch(e.target.value)}
            placeholder="Search name, number or message"
            className="h-9 w-full rounded-md border border-line pl-9 pr-3 text-sm focus:border-teal focus:outline-none focus:ring-2 focus:ring-teal/15"
          />
        </label>
      </div>
      <ul className="min-h-0 flex-1 overflow-y-auto" aria-label="Conversation list">
        {!items &&
          Array.from({ length: 6 }).map((_, i) => (
            <li key={i} className="flex gap-3 border-b border-line p-3">
              <Skeleton className="size-10 rounded-full" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-4 w-1/2" />
                <Skeleton className="h-3 w-3/4" />
              </div>
            </li>
          ))}
        {items?.length === 0 && (
          <li className="px-6 py-12 text-center text-sm text-muted">
            {search ? "No conversations match your search." : tab === "mine" ? "No conversations are assigned to you." : status === "closed" ? "No closed conversations." : "No conversations yet. They appear here when customers message your WhatsApp number."}
          </li>
        )}
        {items?.map((c) => (
          <li key={c.id}>
            <button
              onClick={() => onSelect(c.id)}
              aria-current={selectedId === c.id ? "true" : undefined}
              className={clsx("flex w-full gap-3 border-b border-line px-3 py-3 text-left transition-colors", selectedId === c.id ? "bg-teal-soft/70" : "hover:bg-paper")}
            >
              <span className={clsx("grid size-10 shrink-0 place-items-center rounded-full text-sm font-semibold", c.unread_count ? "bg-teal text-white" : "bg-teal-soft text-teal")}>{initials(c.contact.name || "?")}</span>
              <span className="min-w-0 flex-1">
                <span className="flex items-baseline gap-2">
                  <span className={clsx("flex-1 truncate", c.unread_count ? "font-semibold text-ink" : "font-medium")}>{c.contact.name}</span>
                  <span className={clsx("shrink-0 text-xs", c.unread_count ? "font-medium text-teal" : "text-muted")}>{shortTime(c.last_message_at)}</span>
                </span>
                <span className="mt-0.5 flex items-center gap-2">
                  <span className={clsx("flex-1 truncate text-[13px]", c.unread_count ? "text-text" : "text-muted")}>
                    {c.last_message_direction === "out" && <span className="text-muted">You: </span>}
                    {c.last_message_preview || "No messages yet"}
                  </span>
                  {c.unread_count > 0 && <span className="tabular grid min-w-5 place-items-center rounded-full bg-mint px-1 text-[11px] font-semibold text-ink">{c.unread_count}</span>}
                </span>
                <span className="mt-1 flex items-center gap-2 text-[11.5px] text-muted">
                  {c.assigned_user ? <span className="truncate">{c.assigned_user.name}</span> : <span className="text-amber">Unassigned</span>}
                  {!c.window.open && <span>Window closed</span>}
                </span>
              </span>
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
