"use client";
import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Search, X, Pin, Archive, Trash2, MoreVertical, CheckCheck } from "lucide-react";
import { useMessaging } from "@/lib/MessagingContext";
import type { Conversation } from "./types";

const TABS = [
  { key: "all", label: "All" },
  { key: "buying", label: "Buying" },
  { key: "selling", label: "Selling" },
  { key: "unread", label: "Unread" },
  { key: "archived", label: "Archived" },
];

function formatTime(iso: string) {
  const d = new Date(iso);
  const now = new Date("2026-06-26T12:00:00Z");
  const diffMs = now.getTime() - d.getTime();
  const diffDays = Math.floor(diffMs / 86400000);
  if (diffDays === 0) {
    return d.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", hour12: true });
  }
  if (diffDays === 1) return "Yesterday";
  if (diffDays < 7) return d.toLocaleDateString("en-IN", { weekday: "short" });
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short" });
}

function statusColor(status: string) {
  if (status === "sold") return "bg-red-500/20 text-red-400 border-red-500/30";
  if (status === "reserved") return "bg-yellow-500/20 text-yellow-400 border-yellow-500/30";
  return "bg-green-500/20 text-green-400 border-green-500/30";
}

interface CardProps {
  conv: Conversation;
  isSelected: boolean;
  onSelect: () => void;
}

