import React, { useEffect } from 'react';
import { ChatSidebar } from '../components/ChatSidebar';
import { ChatRoom } from '../components/ChatRoom';
import { ChatInput } from '../components/ChatInput';
import { useChatStore } from '../store/chatStore';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useUser } from '@/features/auth/hooks/useUser';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import { Loader2, AlertCircle } from 'lucide-react';
import { env } from '@/config/env';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';

export const ChatPage: React.FC = () => {
  const { isAuthenticated } = useAuthStore();
  const { data: user } = useUser();
  const userId = user?.id;
  const { setWsToken, currentConversationId, wsStatus } = useChatStore();

  const {
    data: wsTokenResponse,
    isLoading: isTokenLoading,
    error: tokenError,
  } = useQuery({
    queryKey: ['chatWsToken', userId],
    queryFn: async () => {
      if (!isAuthenticated || !userId) return null;
      const response = await apiClient.post('/chat/token', {});
      return response.data;
    },
    enabled: isAuthenticated && !!userId && wsStatus === 'disconnected',
    refetchOnWindowFocus: false,
    retry: false,
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });

  useEffect(() => {
    if (wsTokenResponse?.token) {
      const needsUpdate =
        wsTokenResponse.token !== useChatStore.getState().wsToken ||
        env.WS_URL !== useChatStore.getState().wsUrl;

      if (needsUpdate) {
        setWsToken(wsTokenResponse.token, env.WS_URL);
      }
    }
  }, [wsTokenResponse, setWsToken]);

  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center h-[calc(100vh-100px)] text-kodo-secondary glass-hud rounded-2xl">
        <div className="p-8 text-center max-w-md">
          <AlertCircle className="w-12 h-12 text-kodo-cyan mx-auto mb-4 opacity-50" />
          <h2 className="text-xl font-bold text-white mb-2">
            Access Restricted
          </h2>
          <p className="mb-6">
            Authorization required to access secure communication channels.
          </p>
          <Button
            variant="default"
            onClick={() => (window.location.href = '/login')}
          >
            Initialize Login
          </Button>
        </div>
      </div>
    );
  }

  if (isTokenLoading || wsStatus === 'connecting') {
    return (
      <div className="flex flex-col items-center justify-center h-[calc(100vh-100px)] glass-hud rounded-2xl">
        <div className="relative">
          <div className="w-16 h-16 border-4 border-kodo-cyan/20 border-t-kodo-cyan rounded-full animate-spin" />
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-2 h-2 bg-kodo-cyan rounded-full animate-pulse" />
          </div>
        </div>
        <p className="mt-6 text-sm font-mono text-kodo-cyan animate-pulse uppercase tracking-widest">
          Establishing Uplink...
        </p>
      </div>
    );
  }

  if (tokenError) {
    return (
      <div className="flex flex-col items-center justify-center h-[calc(100vh-100px)] glass-hud rounded-2xl border-kodo-red/20">
        <AlertCircle className="w-12 h-12 text-kodo-red mb-4" />
        <h2 className="text-xl font-bold text-white mb-2">
          Connection Failure
        </h2>
        <p className="text-kodo-red/80 max-w-md text-center">
          {(tokenError as any).message ||
            'Unable to retrieve secure token via Handshake Protocol.'}
        </p>
      </div>
    );
  }

  return (
    <div className="h-[calc(100vh-theme(spacing.24))] flex gap-6 overflow-hidden animate-fadeIn">
      {/* Sidebar Container */}
      <div className="w-80 shrink-0 flex flex-col glass-hud rounded-2xl border-white/5 overflow-hidden">
        <ChatSidebar />
      </div>

      {/* Chat Area Container */}
      <div className="flex-1 flex flex-col glass-hud rounded-2xl border-white/5 overflow-hidden relative">
        {/* Background Grid Effect */}
        <div
          className="absolute inset-0 opacity-[0.02] pointer-events-none"
          style={{
            backgroundImage:
              'linear-gradient(rgba(102, 252, 241, 0.5) 1px, transparent 1px), linear-gradient(90deg, rgba(102, 252, 241, 0.5) 1px, transparent 1px)',
            backgroundSize: '20px 20px',
          }}
        />

        <div className="flex-1 overflow-hidden flex flex-col relative z-10">
          <ChatRoom conversationId={currentConversationId || ''} />
        </div>

        <div className="p-4 border-t border-white/5 bg-black/20 backdrop-blur-xl relative z-20">
          <ChatInput />
        </div>
      </div>
    </div>
  );
};
