'use client';

import React, { memo, useMemo } from 'react';
import type { RoomMemberResponse } from '@/client';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Loader2, Shield, UserRound, Bot } from 'lucide-react';
import { useTheme } from '@/contexts';
import type { PresenceMap } from '@/contexts/room-context';
import { cn } from '@/lib/utils';
import type { RoomAiConfig } from '@/contexts';

interface DiscordMemberListProps {
  members: RoomMemberResponse[];
  membersLoading: boolean;
  onMemberClick?: (member: RoomMemberResponse) => void;
  onMemberMention?: (id: string, label: string) => void;
  aiConfigs?: RoomAiConfig[];
  presence?: PresenceMap;
}

// Role color mapping — AI Studio clean palette
const ROLE_COLORS: Record<string, string> = {
  owner: '#1c7ded',
  admin: '#1c7ded',
  moderator: '#6b7280',
  member: '#9ca3af',
  guest: '#9ca3af',
};

// Presence dot colors
const PRESENCE_COLORS: Record<string, string> = {
  online: '#3ba55c',
  away: '#faa61a',
  dnd: '#ed4245',
  offline: '#747f8d',
};

function getRoleColor(role: string): string {
  return ROLE_COLORS[role] ?? ROLE_COLORS['member'];
}

function PresenceDot({ status }: { status: string }) {
  const color = PRESENCE_COLORS[status] ?? PRESENCE_COLORS['offline'];
  return (
    <span
      className="absolute bottom-0 right-0 rounded-full border-2"
      style={{
        background: color,
        width: 10,
        height: 10,
        borderColor: 'var(--room-sidebar)',
      }}
    />
  );
}

function MemberItem({
  member,
  onClick,
  presenceStatus,
}: {
  member: RoomMemberResponse;
  onClick?: (member: RoomMemberResponse) => void;
  presenceStatus?: string;
}) {
  const { resolvedTheme } = useTheme();
  const displayName = (member.user_info as { username?: string } | null | undefined)?.username ?? member.user.slice(0, 8);
  const roleColor = getRoleColor(member.role ?? 'member');

  return (
    <button
      type="button"
      className="discord-member-item w-full text-left"
      onClick={() => onClick?.(member)}
      title={`@${displayName} — ${member.role ?? 'member'}`}
    >
      <div className="discord-member-avatar-wrap relative">
        <Avatar className="h-8 w-8">
          {member.user_info?.avatar_url ? (
            <AvatarImage src={member.user_info.avatar_url} alt={displayName} />
          ) : null}
          <AvatarFallback
            className="text-xs font-semibold"
            style={{ background: `${roleColor}33`, color: roleColor }}
          >
            {displayName.slice(0, 2).toUpperCase()}
          </AvatarFallback>
        </Avatar>
        <PresenceDot status={presenceStatus ?? 'offline'} />
      </div>

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-1.5">
          <span
            className="truncate text-sm font-medium"
            style={{ color: roleColor }}
          >
            {displayName}
          </span>
        </div>
        {member.role && member.role !== 'member' && (
          <span className={cn('text-[10px] uppercase tracking-wide',
            resolvedTheme === 'dark' ? 'opacity-60' : 'text-muted-foreground'
          )}>
            {member.role}
          </span>
        )}
      </div>
    </button>
  );
}

function MemberSection({
  title,
  icon,
  children,
}: {
  title: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div>
      <div className="discord-member-section-title">
        {icon}
        <span>{title}</span>
      </div>
      <div>{children}</div>
    </div>
  );
}

export const DiscordMemberList = memo(function DiscordMemberList({
  members,
  membersLoading,
  onMemberClick,
  aiConfigs = [],
  presence = {},
}: DiscordMemberListProps) {
  useTheme(); // theme consumed via CSS variables
  const { admins, moderators, regularMembers } = useMemo(() => {
    const a: RoomMemberResponse[] = [];
    const m: RoomMemberResponse[] = [];
    const r: RoomMemberResponse[] = [];
    for (const member of members) {
      if (member.role === 'owner' || member.role === 'admin') a.push(member);
      else if (member.role === 'moderator') m.push(member);
      else r.push(member);
    }
    return { admins: a, moderators: m, regularMembers: r };
  }, [members]);

  return (
    <div className="discord-member-sidebar">
      <div className="discord-member-header">
        <span className="text-sm font-semibold" style={{ color: 'var(--room-text)' }}>Members</span>
        <span className="ml-auto text-xs" style={{ color: 'var(--room-text-muted)' }}>{members.length}</span>
      </div>

      <div className="flex-1 overflow-y-auto py-2 px-1">
        {membersLoading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-5 w-5 animate-spin" style={{ color: 'var(--room-text-muted)' }} />
          </div>
        ) : (
          <>
            {/* AI section — always at top */}
            {aiConfigs.length > 0 && (
              <MemberSection
                title={`AI — ${aiConfigs.length}`}
                icon={<Bot className="h-3 w-3" />}
              >
                {aiConfigs.map((ai) => {
                  const label = ai.modelName || 'Unknown AI';
                  return (
                    <button
                      key={ai.model}
                      type="button"
                      className="discord-member-item w-full text-left"
                      onClick={() => onMemberClick?.({
                        user: ai.model,
                        user_info: { username: label },
                        role: 'ai',
                      } as RoomMemberResponse)}
                      title={`@${label}`}
                    >
                      <div className="discord-member-avatar-wrap">
                        <Avatar className="h-8 w-8">
                          <AvatarFallback
                            className="text-xs font-semibold"
                            style={{ background: '#10b98133', color: '#10b981' }}
                          >
                            <Bot className="h-4 w-4" />
                          </AvatarFallback>
                        </Avatar>
                        <span className="discord-member-status-dot online" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-1.5">
                          <span
                            className="truncate text-sm font-medium"
                            style={{ color: '#10b981' }}
                          >
                            {label}
                          </span>
                          <span
                            className="shrink-0 rounded px-1 py-0.5 text-[10px] font-medium"
                            style={{ background: 'rgba(16,185,129,0.1)', color: '#10b981' }}
                          >
                            AI
                          </span>
                        </div>
                      </div>
                    </button>
                  );
                })}
              </MemberSection>
            )}

            {(admins.length > 0 || moderators.length > 0) && (
              <MemberSection
                title={`Online — ${admins.length + moderators.length}`}
                icon={<Shield className="h-3 w-3" />}
              >
                {[...admins, ...moderators].map((member) => (
                  <MemberItem
                    key={member.user}
                    member={member}
                    onClick={onMemberClick}
                    presenceStatus={presence[member.user]}
                  />
                ))}
              </MemberSection>
            )}

            {regularMembers.length > 0 && (
              <MemberSection
                title={`Members — ${regularMembers.length}`}
                icon={<UserRound className="h-3 w-3" />}
              >
                {regularMembers.map((member) => (
                  <MemberItem
                    key={member.user}
                    member={member}
                    onClick={onMemberClick}
                    presenceStatus={presence[member.user]}
                  />
                ))}
              </MemberSection>
            )}
          </>
        )}
      </div>
    </div>
  );
});
