import { useEffect, useState } from 'react';
import { useAuthStore, type PublicProfile } from '../stores/auth.ts';
import { useServerStore } from '../stores/server.ts';
import { useMemberStore } from '../stores/member.ts';
import { usePermissions } from '../lib/usePermissions.ts';
import { MemberRoleAssign } from './MemberRoleAssign.tsx';

interface UserProfileModalProps {
  userId: string;
  onClose: () => void;
}

export function UserProfileModal({ userId, onClose }: UserProfileModalProps) {
  const getPublicProfile = useAuthStore((s) => s.getPublicProfile);
  const blockUser = useAuthStore((s) => s.blockUser);
  const currentUser = useAuthStore((s) => s.user);
  const activeServerId = useServerStore((s) => s.activeServerId);
  const [profile, setProfile] = useState<PublicProfile | null>(null);
  const [error, setError] = useState<string | null>(null);

  const isSelf = currentUser?.id === userId;
  const { isOwner, canManageServer, canChangeNickname, canManageNicknames } = usePermissions(activeServerId);
  const canEditNickname = isOwner || canManageServer || (isSelf ? canChangeNickname : canManageNicknames);

  const membersByServer = useMemberStore((s) => s.membersByServer);
  const serverMembers = activeServerId ? membersByServer[activeServerId] || [] : [];
  const memberData = serverMembers.find((m) => m.id === userId);
  const currentNickname = memberData?.nickname || '';

  const setMemberNickname = useMemberStore((s) => s.setMemberNickname);

  const [nickname, setNickname] = useState(currentNickname);
  const [isEditingNickname, setIsEditingNickname] = useState(false);
  const [savingNickname, setSavingNickname] = useState(false);

  useEffect(() => {
    setNickname(currentNickname);
  }, [currentNickname]);

  const handleSaveNickname = async () => {
    if (!activeServerId) return;
    setSavingNickname(true);
    setError(null);
    try {
      await setMemberNickname(activeServerId, userId, nickname.trim());
      setIsEditingNickname(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save nickname');
    } finally {
      setSavingNickname(false);
    }
  };

  useEffect(() => {
    getPublicProfile(userId).then(setProfile).catch(setError);
  }, [userId, getPublicProfile]);

  const statusColor = {
    online: 'bg-gb-green',
    idle: 'bg-gb-orange',
    dnd: 'bg-gb-red',
    offline: 'bg-gb-fg-t',
  }[profile?.status || 'offline'];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-gb-bg/90 p-4" onClick={onClose}>
      <div className="bg-gb-bg border border-gb-fg-t w-full max-w-md max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
        {error && <div className="p-3 text-gb-red text-xs">ERR: {error}</div>}
        {!profile && !error && <div className="p-6 text-gb-fg-f text-center text-xs">[loading...]</div>}
        {profile && (
          <>
            <div
              className="h-24 bg-cover bg-center border-b border-gb-bg-t"
              style={{ backgroundImage: profile.banner_url ? `url(${profile.banner_url})` : undefined, backgroundColor: profile.accent_color || '#2D3436' }}
            />
            <div className="p-4">
              <div className="flex items-start gap-3 -mt-12 mb-3">
                <img src={profile.avatar} alt="" className="w-20 h-20 border-2 border-gb-bg bg-gb-bg object-cover" />
                <div className="mt-12">
                  <div className="flex items-center gap-2">
                    <span className={`w-2 h-2 rounded-full ${statusColor}`} />
                    <span className="text-gb-fg font-bold">{currentNickname || profile.display_name || profile.username}</span>
                  </div>
                  <div className="text-gb-fg-s text-xs">@{profile.username}</div>
                  {profile.pronouns && <div className="text-gb-fg-t text-[10px]">{profile.pronouns}</div>}
                  {activeServerId && (
                    <div className="text-[10px] font-mono mt-1 flex items-center gap-1.5">
                      <span className="text-gb-fg-t">NICKNAME:</span>
                      {isEditingNickname ? (
                        <div className="flex items-center gap-1">
                          <input
                            type="text"
                            value={nickname}
                            onChange={(e) => setNickname(e.target.value)}
                            placeholder="no nickname"
                            className="bg-gb-bg-t text-gb-fg px-1 py-0.5 text-[10px] outline-none border border-gb-orange max-w-[120px]"
                          />
                          <button
                            onClick={handleSaveNickname}
                            disabled={savingNickname}
                            className="text-gb-green hover:underline font-bold"
                          >
                            [SAVE]
                          </button>
                          <button
                            onClick={() => {
                              setNickname(currentNickname);
                              setIsEditingNickname(false);
                            }}
                            className="text-gb-fg-f hover:underline"
                          >
                            [X]
                          </button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-1">
                          <span className="text-gb-fg-s">{currentNickname || '[NONE]'}</span>
                          {canEditNickname && (
                            <button
                              onClick={() => setIsEditingNickname(true)}
                              className="text-gb-aqua hover:underline"
                            >
                              [EDIT]
                            </button>
                          )}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
              {profile.tagline && <div className="text-gb-fg text-sm mb-2 italic">"{profile.tagline}"</div>}
              {profile.bio && <div className="text-gb-fg-s text-xs mb-3 whitespace-pre-wrap">{profile.bio}</div>}
              {profile.social_links && profile.social_links.length > 0 && (
                <div className="mb-3 space-y-1">
                  {profile.social_links.map((link, idx) => (
                    <a key={idx} href={link.url} target="_blank" rel="noreferrer" className="text-gb-aqua text-xs block hover:underline">
                      {link.platform}
                    </a>
                  ))}
                </div>
              )}
              {profile.badges && profile.badges.length > 0 && (
                <div className="flex flex-wrap gap-1 mb-3">
                  {profile.badges.map((badge) => (
                    <span key={badge.id} className="text-[10px] px-1.5 py-0.5 border border-gb-bg-t text-gb-fg-s" title={badge.description}>
                      {badge.icon && <span className="mr-1">{badge.icon}</span>}
                      {badge.name}
                    </span>
                  ))}
                </div>
              )}
              {activeServerId && (
                <div className="mb-4 mt-2">
                  <div className="text-xs text-gb-fg-t font-mono mb-1">{'>'} ROLES:</div>
                  <MemberRoleAssign serverId={activeServerId} member={profile as any} />
                </div>
              )}
              <div className="flex justify-end gap-2">
                <button onClick={onClose} className="text-xs text-gb-fg-f hover:text-gb-orange font-mono">[CLOSE]</button>
                <button
                  onClick={() => blockUser(userId).then(onClose)}
                  className="text-xs text-gb-red hover:text-gb-orange font-mono"
                >
                  [BLOCK]
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
