import { ChannelBadge } from "@ui/components/ChannelBadge";
import { UserTablo } from "@xtablo/shared/types/tablos.types";
import { Badge } from "@xtablo/ui/components/badge";
import { ReactNode } from "react";
import { Channel } from "stream-chat";
import { twMerge } from "tailwind-merge";

interface ChannelPreviewProps {
  channel: Channel;
  tablo: UserTablo | null;
  displayTitle: string | undefined;
  activeChannel?: Channel;
  setActiveChannel?: (channel: Channel) => void;
  unreadCount?: number;
  latestMessagePreview?: ReactNode;
  className?: string;
}

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();
}

// function getLastMessagePreview(lastMessage?: StreamMessage): string {
//   if (!lastMessage) return "No messages yet";

//   if (lastMessage.deleted_at) return "Message deleted";

//   if (lastMessage.text) {
//     return lastMessage.text.length > 50
//       ? lastMessage.text.substring(0, 50) + "..."
//       : lastMessage.text;
//   }

//   if (lastMessage.attachments?.length && lastMessage.attachments.length > 0) {
//     const attachment = lastMessage.attachments[0];
//     if (attachment.type === "image") return "📷 Image";
//     if (attachment.type === "video") return "🎥 Video";
//     if (attachment.type === "file") return "📎 File";
//   }

//   return "Message";
// }

function isUserOnline(channel: Channel): boolean {
  const members = Object.values(channel.state?.members || {});

  const otherMembers = members.filter(
    // @ts-expect-error TODO: fix this
    (member) => member.user?.id !== channel.data?.config?.created_by?.id
  );

  return otherMembers.some((member) => member.user?.online);
}

export function ChannelPreview({
  displayTitle,
  channel,
  tablo,
  activeChannel,
  setActiveChannel,
  unreadCount = 0,
  latestMessagePreview,
  className,
}: ChannelPreviewProps) {
  const isActive = activeChannel?.id === channel.id;
  const isOnline = isUserOnline(channel);
  const timestamp = channel.data?.created_at;

  const handleClick = () => {
    setActiveChannel?.(channel);
  };

  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",
        className
      )}
      onClick={handleClick}
    >
      <ChannelBadge tablo={tablo} displayTitle={displayTitle} isOnline={isOnline} />

      {/* Channel info */}
      <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"
            )}
          >
            {displayTitle}
          </h3>
          {timestamp && (
            <span className="text-xs text-gray-500 dark:text-gray-400 ml-2 shrink-0">
              {formatTimestamp(timestamp)}
            </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">
            {latestMessagePreview}
          </p>

          {/* Unread count badge */}
          {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>

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