"use client";

import { Plus, BellOff } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useRooms } from "@/hooks/useMessenger";
import { useMessengerContext } from "@/contexts/MessengerContext";
import { useAuth } from "@/hooks/useAuth";
import { UserAvatar } from "./UserAvatar";
import { cn } from "@/lib/utils";
import type { Room } from "@/hooks/useMessenger";
import type { UserStatus } from "@/hooks/useMessengerSocket";

function formatTime(dateStr?: string) {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  const now = new Date();
  const isToday = d.toDateString() === now.toDateString();
  if (isToday) {
    return d.toLocaleTimeString("ko-KR", { hour: "2-digit", minute: "2-digit" });
  }
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (d.toDateString() === yesterday.toDateString()) return "어제";
  return d.toLocaleDateString("ko-KR", { month: "short", day: "numeric" });
}

function RoomItem({ room, selected, onClick, currentUserId, userStatuses, isMuted }: { room: Room; selected: boolean; onClick: () => void; currentUserId?: string; userStatuses: Map<string, UserStatus>; isMuted: boolean }) {
  const otherParticipant = room.type === "dm"
    ? room.participants.find((p) => p.userId !== currentUserId)
    : undefined;
  const displayName = otherParticipant?.userName ?? room.name;
  const avatarParticipant = otherParticipant ?? room.participants[0];
  return (
    <button
      onClick={onClick}
      className={cn(
        "w-full grid items-center gap-2 px-3 py-2 hover:bg-muted/50 text-left border-l-2 border-transparent",
        selected && "bg-accent border-l-primary"
      )}
      style={{ gridTemplateColumns: "36px 1fr" }}
    >
      <UserAvatar
        photo={avatarParticipant?.photo}
        name={displayName || avatarParticipant?.userName || "?"}
        size="md"
        status={otherParticipant ? (userStatuses.get(otherParticipant.userId) ?? "offline") : undefined}
      />
      <div className="min-w-0 overflow-hidden">
        <div className="flex items-center gap-1 min-w-0">
          <span className={cn("text-sm truncate min-w-0 flex-1", selected ? "font-semibold" : "font-medium")}>{displayName}</span>
          <span className="text-[10px] text-muted-foreground shrink-0 whitespace-nowrap">
            {formatTime(room.lastMessageAt)}
          </span>
        </div>
        <div className="flex items-center gap-1 min-w-0">
          <span className="text-xs text-muted-foreground truncate min-w-0 flex-1">
            {room.lastMessage || "\u00A0"}
          </span>
          {isMuted && <BellOff className="h-3 w-3 text-muted-foreground shrink-0" />}
          {room.unreadCount > 0 && !selected && (
            <span className="ml-1 shrink-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground px-1">
              {room.unreadCount > 99 ? "99+" : room.unreadCount}
            </span>
          )}
        </div>
      </div>
    </button>
  );
}

export function RoomList({ userStatuses, newRoomOpen, setNewRoomOpen }: { userStatuses: Map<string, UserStatus>; newRoomOpen: boolean; setNewRoomOpen: (open: boolean) => void }) {
  const { data: rooms = [] } = useRooms();
  const { selectedRoomId, selectRoom, mutedRooms } = useMessengerContext();
  const { user } = useAuth();

  const dmRooms = rooms.filter((r) => r.type === "dm");
  const groupRooms = rooms.filter((r) => r.type === "group");
  const channelRooms = rooms.filter((r) => r.type === "channel");

  const renderRooms = (list: Room[]) =>
    list.length === 0 ? (
      <div className="text-xs text-muted-foreground text-center py-4">대화가 없습니다</div>
    ) : (
      list.map((r) => (
        <RoomItem
          key={r.id}
          room={r}
          selected={r.id === selectedRoomId}
          onClick={() => selectRoom(r.id)}
          currentUserId={user?.userId}
          userStatuses={userStatuses}
          isMuted={mutedRooms.has(String(r.id))}
        />
      ))
    );

  return (
    <div className="flex flex-col h-full border-r w-[240px] shrink-0 overflow-hidden">
      <div className="flex items-center justify-between px-3 py-2 border-b">
        <span className="text-xs font-semibold text-muted-foreground">대화 목록</span>
        <button
          onClick={() => setNewRoomOpen(true)}
          className="p-1 hover:bg-muted rounded"
          aria-label="새 대화"
        >
          <Plus className="h-4 w-4" />
        </button>
      </div>

      <Tabs defaultValue="dm" className="flex-1 flex flex-col">
        <TabsList className="w-full rounded-none border-b h-8 bg-transparent p-0">
          <TabsTrigger value="dm" className="flex-1 text-xs h-8 rounded-none data-[state=active]:border-b-2 data-[state=active]:border-primary data-[state=active]:shadow-none">
            DM
          </TabsTrigger>
          <TabsTrigger value="group" className="flex-1 text-xs h-8 rounded-none data-[state=active]:border-b-2 data-[state=active]:border-primary data-[state=active]:shadow-none">
            그룹
          </TabsTrigger>
          <TabsTrigger value="channel" className="flex-1 text-xs h-8 rounded-none data-[state=active]:border-b-2 data-[state=active]:border-primary data-[state=active]:shadow-none">
            채널
          </TabsTrigger>
        </TabsList>

        <ScrollArea className="flex-1">
          <TabsContent value="dm" className="m-0">{renderRooms(dmRooms)}</TabsContent>
          <TabsContent value="group" className="m-0">{renderRooms(groupRooms)}</TabsContent>
          <TabsContent value="channel" className="m-0">{renderRooms(channelRooms)}</TabsContent>
        </ScrollArea>
      </Tabs>

    </div>
  );
}
