import { useState, useEffect, useMemo } from 'react';
import { motion } from 'framer-motion';
import { 
  Play, 
  Pause, 
  Heart, 
  Clock, 
  User, 
  Music,
  Volume2,
  ExternalLink
} from 'lucide-react';
import { useStore } from '../store/useStore';
import { playTrack, pausePlayback, getCurrentPlayback } from '../utils/spotify';
import { formatDate, formatDuration } from '../utils/cn';
import { getThemeClasses } from '../utils/theme';
import toast from 'react-hot-toast';

export const LastListenedPage = () => {
  const { currentUser, partnerUser, currentTrack, isPlaying, setCurrentTrack, setIsPlaying, theme } = useStore();
  const themeClasses = getThemeClasses(theme);
  const [isLoading, setIsLoading] = useState(false);
  const [playingTrackId, setPlayingTrackId] = useState<string | null>(null);

  const sharedTimeline = useMemo(() => {
    const a = (currentUser?.recentlyPlayed || []).map((x: any) => ({
      who: 'you',
      played_at: new Date(x.played_at).getTime(),
      track: x.track,
      key: `you-${x.track.id}-${x.played_at}`,
    }));
    const b = (partnerUser?.recentlyPlayed || []).map((x: any) => ({
      who: 'partner',
      played_at: new Date(x.played_at).getTime(),
      track: x.track,
      key: `partner-${x.track.id}-${x.played_at}`,
    }));
    const merged = [...a, ...b].sort((x, y) => y.played_at - x.played_at).slice(0, 30);
    const seenIds = new Set<string>();
    const overlaps = new Set<string>();
    merged.forEach(item => {
      const id = item.track.id;
      if (seenIds.has(id)) overlaps.add(id); else seenIds.add(id);
    });
    return { items: merged, overlaps };
  }, [currentUser?.recentlyPlayed, partnerUser?.recentlyPlayed]);

  const handlePlayTrack = async (trackUri: string, trackId: string) => {
    if (!currentUser?.accessToken) {
      toast.error('Not authenticated with Spotify');
      return;
    }

    try {
      setIsLoading(true);
      setPlayingTrackId(trackId);
      
      if (isPlaying && playingTrackId === trackId) {
        await pausePlayback(currentUser.accessToken);
        setIsPlaying(false);
        setCurrentTrack(null);
        setPlayingTrackId(null);
      } else {
        await playTrack(currentUser.accessToken, trackUri);
        setIsPlaying(true);
        setCurrentTrack(currentUser.recentlyPlayed?.find(item => item.track.id === trackId)?.track || null);
      }
      
      toast.success(isPlaying && playingTrackId === trackId ? 'Paused' : 'Now playing');
    } catch (error) {
      console.error('Playback error:', error);
      toast.error('Failed to play track. Make sure Spotify is open on your device.');
    } finally {
      setIsLoading(false);
    }
  };

  const UserSection = ({ 
    user, 
    title, 
    isPartner = false 
  }: { 
    user: any; 
    title: string; 
    isPartner?: boolean;
  }) => {
    if (!user?.recentlyPlayed?.length) {
      return (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass rounded-2xl p-8 text-center"
        >
          <Music className="w-16 h-16 mx-auto mb-4 text-white/30" />
          <h3 className="text-xl font-semibold text-white mb-2">No recent activity</h3>
          <p className="text-white/70">
            {isPartner ? 'Your partner' : 'You'} haven't played any music recently
          </p>
        </motion.div>
      );
    }

    const recentTrack = user.recentlyPlayed[0];

    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="glass rounded-2xl p-6"
      >
        <div className="flex items-center space-x-4 mb-6">
          <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
            isPartner ? 'bg-gradient-to-br from-pink-500 to-purple-600' : 'bg-gradient-to-br from-blue-500 to-cyan-600'
          }`}>
            <User className="w-6 h-6 text-white" />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-white">{title}</h2>
            <p className="text-white/70">
              Last played: {formatDate(recentTrack.played_at)}
            </p>
          </div>
        </div>

        {/* Current Track Card */}
        <motion.div
          whileHover={{ scale: 1.02 }}
          className="bg-white/5 rounded-xl p-6 mb-6 border border-white/10"
        >
          <div className="flex items-center space-x-6">
            <div className="relative">
              <img
                src={recentTrack.track.album.images[0]?.url || '/placeholder-album.png'}
                alt={recentTrack.track.album.name}
                className="w-20 h-20 rounded-lg object-cover"
              />
              {isPlaying && playingTrackId === recentTrack.track.id && (
                <div 
                  className="absolute inset-0 rounded-lg flex items-center justify-center"
                  style={{ backgroundColor: `${themeClasses.cssVars?.primary || '#1db954'}20` }}
                >
                  <Volume2 
                    className="w-6 h-6" 
                    style={{ color: themeClasses.cssVars?.primary || '#1db954' }}
                  />
                </div>
              )}
            </div>
            
            <div className="flex-1">
              <h3 className="text-xl font-semibold text-white mb-1">
                {recentTrack.track.name}
              </h3>
              <p className="text-white/70 mb-2">
                {recentTrack.track.artists.map(artist => artist.name).join(', ')}
              </p>
              <p className="text-white/50 text-sm">
                {recentTrack.track.album.name} • {formatDuration(recentTrack.track.duration_ms)}
              </p>
            </div>

            <div className="flex items-center space-x-3">
              <button
                onClick={() => handlePlayTrack(recentTrack.track.external_urls.spotify, recentTrack.track.id)}
                disabled={isLoading}
                className="w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300 text-white disabled:opacity-50"
                style={{
                  backgroundColor: isPlaying && playingTrackId === recentTrack.track.id
                    ? '#ef4444' // Red for pause
                    : themeClasses.cssVars?.primary || '#1db954',
                }}
                onMouseEnter={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.opacity = '0.9';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!isLoading) {
                    e.currentTarget.style.opacity = '1';
                  }
                }}
              >
                {isLoading && playingTrackId === recentTrack.track.id ? (
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                ) : isPlaying && playingTrackId === recentTrack.track.id ? (
                  <Pause className="w-5 h-5" />
                ) : (
                  <Play className="w-5 h-5 ml-0.5" />
                )}
              </button>

              <a
                href={recentTrack.track.external_urls.spotify}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
              >
                <ExternalLink className="w-4 h-4 text-white" />
              </a>
            </div>
          </div>
        </motion.div>

        {/* Recent History */}
        <div>
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
            <Clock className="w-5 h-5" />
            <span>Recent History</span>
          </h3>
          
          <div className="space-y-3">
            {user.recentlyPlayed.slice(0, 5).map((item, index) => (
              <motion.div
                key={item.track.id}
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: index * 0.1 }}
                className="flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors group"
              >
                <img
                  src={item.track.album.images[0]?.url || '/placeholder-album.png'}
                  alt={item.track.album.name}
                  className="w-12 h-12 rounded-lg object-cover"
                />
                
                <div className="flex-1">
                  <h4 className="text-white font-medium group-hover:text-spotify-green transition-colors">
                    {item.track.name}
                  </h4>
                  <p className="text-white/70 text-sm">
                    {item.track.artists[0]?.name}
                  </p>
                </div>
                
                <div className="text-white/50 text-sm">
                  {formatDate(item.played_at)}
                </div>

                <button
                  onClick={() => handlePlayTrack(item.track.external_urls.spotify, item.track.id)}
                  disabled={isLoading}
                  className="opacity-0 group-hover:opacity-100 w-8 h-8 rounded-full flex items-center justify-center transition-all disabled:opacity-50"
                  style={{
                    backgroundColor: themeClasses.cssVars?.primary || '#1db954',
                  }}
                  onMouseEnter={(e) => {
                    if (!isLoading) {
                      e.currentTarget.style.opacity = '0.9';
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (!isLoading) {
                      e.currentTarget.style.opacity = '1';
                    }
                  }}
                >
                  <Play className="w-4 h-4 text-white ml-0.5" />
                </button>
              </motion.div>
            ))}
          </div>
        </div>
      </motion.div>
    );
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="mb-8"
      >
        <h1 className="text-4xl font-bold text-white mb-2 flex items-center space-x-3">
          <Heart 
            className="w-10 h-10" 
            style={{ color: themeClasses.cssVars?.primary || '#1db954' }}
          />
          <span>What's Playing</span>
        </h1>
        <p className="text-white/70 text-lg">
          Discover what you and your partner are listening to right now
        </p>
      </motion.div>

      <div className="grid lg:grid-cols-2 gap-8">
        {currentUser && (
          <UserSection
            user={currentUser}
            title={`${currentUser.user?.display_name}'s Music`}
            isPartner={false}
          />
        )}

        {partnerUser && (
          <UserSection
            user={partnerUser}
            title={`${partnerUser.user?.display_name}'s Music`}
            isPartner={true}
          />
        )}

        {!partnerUser && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="glass rounded-2xl p-8 text-center"
          >
            <Heart className="w-16 h-16 mx-auto mb-4 text-pink-400" />
            <h3 className="text-xl font-semibold text-white mb-2">Waiting for your partner</h3>
            <p className="text-white/70 mb-4">
              Invite your partner to connect their Spotify account to see their music
            </p>
            <button className="bg-pink-500 hover:bg-pink-600 text-white px-6 py-3 rounded-lg transition-colors">
              Send Invitation
            </button>
          </motion.div>
        )}
      </div>

      {/* Shared Timeline */}
      {currentUser && partnerUser && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass rounded-2xl p-8 mt-8"
        >
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center space-x-2">
            <Clock className="w-5 h-5" />
            <span>Shared Timeline</span>
          </h3>
          <div className="space-y-3">
            {sharedTimeline.items.map((item) => (
              <div key={item.key} className="flex items-center gap-4 p-3 rounded-lg bg-white/5">
                <img
                  src={item.track.album?.images?.[0]?.url || '/placeholder-album.png'}
                  alt={item.track.album?.name || 'Album'}
                  className="w-10 h-10 rounded"
                />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-white font-medium truncate">{item.track.name}</span>
                    {sharedTimeline.overlaps.has(item.track.id) && (
                      <span className="text-pink-400 text-sm">💕</span>
                    )}
                  </div>
                  <div className="text-white/70 text-sm truncate">{item.track.artists?.map((a: any) => a.name).join(', ')}</div>
                </div>
                <div className="text-white/50 text-xs w-32 text-right">
                  {formatDate(new Date(item.played_at).toISOString())}
                  <div className="text-white/60">{item.who === 'you' ? 'You' : 'Partner'}</div>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </div>
  );
};
