import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Search,
  Plus,
  Menu,
  MessageSquare,
  X,
  User as UserIcon,
} from 'lucide-react';
import { useAuthStore } from '../../../modules/auth/application/authStore';
import { useChatStore } from '../../../modules/chats/application/chatStore';
import { useNotificationStore } from '../../application/stores/notificationStore';
import { useLang } from '../../infrastructure/i18n';
import { useFriendStore } from '../../../modules/friends/application/friendStore';
import { StoryApi } from '../../../modules/stories/infrastructure/storyApi';
import { getSocket } from '../../infrastructure/socket';
import { getInitials, generateAvatarColor } from '../../utils/utils';
import Avatar from '../components/ui/Avatar';
import { StoryGroup } from '../../domain/types';
import ChatListItem from '../../../modules/chats/presentation/components/ChatListItem';
import NewChatModal from '../../../modules/chats/presentation/components/NewChatModal';
import UserProfile from '../../../modules/users/presentation/components/UserProfile';
import SideMenu from './SideMenu';
import StoryViewer from '../../../modules/stories/presentation/components/StoryViewer';
import { CreateStoryModal } from '../../../modules/stories/presentation/components/CreateStoryModal';
import { useStoryStore } from '../../../modules/stories/application/storyStore';
import TelegramImportModal from '../../../modules/users/presentation/components/TelegramImportModal';

const API_URL = import.meta.env.VITE_API_URL || '';