function ConversationCard({ conv, isSelected, onSelect }: CardProps) {
  const { archiveConversation, deleteConversation } = useMessaging();
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, x: -40 }}
      transition={{ type: "spring", stiffness: 320, damping: 30 }}
      className={`relative flex items-start gap-3 px-4 py-3 cursor-pointer transition-colors select-none ${
        isSelected
          ? "bg-[var(--accent)]/10 border-l-2 border-[var(--accent)]"
          : "hover:bg-[var(--card)] border-l-2 border-transparent"
      }`}
      onClick={onSelect}
    >
      {/* Avatar */}
      <div className="relative shrink-0">
        <img
          src={conv.otherUserAvatar}
          alt={conv.otherUserName}
          className="w-12 h-12 rounded-full object-cover"
        />
        {conv.otherUserIsOnline && (
          <span className="absolute bottom-0 right-0 w-3 h-3 rounded-full bg-green-500 border-2 border-[var(--bg)]" />
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2 mb-0.5">
          <div className="flex items-center gap-1.5 min-w-0">
            {conv.isPinned && <Pin size={10} className="text-[var(--accent)] shrink-0" />}
            <span className="text-sm font-semibold text-[var(--text-primary)] truncate">
              {conv.otherUserName}
            </span>
            {conv.otherUserVerified && (
              <span className="shrink-0 text-[9px] bg-[var(--accent)]/15 text-[var(--accent)] px-1 rounded font-medium">
                ✓
              </span>
            )}
          </div>
          <div className="flex items-center gap-1 shrink-0">
            <span className="text-[10px] text-[var(--text-muted)]">
              {formatTime(conv.lastMessageTime)}
            </span>
            <button
              className="opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-[var(--card)] text-[var(--text-muted)]"
              onClick={(e) => {
                e.stopPropagation();
                setMenuOpen(!menuOpen);
              }}
            >
              <MoreVertical size={12} />
            </button>
          </div>
        </div>

        {/* Listing mini-chip */}
        <div className="flex items-center gap-1.5 mb-1">
          <img
            src={conv.listingImage}
            alt=""
            className="w-4 h-4 rounded object-cover shrink-0 opacity-70"
          />
          <span className="text-[10px] text-[var(--text-muted)] truncate">{conv.listingTitle}</span>
          <span
            className={`shrink-0 text-[9px] px-1.5 py-0.5 rounded-full border font-medium ${statusColor(conv.listingStatus)}`}
          >
            {conv.listingStatus}
          </span>
        </div>

        {/* Last message */}
        <div className="flex items-center justify-between">
          <p
            className={`text-xs truncate ${
              conv.unreadCount > 0
                ? "text-[var(--text-primary)] font-medium"
                : "text-[var(--text-muted)]"
            }`}
          >
            {conv.lastMessage}
          </p>
          <div className="flex items-center gap-1 shrink-0 ml-2">
            {conv.unreadCount > 0 ? (
              <span className="min-w-[18px] h-[18px] flex items-center justify-center rounded-full bg-[var(--accent)] text-white text-[10px] font-bold px-1">
                {conv.unreadCount}
              </span>
            ) : (
              <CheckCheck size={12} className="text-[var(--accent)] opacity-60" />
            )}
          </div>
        </div>
      </div>

      {/* Context menu */}
      <AnimatePresence>
        {menuOpen && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9, y: -4 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: -4 }}
            transition={{ duration: 0.12 }}
            className="absolute right-4 top-10 z-30 rounded-xl overflow-hidden shadow-xl border border-[var(--border)]"
            style={{ background: "var(--card)", minWidth: 160 }}
            onClick={(e) => e.stopPropagation()}
          >
            <button
              className="w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--text-primary)] hover:bg-[var(--bg)] transition-colors"
              onClick={() => { archiveConversation(conv.id); setMenuOpen(false); }}
            >
              <Archive size={13} />
              {conv.isArchived ? "Unarchive" : "Archive"}
            </button>
            <button
              className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-400 hover:bg-red-500/10 transition-colors"
              onClick={() => { deleteConversation(conv.id); setMenuOpen(false); }}
            >
              <Trash2 size={13} />
              Delete
            </button>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

interface Props {
  onSelectMobile?: () => void;
}

export function ConversationList({ onSelectMobile }: Props) {
  const { conversations, activeTab, setActiveTab, selectedConversationId, selectConversation, totalUnread } =
    useMessaging();
  const [search, setSearch] = useState("");

  const filtered = useMemo(() => {
    let list = conversations;
    if (activeTab === "buying") list = list.filter((c) => c.myRole === "buyer" && !c.isArchived);
    else if (activeTab === "selling") list = list.filter((c) => c.myRole === "seller" && !c.isArchived);
    else if (activeTab === "unread") list = list.filter((c) => c.unreadCount > 0);
    else if (activeTab === "archived") list = list.filter((c) => c.isArchived);
    else list = list.filter((c) => !c.isArchived);

    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(
        (c) =>
          c.otherUserName.toLowerCase().includes(q) ||
          c.listingTitle.toLowerCase().includes(q) ||
          c.lastMessage.toLowerCase().includes(q)
      );
    }

    return [...list].sort((a, b) => {
      if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
      return new Date(b.lastMessageTime).getTime() - new Date(a.lastMessageTime).getTime();
    });
  }, [conversations, activeTab, search]);

  return (
    <div className="flex flex-col h-full" style={{ background: "var(--bg)" }}>
      {/* Header */}
      <div className="px-4 pt-4 pb-2 border-b border-[var(--border)]">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-bold text-[var(--text-primary)]">
            Messages
          </h2>
          {totalUnread > 0 && (
            <span className="text-xs bg-[var(--accent)] text-white rounded-full px-2 py-0.5 font-bold">
              {totalUnread} new
            </span>
          )}
        </div>
        {/* Search */}
        <div
          className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm"
          style={{ background: "var(--card)", border: "1px solid var(--border)" }}
        >
          <Search size={14} className="text-[var(--text-muted)] shrink-0" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search conversations…"
            className="flex-1 bg-transparent outline-none text-[var(--text-primary)] placeholder:text-[var(--text-muted)] text-sm"
          />
          {search && (
            <button onClick={() => setSearch("")}>
              <X size={13} className="text-[var(--text-muted)]" />
            </button>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 px-3 py-2 overflow-x-auto no-scrollbar border-b border-[var(--border)]">
        {TABS.map((tab) => {
          const count =
            tab.key === "unread"
              ? conversations.filter((c) => c.unreadCount > 0).length
              : tab.key === "archived"
              ? conversations.filter((c) => c.isArchived).length
              : tab.key === "buying"
              ? conversations.filter((c) => c.myRole === "buyer" && !c.isArchived).length
              : tab.key === "selling"
              ? conversations.filter((c) => c.myRole === "seller" && !c.isArchived).length
              : conversations.filter((c) => !c.isArchived).length;

          return (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className="relative shrink-0 px-3 py-1 rounded-full text-xs font-medium transition-colors"
              style={{
                background: activeTab === tab.key ? "var(--accent)" : "var(--card)",
                color: activeTab === tab.key ? "#fff" : "var(--text-muted)",
              }}
            >
              {tab.label}
              {count > 0 && activeTab !== tab.key && (
                <span className="ml-1 text-[9px] opacity-70">({count})</span>
              )}
            </button>
          );
        })}
      </div>

      {/* List */}
      <div className="flex-1 overflow-y-auto group">
        <AnimatePresence initial={false}>
          {filtered.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="flex flex-col items-center justify-center h-40 text-center px-6 gap-2"
            >
              <span className="text-3xl">💬</span>
              <p className="text-sm text-[var(--text-muted)]">No conversations found</p>
            </motion.div>
          ) : (
            filtered.map((conv) => (
              <ConversationCard
                key={conv.id}
                conv={conv}
                isSelected={selectedConversationId === conv.id}
                onSelect={() => {
                  selectConversation(conv.id);
                  onSelectMobile?.();
                }}
              />
            ))
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
