'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Pin, X, Loader2 } from 'lucide-react';
import { pinList, pinRemove, type RoomPinResponse, type RoomMemberResponse } from '@/client';
import { toast } from 'sonner';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { getSenderDisplayName } from './sender';
import { formatMessageTime } from './shared/formatters';

interface RoomPinPanelProps {
  roomId: string;
  messages: Array<{
    id: string;
    content: string;
    sender_id: string;
    sender_type: string;
    send_at: string;
  }>;
  members: RoomMemberResponse[];
  onClose: () => void;
  onJumpToMessage: (messageId: string) => void;
}

export function RoomPinPanel({ roomId, messages, members, onClose, onJumpToMessage }: RoomPinPanelProps) {
  const queryClient = useQueryClient();

  const { data: pins, isLoading } = useQuery({
    queryKey: ['roomPins', roomId],
    queryFn: async () => {
      const resp = await pinList({ path: { room_id: roomId } });
      return resp.data?.data ?? ([] as RoomPinResponse[]);
    },
  });

  const unpinMutation = useMutation({
    mutationFn: async (messageId: string) => {
      await pinRemove({ path: { room_id: roomId, message_id: messageId } });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roomPins', roomId] });
      toast.success('Message unpinned');
    },
    onError: () => {
      toast.error('Failed to unpin message');
    },
  });

  // Build a map of message_id -> message content from local messages
  const messageMap = new Map(messages.map(m => [m.id, m]));

  return (
    <aside
      className="flex flex-col border-l z-20 animate-in slide-in-from-right duration-200"
      style={{
        width: 380,
        borderColor: 'var(--room-border)',
        background: 'var(--room-bg)',
        top: '48px',
        bottom: 0,
        right: 0,
        position: 'absolute',
      }}
    >
      {/* Header */}
      <div
        className="flex items-center justify-between px-4 py-3 border-b shrink-0"
        style={{ borderColor: 'var(--room-border)' }}
      >
        <div className="flex items-center gap-2">
          <Pin className="h-4 w-4" style={{ color: 'var(--room-accent)' }} />
          <span className="text-sm font-semibold" style={{ color: 'var(--room-text)' }}>
            Pinned Messages
          </span>
          {pins && (
            <span
              className="text-[11px] px-1.5 py-0.5 rounded-full"
              style={{ background: 'var(--room-channel-active)', color: 'var(--room-text-muted)' }}
            >
              {pins.length}
            </span>
          )}
        </div>
        <button
          onClick={onClose}
          className="flex h-6 w-6 items-center justify-center rounded-md transition-colors cursor-pointer bg-transparent border-0"
          style={{ color: 'var(--room-text-muted)' }}
        >
          <X className="h-4 w-4" />
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="flex items-center justify-center h-24">
            <Loader2 className="h-5 w-5 animate-spin" style={{ color: 'var(--room-text-muted)' }} />
          </div>
        ) : pins && pins.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 gap-2">
            <Pin className="h-8 w-8 opacity-30" style={{ color: 'var(--room-text-muted)' }} />
            <p className="text-sm" style={{ color: 'var(--room-text-muted)' }}>No pinned messages</p>
          </div>
        ) : (
          <div className="divide-y" style={{ borderColor: 'var(--room-border)' }}>
            {pins?.map((pin) => {
              const localMsg = messageMap.get(pin.message);
              return (
                <div
                  key={pin.message}
                  className="group px-4 py-3 hover:bg-[var(--room-channel-active)] transition-colors cursor-pointer"
                  onClick={() => {
                    onJumpToMessage(pin.message);
                    onClose();
                  }}
                >
                  {/* Sender row */}
                  <div className="flex items-center gap-2 mb-1">
                    <Avatar className="h-5 w-5">
                      {(() => {
                        const member = members.find(m => m.user === pin.pinned_by);
                        return (
                          <>
                            {member?.user_info?.avatar_url ? (
                              <AvatarImage src={member.user_info.avatar_url} className="h-5 w-5" />
                            ) : null}
                            <AvatarFallback className="h-5 w-5 text-[10px]">
                              {(member?.user_info?.username ?? pin.pinned_by).charAt(0).toUpperCase()}
                            </AvatarFallback>
                          </>
                        );
                      })()}
                    </Avatar>
                    <span className="text-xs font-medium" style={{ color: 'var(--room-text)' }}>
                      {(() => {
                        const member = members.find(m => m.user === pin.pinned_by);
                        return member?.user_info?.username ?? pin.pinned_by;
                      })()}
                    </span>
                    <span className="text-[11px]" style={{ color: 'var(--room-text-muted)' }}>
                      pinned {formatMessageTime(pin.pinned_at).split(':').slice(0, 2).join(':')}
                    </span>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        unpinMutation.mutate(pin.message);
                      }}
                      className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity flex h-5 w-5 items-center justify-center rounded text-[var(--room-text-muted)] hover:text-red-400 cursor-pointer bg-transparent border-0"
                      title="Unpin"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </div>

                  {/* Message preview */}
                  <p
                    className="text-[13px] line-clamp-2 pl-7"
                    style={{ color: 'var(--room-text-secondary)' }}
                  >
                    {localMsg
                      ? localMsg.content.length > 120
                        ? localMsg.content.slice(0, 120) + '…'
                        : localMsg.content
                      : `[Message #${pin.message}]`}
                  </p>

                  {/* Original sender */}
                  {localMsg && (
                    <div className="mt-0.5 pl-7">
                      <span className="text-[11px]" style={{ color: 'var(--room-text-muted)' }}>
                        {getSenderDisplayName(localMsg as any)} • {formatMessageTime(localMsg.send_at)}
                      </span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </aside>
  );
}