export default function Sidebar() {
  const { user, logout } = useAuthStore();
  const { chats, activeChat, searchQuery, setSearchQuery, clearStore } = useChatStore();
  const { t } = useLang();
  const [showNewChat, setShowNewChat] = useState(false);
  const [showProfile, setShowProfile] = useState(false);
  const [showSideMenu, setShowSideMenu] = useState(false);
  const { storyGroups, setStoryGroups, viewerIndex, viewerStoryIndex, openViewer, closeViewer } = useStoryStore();
  const [showCreateStory, setShowCreateStory] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const { friends, loadFriends } = useFriendStore();

  const loadStories = () => {
    StoryApi.getStories()
      .then(setStoryGroups)
      .catch((err) => {
        console.error(err);
        const { addNotification } = useNotificationStore.getState();
        addNotification('error', (t('loadStoriesError') || 'Failed to load stories') as string);
      });
  };

  useEffect(() => {
    loadStories();
    const interval = setInterval(loadStories, 30000); // refresh every 30s
    
    const socket = getSocket();
    const onStoryViewed = (data: any) => {
      // Refresh stories if I'm the owner or the viewer
      if (data.ownerId === user?.id || data.userId === user?.id) {
        loadStories();
      }
    };
    
    socket?.on('story_viewed', onStoryViewed);
    
    const handleOpenNewChat = () => setShowNewChat(true);
    const handleOpenSideMenu = () => setShowSideMenu(true);
    const handleOpenImport = () => { loadFriends(); setShowImportModal(true); };
    window.addEventListener('OPEN_NEW_CHAT', handleOpenNewChat);
    window.addEventListener('OPEN_SIDE_MENU', handleOpenSideMenu);
    window.addEventListener('OPEN_TELEGRAM_IMPORT', handleOpenImport);

    return () => {
      clearInterval(interval);
      socket?.off('story_viewed', onStoryViewed);
      window.removeEventListener('OPEN_NEW_CHAT', handleOpenNewChat);
      window.removeEventListener('OPEN_SIDE_MENU', handleOpenSideMenu);
      window.removeEventListener('OPEN_TELEGRAM_IMPORT', handleOpenImport);
    };
  }, [user?.id]);

  const filteredChats = chats.filter((chat) => {
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    if (chat.name?.toLowerCase().includes(q)) return true;
    return chat.members.some(
      (m) =>
        m.user?.id !== user?.id &&
        ((m.user?.username || m.user?.userName || '').toLowerCase().includes(q) ||
          (m.user?.displayName || '').toLowerCase().includes(q))
    );
  }).sort((a, b) => {
    // 1. Favorites chat always on top
    if (a.type === 'favorites') return -1;
    if (b.type === 'favorites') return 1;
    
    // 2. Pinned chats next
    const aPinned = a.members?.find(m => m.user?.id === user?.id)?.isPinned ?? false;
    const bPinned = b.members?.find(m => m.user?.id === user?.id)?.isPinned ?? false;
    if (aPinned && !bPinned) return -1;
    if (!aPinned && bPinned) return 1;
    
    // 3. Importing chats next
    if (a.isImporting && !b.isImporting) return -1;
    if (!a.isImporting && b.isImporting) return 1;
    
    // 4. Last message timestamp or CreatedAt
    const aTime = new Date(a.messages?.[0]?.createdAt || a.createdAt).getTime();
    const bTime = new Date(b.messages?.[0]?.createdAt || b.createdAt).getTime();
    return bTime - aTime;
  });

  const handleLogout = () => {
    clearStore();
    logout();
  };

  return (
    <>
      <div className="w-full h-full flex flex-col bg-surface-container-low overflow-hidden border-none relative z-10 slide-on-ice">
        {/* Title Section (Minimal) */}
        <div className="px-6 py-8 pb-4 flex items-center justify-between">
          <h1 className="text-2xl font-bold font-headline text-white tracking-tight leading-none">{t('chats')}</h1>
          <button 
            onClick={() => setShowSideMenu(true)}
            className="p-2 rounded-xl text-zinc-400 hover:text-white hover:bg-white/10 transition-all"
          >
            <Menu size={22} />
          </button>
        </div>

        {/* Search */}
        <div className="px-6 mb-4">
          <div className="relative group">
            <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-on-surface-variant/40 group-focus-within:text-primary transition-colors text-[20px]">search</span>
            <input
              type="text"
              placeholder={t('searchChats')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-12 pr-4 py-3 rounded-xl bg-surface-container-highest text-sm text-on-surface placeholder-on-surface-variant/30 border-none focus:ring-2 focus:ring-primary/20 hover:bg-surface-bright transition-all outline-none"
            />
          </div>
        </div>

        {/* Stories Section */}
        <div className="px-6 mb-2">
          <h2 className="text-[11px] font-black text-on-surface-variant/40 uppercase tracking-[0.12em] select-none">
            {t('stories')}
          </h2>
        </div>

        <div className="flex items-center gap-4 px-6 py-2 pb-6 overflow-x-auto scrollbar-hide flex-shrink-0">
          {/* Add story item */}
          <button
            onClick={() => setShowCreateStory(true)}
            className="flex flex-col items-center gap-2 flex-shrink-0 group w-[62px]"
          >
            <div className="w-[56px] h-[56px] rounded-2xl border-2 border-dashed border-white/10 flex items-center justify-center group-hover:border-accent group-hover:bg-accent/5 transition-all">
              <Plus size={22} className="text-accent/80 group-hover:text-accent transition-colors" />
            </div>
            <span className="text-[12px] font-medium text-zinc-400 group-hover:text-white transition-colors truncate w-full text-center">
              {t('add')}
            </span>
          </button>

          {storyGroups.map((group, idx) => {
            const avatar = group.user.avatarUrl || group.user.avatar;
            const avatarUrl = avatar ? `${API_URL}${avatar}` : null;
            const isMine = group.user.id === user?.id;
            return (
              <button
                key={group.user.id}
                onClick={() => openViewer(idx)}
                className="flex flex-col items-center gap-2 flex-shrink-0 group w-[62px]"
              >
                <div className={`relative p-[1.5px] rounded-[1.25rem] transition-all duration-300 ${
                  group.hasUnviewed
                    ? 'bg-accent shadow-[0_0_15px_rgba(48,150,229,0.2)] scale-[1.02]'
                    : 'bg-white/5'
                }`}>
                  <div className="w-[53px] h-[53px] rounded-[1.125rem] bg-surface-container-low p-1 flex items-center justify-center">
                    <div className="relative w-full h-full rounded-[0.9rem] overflow-hidden">
                      <Avatar
                        src={avatarUrl}
                        name={group.user.displayName || group.user.userName || group.user.username || '?'}
                        size="md"
                      />
                    </div>
                  </div>
                </div>
                <span className="text-[12px] font-medium text-zinc-400 group-hover:text-white transition-colors truncate w-full text-center">
                  {isMine ? t('myStory') : (group.user.displayName || group.user.userName || group.user.username || '?').split(' ')[0]}
                </span>
              </button>
            );
          })}
        </div>

        {/* Список чатов */}
        <div className="flex-1 overflow-y-auto px-2 custom-scrollbar pb-28 lg:pb-4">
          {filteredChats.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-on-surface-variant/40 gap-3 px-6">
              <span className="material-symbols-outlined text-5xl opacity-20">chat_bubble</span>
              <p className="text-sm text-center">
                {searchQuery ? t('nothingFound') : t('noChats')}
              </p>
            </div>
          ) : (
            filteredChats.map((chat) => (
              <ChatListItem key={chat.id} chat={chat} isActive={chat.id === activeChat} />
            ))
          )}
        </div>

        {/* Float Action Button equivalent for Web */}
        <button
          onClick={() => setShowNewChat(true)}
          className="absolute bottom-20 lg:bottom-10 right-4 lg:right-10 w-12 h-12 lg:w-16 lg:h-16 rounded-2xl lg:rounded-3xl bg-primary text-black shadow-[0_10px_30px_-5px_rgba(var(--primary-rgb),0.4)] flex items-center justify-center hover:scale-105 active:scale-95 transition-all slide-on-ice z-30"
          title={t('newChat')}
        >
          <span className="material-symbols-outlined text-2xl lg:text-3xl">add</span>
        </button>
      </div>

      {/* Модалки */}
      <AnimatePresence>
        {showNewChat && <NewChatModal onClose={() => setShowNewChat(false)} onOpenTelegramImport={() => { loadFriends(); setShowImportModal(true); }} />}
      </AnimatePresence>
      <AnimatePresence>
        {showProfile && user && <UserProfile userId={user.id} onClose={() => setShowProfile(false)} isSelf />}
      </AnimatePresence>
      <SideMenu
        isOpen={showSideMenu}
        onClose={() => setShowSideMenu(false)}
        onOpenProfile={() => setShowProfile(true)}
        onOpenTelegramImport={() => { loadFriends(); setShowImportModal(true); }}
      />
      <TelegramImportModal
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        friends={friends}
      />
      <AnimatePresence>
        {viewerIndex !== null && storyGroups.length > 0 && (
          <StoryViewer
            stories={storyGroups}
            initialUserIndex={viewerIndex}
            initialStoryIndex={viewerStoryIndex}
            onClose={() => { closeViewer(); loadStories(); }}
            onRefresh={loadStories}
          />
        )}
      </AnimatePresence>
      <AnimatePresence>
        {showCreateStory && (
          <CreateStoryModal
            onClose={() => setShowCreateStory(false)}
            onCreated={loadStories}
          />
        )}
      </AnimatePresence>
    </>
  );
}
