import { ChannelBadge } from "@ui/components/ChannelBadge";
import type { UserTablo } from "@xtablo/shared/types/tablos.types";
import { Badge } from "@xtablo/ui/components/badge";
import { twMerge } from "tailwind-merge";

interface ChatChannelPreviewProps {
  tablo: UserTablo;
  isActive: boolean;
  onClick: () => void;
  unreadCount: number;
  lastMessage?: string;
  lastMessageTime?: string;
  isOnline: boolean;
}

function formatTimestamp(timestamp: string | Date): string {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return "now";
  if (minutes < 60) return `${minutes}m`;
  if (hours < 24) return `${hours}h`;
  if (days < 7) return `${days}d`;
  return date.toLocaleDateString();
}

export function ChatChannelPreview({
  tablo,
  isActive,
  onClick,
  unreadCount,
  lastMessage,
  lastMessageTime,
  isOnline,
}: ChatChannelPreviewProps) {
  return (
    <div
      className={twMerge(
        "group relative flex items-center gap-3 p-3 cursor-pointer transition-all duration-200 hover:bg-gray-50 dark:hover:bg-gray-800/50 border-b border-gray-100 dark:border-gray-800",
        isActive && "bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"
      )}
      onClick={onClick}
    >
      <ChannelBadge tablo={tablo} displayTitle={tablo.name} isOnline={isOnline} />

      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between mb-1">
          <h3
            className={twMerge(
              "font-medium text-gray-900 dark:text-gray-100 truncate",
              isActive && "text-[#804EEC] dark:text-purple-400"
            )}
          >
            {tablo.name}
          </h3>
          {lastMessageTime && (
            <span className="text-xs text-gray-500 dark:text-gray-400 ml-2 shrink-0">
              {formatTimestamp(lastMessageTime)}
            </span>
          )}
        </div>

        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2 max-h-10 overflow-hidden">
            {lastMessage ?? "No messages yet"}
          </p>

          {unreadCount > 0 && (
            <div className="ml-2 shrink-0">
              <Badge
                color="indigo"
                className="text-xs min-w-[20px] h-5 px-2 py-0 flex items-center justify-center"
              >
                {unreadCount > 99 ? "99+" : unreadCount}
              </Badge>
            </div>
          )}
        </div>
      </div>

      {isActive && (
        <div className="absolute left-0 top-0 bottom-0 w-1 bg-[#804EEC] dark:bg-purple-400 rounded-r-full" />
      )}
    </div>
  );
}
