import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { motion } from 'framer-motion';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { getSpotifyAuthUrl } from '../utils/spotify';
import { apiPostForm, apiGet, apiPost } from '../utils/api';
import { useStore } from '../store/useStore';

// Global flag to prevent multiple executions across all instances
let globalProcessingFlag = false;

export const CallbackPage = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { setCurrentUser, setPartnerUser, currentUser } = useStore();
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
  const [message, setMessage] = useState('');

  useEffect(() => {
    const handleCallback = async () => {
      // Prevent multiple executions using global flag
      if (globalProcessingFlag) {
        console.log('🔍 CallbackPage - Already processing globally, skipping...');
        return;
      }
      
      globalProcessingFlag = true;
      console.log('🔍 CallbackPage - Global processing flag set to TRUE');
      
      try {
        const code = searchParams.get('code');
        const error = searchParams.get('error');

        console.log('🔍 CallbackPage - Code:', code);
        console.log('🔍 CallbackPage - Error:', error);

        if (error) {
          throw new Error('Spotify authorization was denied');
        }

        if (!code) {
          throw new Error('No authorization code received');
        }

        setMessage('Exchanging authorization code...');
        
        // Exchange code for tokens via backend
        console.log('🔍 CallbackPage - Exchanging code with backend...');
        const exchangeResp = await apiPostForm<{ token: string; uid: string; access_token: string; refresh_token: string }>(
          '/auth/exchange',
          { code }
        );

        setMessage('Syncing your music data...');
        await apiPost(`/users/${exchangeResp.uid}/sync`, undefined, exchangeResp.token);

        setMessage('Loading your profile...');
        const [userProfile, recentlyPlayed, topTracks] = await Promise.all([
          apiGet(`/users/${exchangeResp.uid}`),
          apiGet(`/users/${exchangeResp.uid}/recently-played`),
          apiGet(`/users/${exchangeResp.uid}/top-tracks?time_range=short_term`),
        ]);

        const userState = {
          user: userProfile,
          accessToken: exchangeResp.access_token,
          refreshToken: exchangeResp.refresh_token,
          isAuthenticated: true,
          recentlyPlayed,
          topTracks: topTracks.map((item: any) => item.track),
          topArtists: [], // Will be fetched separately if needed
          jwt: exchangeResp.token,
        };

        // Store user data
        localStorage.setItem('spotify-user', JSON.stringify(userState));
        
        // Determine if this is the current user or partner
        if (!currentUser) {
          setCurrentUser(userState);
          setMessage('Welcome! Setting up your musical journey...');
        } else {
          setPartnerUser(userState);
          localStorage.setItem('spotify-partner', JSON.stringify(userState));
          setMessage('Partner connected! Your musical journey begins...');
        }

        setStatus('success');
        toast.success(
          !currentUser ? 'Successfully connected to Spotify!' : 'Partner connected successfully!',
          { duration: 3000 }
        );

        // Redirect after a short delay
        setTimeout(() => {
          navigate('/');
          // Reset flag only after navigation
          setTimeout(() => {
            globalProcessingFlag = false;
            console.log('🔍 CallbackPage - Global processing flag set to FALSE (after success)');
          }, 1000);
        }, 2000);

      } catch (error) {
        console.error('🔍 CallbackPage - ERROR:', error);
        console.error('🔍 CallbackPage - Error details:', {
          message: error instanceof Error ? error.message : 'Unknown error',
          stack: error instanceof Error ? error.stack : undefined
        });
        setStatus('error');
        setMessage(error instanceof Error ? error.message : 'An unexpected error occurred');
        toast.error('Failed to connect to Spotify. Please try again.');
        
        setTimeout(() => {
          navigate('/');
          // Reset flag only after navigation
          setTimeout(() => {
            globalProcessingFlag = false;
            console.log('🔍 CallbackPage - Global processing flag set to FALSE (after error)');
          }, 1000);
        }, 3000);
      }
    };

    handleCallback();
  }, [searchParams, navigate, setCurrentUser, setPartnerUser, currentUser]);

  const getStatusIcon = () => {
    switch (status) {
      case 'loading':
        return <Loader2 className="w-12 h-12 text-spotify-green animate-spin" />;
      case 'success':
        return <CheckCircle className="w-12 h-12 text-green-400" />;
      case 'error':
        return <XCircle className="w-12 h-12 text-red-400" />;
    }
  };

  const getStatusColor = () => {
    switch (status) {
      case 'loading':
        return 'border-spotify-green/30';
      case 'success':
        return 'border-green-400/30';
      case 'error':
        return 'border-red-400/30';
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center px-4 bg-black">
      <motion.div
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        className="glass-fluid rounded-3xl p-10 max-w-md w-full text-center"
      >
        <motion.div
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
          className={`w-20 h-20 mx-auto mb-6 rounded-full border-2 flex items-center justify-center ${getStatusColor()}`}
        >
          {getStatusIcon()}
        </motion.div>

        <motion.h2
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="text-2xl font-bold text-white mb-4"
        >
          {status === 'loading' && 'Connecting...'}
          {status === 'success' && 'Success!'}
          {status === 'error' && 'Connection Failed'}
        </motion.h2>

        <motion.p
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="text-white/70 mb-6"
        >
          {message}
        </motion.p>

        {status === 'loading' && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
            className="w-full bg-white/10 rounded-full h-2 mb-4"
          >
            <motion.div
              className="bg-spotify-green h-2 rounded-full"
              initial={{ width: 0 }}
              animate={{ width: '100%' }}
              transition={{ duration: 3, ease: "easeInOut" }}
            />
          </motion.div>
        )}

        {status === 'error' && (
          <motion.button
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={() => navigate('/')}
            className="bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300"
          >
            Try Again
          </motion.button>
        )}

        {status === 'success' && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="text-spotify-green text-sm"
          >
            Redirecting you to your musical journey...
          </motion.div>
        )}
      </motion.div>
    </div>
  );
};
