import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Search, MessageSquare, Users, Check, ArrowLeft, ArrowRight, Loader2 } from 'lucide-react';
import { ChatApi } from '../../infrastructure/chatApi';
import { UserApi } from '../../../users/infrastructure/userApi';
import { FriendApi } from '../../../friends/infrastructure/friendApi';
import { useChatStore } from '../../application/chatStore';
import { useAuthStore } from '../../../auth/application/authStore';
import { useLang } from '../../../../core/infrastructure/i18n';
import type { UserPresence, FriendWithId } from '../../../../core/domain/types';

import { getInitials } from '../../../../core/utils/utils';

interface NewChatModalProps {
  onClose: () => void;
  onOpenTelegramImport?: () => void;
}

type Mode = 'personal' | 'group-select' | 'group-name';

export default function NewChatModal({ onClose, onOpenTelegramImport }: NewChatModalProps) {
  const { user, config } = useAuthStore();
  const { t } = useLang();
  const { addChat, setActiveChat, loadMessages } = useChatStore();
  const [mode, setMode] = useState<Mode>('personal');
  const [query, setQuery] = useState('');
  const [users, setUsers] = useState<UserPresence[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedUsers, setSelectedUsers] = useState<UserPresence[]>([]);
  const [groupName, setGroupName] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [friends, setFriends] = useState<FriendWithId[]>([]);

  // Load friends on mount
  useEffect(() => {
    FriendApi.getFriends().then(setFriends).catch(() => {});
  }, []);

  useEffect(() => {
    if (!query.trim() || query.trim().length < 3) {
      setUsers([]);
      return;
    }
    const timer = setTimeout(async () => {
      try {
        setIsLoading(true);
        const results = await UserApi.searchUsers(query);
        setUsers(results.filter((u) => u.id !== user?.id));
      } catch (e) {
        console.error(e);
      } finally {
        setIsLoading(false);
      }
    }, 300);
    return () => clearTimeout(timer);
  }, [query, user?.id]);

  const handleSelectUser = async (selectedUser: UserPresence) => {
    if (mode === 'personal') {
      try {
        // Check if personal chat with this user already exists
        const existingChat = useChatStore.getState().chats.find(
          (c) => c.type === 'personal' && c.members.some((m) => m.user.id === selectedUser.id)
        );

        if (existingChat) {
          setActiveChat(existingChat.id);
          loadMessages(existingChat.id);
          onClose();
          return;
        }

        const chat = await ChatApi.createPersonalChat(selectedUser.id);
        addChat(chat);
        import('../../../../core/infrastructure/socket').then(({ getSocket }) => getSocket()?.emit('join_chat', chat.id));
        setActiveChat(chat.id);
        loadMessages(chat.id);
        onClose();
      } catch (e: unknown) {
        console.error(e);
      }
    } else {
      // Toggle selection
      setSelectedUsers((prev) => {
        const exists = prev.find((u) => u.id === selectedUser.id);
        if (exists) return prev.filter((u) => u.id !== selectedUser.id);
        return [...prev, selectedUser];
      });
    }
  };

  const handleCreateGroup = async () => {
    if (!groupName.trim() || selectedUsers.length === 0) return;
    setIsCreating(true);
    try {
        const chat = await ChatApi.createGroupChat(
          groupName.trim(),
          selectedUsers.map((u) => u.id)
        );
        addChat(chat);
        import('../../../../core/infrastructure/socket').then(({ getSocket }) => getSocket()?.emit('join_chat', chat.id));
        setActiveChat(chat.id);
        loadMessages(chat.id);
        onClose();
    } catch (e) {
      console.error(e);
    } finally {
      setIsCreating(false);
    }
  };

  const isSelected = (userId: string) => selectedUsers.some((u) => u.id === userId);

  return (
    <>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-black/60 z-50"
        onClick={onClose}
      />
      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 20 }}
        className="fixed inset-0 z-50 flex items-center justify-center lg:p-4"
        onClick={(e) => e.target === e.currentTarget && onClose()}
      >
        <div className="w-full lg:max-w-md h-full lg:h-auto lg:rounded-[2.5rem] bg-surface-container/60 backdrop-blur-3xl shadow-[0_48px_80px_-16px_rgba(0,0,0,0.7)] border-none lg:border lg:border-white/5 overflow-hidden flex flex-col" role="dialog" aria-modal="true" aria-label={t('newChat')}>
          {/* Шапка */}
          <div className="flex items-center justify-between p-7 pb-4">
            <div className="flex items-center gap-4">
              {mode !== 'personal' && (
                <button
                  onClick={() => {
                    if (mode === 'group-name') setMode('group-select');
                    else {
                      setMode('personal');
                      setSelectedUsers([]);
                    }
                  }}
                  className="p-2 rounded-xl text-on-surface-variant/40 hover:text-white hover:bg-white/10 transition-all active:scale-95"
                >
                  <ArrowLeft size={18} />
                </button>
              )}
              <h2 className="text-xl font-black uppercase tracking-tight text-white/90">
                {mode === 'personal'
                  ? t('newChatTitle')
                  : mode === 'group-select'
                    ? t('selectMembers')
                    : t('newGroup')}
              </h2>
            </div>
            <button
              onClick={onClose}
              className="p-2 rounded-xl text-on-surface-variant/40 hover:text-white hover:bg-white/10 transition-all active:scale-95"
            >
              <X size={20} />
            </button>
          </div>

          {mode === 'group-name' ? (
            /* Шаг 2: Назвать группу */
            <div className="p-4 space-y-4">
              <div className="group relative">
                <input
                  type="text"
                  placeholder={t('groupNamePlaceholder')}
                  value={groupName}
                  onChange={(e) => setGroupName(e.target.value)}
                  className="w-full px-6 py-4 rounded-2xl bg-surface-container-highest/30 text-sm text-white placeholder-zinc-500 border border-white/5 focus:border-primary/40 focus:bg-surface-container-highest/50 outline-none transition-all shadow-inner"
                  autoFocus
                />
              </div>
              <div>
                <p className="text-xs text-zinc-500 mb-2">
                  {t('membersCount')} ({selectedUsers.length}):
                </p>
                <div className="flex flex-wrap gap-2">
                  {selectedUsers.map((u) => (
                    <div
                      key={u.id}
                      className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-knot-500/20 border border-knot-500/30"
                    >
                      {u.avatar ? (
                        <img src={u.avatar} alt="" className="w-5 h-5 rounded-lg object-cover" />
                      ) : (
                        <div className="w-5 h-5 rounded-lg bg-linear-to-br from-primary/80 to-primary flex items-center justify-center text-on-primary text-[9px] font-black shadow-inner">
                          {getInitials(u.displayName || u.userName || u.username || '?')}
                        </div>
                      )}
                      <span className="text-xs text-white">{u.displayName || u.userName || u.username || ''}</span>
                      <button
                        onClick={() => setSelectedUsers((prev) => prev.filter((p) => p.id !== u.id))}
                        className="text-zinc-500 hover:text-zinc-300"
                      >
                        <X size={12} />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
              <button
                onClick={handleCreateGroup}
                disabled={!groupName.trim() || isCreating}
                className="w-full py-4 rounded-2xl bg-primary text-on-primary text-[13px] font-black uppercase tracking-widest transition-all hover:brightness-110 active:scale-[0.98] disabled:opacity-50 flex items-center justify-center gap-2 shadow-[0_20px_30px_-10px_rgba(154,203,255,0.2)]"
              >
                {isCreating ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Users size={18} />
                    {t('createGroup')}
                  </>
                )}
              </button>
            </div>
          ) : (
            <>
              {/* Переключатель режима + Поиск */}
              <div className="p-4 space-y-3">
                {mode === 'personal' && (
                  <button
                    onClick={() => setMode('group-select')}
                    className="w-full flex items-center gap-4 px-4 py-3.5 rounded-2xl bg-surface-container-highest/20 hover:bg-surface-container-highest/40 transition-all border border-white/5 active:scale-[0.98] group"
                  >
                    <div className="w-11 h-11 rounded-2xl bg-linear-to-br from-primary to-primary-container flex items-center justify-center shadow-inner border border-white/10 group-hover:scale-105 transition-transform">
                      <Users size={20} className="text-on-primary" />
                    </div>
                    <div className="text-left">
                      <p className="text-[13px] font-black uppercase tracking-tight text-white/90">{t('createGroup')}</p>
                      <p className="text-[11px] text-zinc-500 font-medium tracking-wide">
                        {t('upTo200').replace('200', String(config?.chats?.maxGroupParticipants || 500))}
                      </p>
                    </div>
                  </button>
                )}

                {config?.import?.enableTelegramImport && mode === 'personal' && (
                  <button
                    onClick={() => {
                        onOpenTelegramImport?.();
                        onClose();
                    }}
                    className="w-full flex items-center gap-4 px-4 py-3.5 rounded-2xl bg-surface-container-highest/20 hover:bg-surface-container-highest/40 transition-all border border-white/5 active:scale-[0.98] group"
                  >
                    <div className="w-11 h-11 rounded-2xl bg-linear-to-br from-[#0088cc] to-[#00aaff] flex items-center justify-center shadow-inner border border-white/10 group-hover:scale-105 transition-transform">
                      <MessageSquare size={20} className="text-white" />
                    </div>
                    <div className="text-left">
                      <p className="text-[13px] font-black uppercase tracking-tight text-white/90">{t('importTelegram')}</p>
                      <p className="text-[11px] text-zinc-500 font-medium tracking-wide">
                        {t('importTelegramDesc')}
                      </p>
                    </div>
                  </button>
                )}

                {/* Выбранные (в режиме группы) */}
                {mode === 'group-select' && selectedUsers.length > 0 && (
                  <div className="flex items-center gap-2 flex-wrap">
                    {selectedUsers.map((u) => (
                      <button
                        key={u.id}
                        onClick={() => setSelectedUsers((prev) => prev.filter((p) => p.id !== u.id))}
                        className="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-knot-500/20 border border-knot-500/30 text-xs text-white hover:bg-knot-500/30 transition-colors"
                      >
                        {(u.displayName || u.userName || u.username || '')}
                        <X size={11} />
                      </button>
                    ))}
                  </div>
                )}

                <div className="relative group">
                  <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-on-surface-variant/40 group-focus-within:text-primary transition-colors" />
                  <input
                    type="text"
                    placeholder={
                      mode === 'personal'
                        ? t('findUser')
                        : t('addMembers')
                    }
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    className="w-full pl-12 pr-4 py-4 rounded-2xl bg-surface-container-highest/20 text-sm text-white placeholder-zinc-500 border border-white/5 focus:border-primary/40 outline-none transition-all focus:bg-surface-container-highest/30"
                    autoFocus
                  />
                </div>
              </div>

              {/* Результаты */}
              <div className="max-h-72 overflow-y-auto px-2 pb-4">
                {isLoading ? (
                  <div className="flex justify-center py-8">
                    <div className="w-5 h-5 border-2 border-knot-500 border-t-transparent rounded-full animate-spin" />
                  </div>
                ) : query.trim().length >= 3 && users.length > 0 ? (
                  <div className="space-y-1 px-1">
                    {users.map((u) => (
                      <button
                        key={u.id}
                        onClick={() => handleSelectUser(u)}
                        className={`w-full flex items-center gap-4 px-4 py-3 rounded-2xl transition-all active:scale-[0.98] ${
                          isSelected(u.id)
                            ? 'bg-primary/10 border border-primary/20'
                            : 'hover:bg-white/5 border border-transparent'
                        }`}
                      >
                        <div className="relative flex-shrink-0">
                          {u.avatar ? (
                            <img src={u.avatar} alt="" className="w-11 h-11 rounded-2xl object-cover" />
                          ) : (
                            <div className="w-11 h-11 rounded-2xl bg-linear-to-br from-primary to-primary-container flex items-center justify-center text-on-primary font-black text-sm shadow-inner">
                              {getInitials(u.displayName || u.userName || u.username || '?')}
                            </div>
                          )}
                          {u.isOnline && (
                            <span className="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 bg-emerald-500 rounded-full border-[3px] border-surface-container shadow-lg" />
                          )}
                        </div>
                        <div className="min-w-0 text-left flex-1">
                          <p className="text-[14px] font-bold text-white/90 truncate">
                            {u.displayName || u.userName || u.username || ''}
                          </p>
                          <p className="text-[11px] text-zinc-500 font-medium truncate">@{u.userName || u.username || ''}</p>
                        </div>
                        {mode === 'group-select' && (
                          <div className={`w-6 h-6 rounded-lg border-2 flex items-center justify-center flex-shrink-0 transition-all ${
                            isSelected(u.id)
                              ? 'bg-primary border-primary shadow-[0_0_15px_rgba(154,203,255,0.3)]'
                              : 'border-white/10'
                          }`}>
                            {isSelected(u.id) && <Check size={14} className="text-on-primary" strokeWidth={4} />}
                          </div>
                        )}
                      </button>
                    ))}
                  </div>
                ) : query.trim().length >= 3 && users.length === 0 ? (
                  <div className="text-center py-8 text-zinc-500">
                    <p className="text-sm">{t('usersNotFound')}</p>
                  </div>
                ) : query.trim().length > 0 && query.trim().length < 3 ? (
                  <div className="text-center py-6 text-zinc-500">
                    <p className="text-sm">{t('minCharsHint')}</p>
                  </div>
                ) : friends.length > 0 ? (
                  <>
                    <p className="text-[10px] text-zinc-500 uppercase tracking-[0.2em] px-4 mb-3 font-bold">{t('friends')}</p>
                    <div className="space-y-1 px-1">
                      {friends.map((u) => (
                        <button
                          key={u.id}
                          onClick={() => handleSelectUser(u)}
                          className={`w-full flex items-center gap-4 px-4 py-3 rounded-2xl transition-all active:scale-[0.98] ${
                            isSelected(u.id)
                              ? 'bg-primary/10 border border-primary/20'
                              : 'hover:bg-white/5 border border-transparent'
                          }`}
                        >
                          <div className="relative flex-shrink-0">
                            {u.avatar ? (
                              <img src={u.avatar} alt="" className="w-11 h-11 rounded-2xl object-cover" />
                            ) : (
                              <div className="w-11 h-11 rounded-2xl bg-linear-to-br from-primary to-primary-container flex items-center justify-center text-on-primary font-black text-sm shadow-inner">
                                {getInitials(u.displayName || u.userName || u.username || '?')}
                              </div>
                            )}
                            {u.isOnline && (
                              <span className="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 bg-emerald-500 rounded-full border-[3px] border-surface-container shadow-lg" />
                            )}
                          </div>
                          <div className="min-w-0 text-left flex-1">
                            <p className="text-[14px] font-bold text-white/90 truncate">
                              {u.displayName || u.userName || u.username || ''}
                            </p>
                            <p className="text-[11px] text-zinc-500 font-medium truncate">@{u.userName || u.username || ''}</p>
                          </div>
                          {mode === 'group-select' && (
                            <div className={`w-6 h-6 rounded-lg border-2 flex items-center justify-center flex-shrink-0 transition-all ${
                              isSelected(u.id)
                                ? 'bg-primary border-primary shadow-[0_0_15px_rgba(154,203,255,0.3)]'
                                : 'border-white/10'
                            }`}>
                              {isSelected(u.id) && <Check size={14} className="text-on-primary" strokeWidth={4} />}
                            </div>
                          )}
                        </button>
                      ))}
                    </div>
                  </>
                ) : (
                  <div className="flex flex-col items-center gap-2 py-8 text-zinc-500">
                    <MessageSquare size={32} className="opacity-30" />
                    <p className="text-sm">{t('enterNameOrUsername')}</p>
                  </div>
                )}
              </div>

              {/* Кнопка "Далее" для группы */}
              {mode === 'group-select' && selectedUsers.length > 0 && (
                <div className="p-4 border-t border-border">
                  <button
                    onClick={() => setMode('group-name')}
                    className="w-full py-2.5 rounded-xl bg-accent hover:bg-accent-hover text-white text-sm font-medium transition-colors flex items-center justify-center gap-2"
                  >
                    {t('next')}
                    <ArrowRight size={16} />
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </motion.div>
    </>
  );
}
