import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { apiGet, apiPost } from '../utils/api';
import toast from 'react-hot-toast';
import { 
  Music, 
  PlayCircle, 
  Sparkles, 
  Heart, 
  Clock, 
  TrendingUp,
  User,
  Plus
} from 'lucide-react';
import { useStore } from '../store/useStore';
import { formatDate } from '../utils/cn';
import { getThemeClasses } from '../utils/theme';

export const DashboardPage = () => {
  const { currentUser, partnerUser, theme } = useStore();
  const themeClasses = getThemeClasses(theme);
  const [incomingRequests, setIncomingRequests] = useState<any[]>([]);
  const [loadingReqs, setLoadingReqs] = useState(false);
  const [status, setStatus] = useState<{ lastSyncedAt: number | null; nextSyncAt: number | null } | null>(null);
  const [countdown, setCountdown] = useState<string>('');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [nowA, setNowA] = useState<any>(null);
  const [nowB, setNowB] = useState<any>(null);

  // Periodically refresh recently-played for both users to avoid stale local state
  useEffect(() => {
    let timer: any;
    const tick = async () => {
      try {
        const uid = currentUser?.user?.id;
        if (uid) {
          const meRecent = await apiGet(`/users/${uid}/recently-played`);
          // Update only the recentlyPlayed field to keep other state
          const state = useStore.getState().currentUser;
          if (state) useStore.getState().setCurrentUser({ ...state, recentlyPlayed: meRecent } as any);
        }
        const pid = useStore.getState().partnerUser?.user?.id;
        if (pid) {
          const partnerRecent = await apiGet(`/users/${pid}/recently-played`);
          const pstate = useStore.getState().partnerUser;
          if (pstate) useStore.getState().setPartnerUser({ ...pstate, recentlyPlayed: partnerRecent } as any);
        }
      } catch {}
      timer = setTimeout(tick, 30000);
    };
    tick();
    return () => clearTimeout(timer);
  }, [currentUser?.user?.id, partnerUser?.user?.id]);

  useEffect(() => {
    const fetchRequests = async () => {
      if (!currentUser?.user?.id) return;
      setLoadingReqs(true);
      try {
        const reqs = await apiGet(`/partners/requests/${currentUser.user.id}`);
        setIncomingRequests(reqs as any[]);
      } catch {
        setIncomingRequests([]);
      } finally {
        setLoadingReqs(false);
      }
    };
    fetchRequests();
  }, [currentUser?.user?.id]);

  useEffect(() => {
    let interval: any;
    const loadStatus = async () => {
      if (!currentUser?.user?.id) return;
      try {
        const s = await apiGet(`/users/${currentUser.user.id}/status`);
        setStatus(s as { lastSyncedAt: number | null; nextSyncAt: number | null });
      } catch {}
    };
    const updateCountdown = () => {
      if (!status?.nextSyncAt) { setCountdown(''); return; }
      const diff = status.nextSyncAt - Date.now();
      if (diff <= 0) { setCountdown('now'); return; }
      const m = Math.floor(diff / 60000);
      const s = Math.floor((diff % 60000) / 1000);
      setCountdown(`${m}m ${s}s`);
    };
    loadStatus();
    interval = setInterval(() => {
      updateCountdown();
    }, 1000);
    return () => clearInterval(interval);
  }, [currentUser?.user?.id, status?.nextSyncAt]);

  // Live now-playing polling
  useEffect(() => {
    let t: any;
    const poll = async () => {
      try {
        const uid = currentUser?.user?.id;
        if (uid) {
          setNowA(await apiGet(`/users/${uid}/now-playing`));
          if (partnerUser?.user?.id) {
            setNowB(await apiGet(`/users/${partnerUser.user.id}/now-playing`));
          } else {
            setNowB(null);
          }
        }
      } catch {}
      t = setTimeout(poll, 8000);
    };
    poll();
    return () => clearTimeout(t);
  }, [currentUser?.user?.id, partnerUser?.user?.id]);

  const hardRefresh = async () => {
    if (!currentUser?.user?.id) return;
    setIsRefreshing(true);
    try {
      await apiPost(`/users/${currentUser.user.id}/sync`);
      // re-fetch status
      const s = await apiGet(`/users/${currentUser.user.id}/status`);
      setStatus(s as { lastSyncedAt: number | null; nextSyncAt: number | null });
      // fetch fresh recent/top data into store
      const [meRecent, meTop] = await Promise.all([
        apiGet(`/users/${currentUser.user.id}/recently-played`),
        apiGet(`/users/${currentUser.user.id}/top-tracks?time_range=short_term`),
      ]);
      const cur = useStore.getState().currentUser;
      if (cur) useStore.getState().setCurrentUser({ ...cur, recentlyPlayed: meRecent, topTracks: (meTop as any[]).map((x: any) => x.track) } as any);
      toast.success('Synced latest data');
    } catch (e) {
      toast.error('Failed to sync');
    } finally {
      setIsRefreshing(false);
    }
  };

  const acceptRequest = async (id: number) => {
    await apiPost(`/partners/requests/${id}/accept`);
    setIncomingRequests(prev => prev.filter(r => r.id !== id));
  };

  const declineRequest = async (id: number) => {
    await apiPost(`/partners/requests/${id}/decline`);
    setIncomingRequests(prev => prev.filter(r => r.id !== id));
  };

  const features = [
    {
      title: 'Last Listened',
      description: 'See what your partner is listening to right now',
      icon: Music,
      href: '/last-listened',
      primaryColor: themeClasses.cssVars?.primary || '#1db954',
      secondaryColor: themeClasses.cssVars?.secondary || '#1ed760',
      accentColor: themeClasses.cssVars?.accent || '#00e676',
    },
    {
      title: 'Mixed Playlist',
      description: 'Create AI-powered playlists blending both your tastes',
      icon: PlayCircle,
      href: '/mixed-playlist',
      primaryColor: themeClasses.cssVars?.secondary || '#1ed760',
      secondaryColor: themeClasses.cssVars?.accent || '#00e676',
      accentColor: themeClasses.cssVars?.primary || '#1db954',
    },
    {
      title: 'Memory Lane',
      description: 'Your shared musical journey and memories',
      icon: Sparkles,
      href: '/memory-lane',
      primaryColor: themeClasses.cssVars?.accent || '#00e676',
      secondaryColor: themeClasses.cssVars?.primary || '#1db954',
      accentColor: themeClasses.cssVars?.secondary || '#1ed760',
    },
  ];

  const getLastPlayedTime = () => {
    if (!currentUser?.recentlyPlayed?.[0]) return null;
    return formatDate(currentUser.recentlyPlayed[0].played_at);
  };


  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Header */}
      <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">
          Welcome back, <span className="gradient-text">{currentUser?.user?.display_name}</span>
        </h1>
        <p className="text-white/70 text-lg">
          Ready to explore your musical connection together?
        </p>
      </motion.div>

      {/* Live Now Playing */}
      <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="grid md:grid-cols-2 gap-6 mb-8">
        <div className="glass rounded-2xl p-6">
          <div className="text-white/70 mb-2">You</div>
          {nowA?.is_playing && nowA?.item ? (
            <div className="flex items-center gap-4">
              <img src={nowA.item.album?.images?.[0]?.url || '/placeholder-album.png'} className="w-14 h-14 rounded" />
              <div className="min-w-0">
                <div className="text-white font-semibold truncate">{nowA.item.name}</div>
                <div className="text-white/70 text-sm truncate">{nowA.item.artists?.map((a: any) => a.name).join(', ')}</div>
              </div>
            </div>
          ) : (
            <div className="text-white/50">Not playing</div>
          )}
        </div>
        <div className="glass rounded-2xl p-6">
          <div className="text-white/70 mb-2">Partner</div>
          {nowB?.is_playing && nowB?.item ? (
            <div className="flex items-center gap-4">
              <img src={nowB.item.album?.images?.[0]?.url || '/placeholder-album.png'} className="w-14 h-14 rounded" />
              <div className="min-w-0">
                <div className="text-white font-semibold truncate">{nowB.item.name}</div>
                <div className="text-white/70 text-sm truncate">{nowB.item.artists?.map((a: any) => a.name).join(', ')}</div>
              </div>
            </div>
          ) : (
            <div className="text-white/50">Not playing</div>
          )}
        </div>
      </motion.div>

      {/* Connection Status & Controls */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="mb-8"
      >
        {/* Controls row */}
        <div className="flex items-center justify-between mb-4">
          <div className="text-white/70 text-sm">
            {status?.lastSyncedAt && (
              <span>Last sync: {new Date(status.lastSyncedAt).toLocaleTimeString()} • Next in: {countdown || '—'}</span>
            )}
          </div>
          <button
            onClick={hardRefresh}
            disabled={isRefreshing}
            className="bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-lg text-sm disabled:opacity-50"
          >
            {isRefreshing ? 'Refreshing…' : 'Hard Refresh'}
          </button>
        </div>
        {partnerUser ? (
          <div className="glass-bubble rounded-3xl p-8 border border-spotify-green/30 glow">
            <div className="flex items-center space-x-6">
              <div className="w-16 h-16 bg-gradient-to-br from-spotify-green to-green-600 rounded-2xl flex items-center justify-center">
                <Heart className="w-8 h-8 text-white" />
              </div>
              <div>
                <h3 className="text-xl font-semibold text-white">
                  Connected with {partnerUser.user?.display_name}
                </h3>
                <p className="text-white/70">
                  Your musical journey is ready to begin! 💕
                </p>
              </div>
            </div>
          </div>
        ) : (
          <div className="glass-bubble rounded-3xl p-8 border border-orange-500/30">
            <div className="flex items-center space-x-6">
              <div className="w-16 h-16 bg-gradient-to-br from-orange-500 to-red-500 rounded-2xl flex items-center justify-center">
                <Plus className="w-8 h-8 text-white" />
              </div>
              <div>
                <h3 className="text-xl font-semibold text-white">
                  Invite your partner
                </h3>
                <p className="text-white/70 mb-2">
                  Ask your partner to search you in the app and send a request.
                </p>
                {loadingReqs ? (
                  <div className="text-white/60">Loading requests...</div>
                ) : incomingRequests.length > 0 ? (
                  <div className="space-y-3">
                    {incomingRequests.map((r) => (
                      <div key={r.id} className="flex items-center justify-between bg-white/5 rounded-lg p-3">
                        <div className="text-white/80 text-sm">Request from {r.from_user_id}</div>
                        <div className="space-x-2">
                          <button onClick={() => acceptRequest(r.id)} className="bg-spotify-green hover:bg-spotify-green/90 text-white px-3 py-1 rounded-md text-sm">Accept</button>
                          <button onClick={() => declineRequest(r.id)} className="bg-white/10 hover:bg-white/20 text-white px-3 py-1 rounded-md text-sm">Decline</button>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-white/60 text-sm">No incoming requests yet</div>
                )}
              </div>
            </div>
          </div>
        )}
      </motion.div>

      {/* Quick Stats */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.2 }}
        className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8"
      >
        <div className="glass-bubble rounded-2xl p-6">
          <div className="flex items-center space-x-4">
            <div className="w-12 h-12 bg-gradient-to-br from-blue-500/30 to-cyan-500/30 rounded-xl flex items-center justify-center">
              <Clock className="w-6 h-6 text-blue-400" />
            </div>
            <div>
              <p className="text-white/70 text-sm">Your last played</p>
              <p className="text-white font-semibold">{getLastPlayedTime() || 'No recent plays'}</p>
            </div>
          </div>
        </div>

        <div className="glass-bubble rounded-2xl p-6">
          <div className="flex items-center space-x-4">
            <div className="w-12 h-12 bg-gradient-to-br from-green-500/30 to-emerald-500/30 rounded-xl flex items-center justify-center">
              <TrendingUp className="w-6 h-6 text-green-400" />
            </div>
            <div>
              <p className="text-white/70 text-sm">Top tracks analyzed</p>
              <p className="text-white font-semibold">{currentUser?.topTracks?.length || 0} songs</p>
            </div>
          </div>
        </div>

        <div className="glass-bubble rounded-2xl p-6">
          <div className="flex items-center space-x-4">
            <div className="w-12 h-12 bg-gradient-to-br from-purple-500/30 to-pink-500/30 rounded-xl flex items-center justify-center">
              <User className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <p className="text-white/70 text-sm">Recently played</p>
              <p className="text-white font-semibold">{currentUser?.recentlyPlayed?.length || 0} tracks</p>
            </div>
          </div>
        </div>
      </motion.div>

      {/* Features Grid */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.3 }}
        className="grid md:grid-cols-3 gap-6"
      >
        {features.map((feature, index) => (
          <motion.div
            key={feature.title}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 + index * 0.1 }}
            whileHover={{ y: -5, scale: 1.02 }}
          >
            <Link to={feature.href}>
              <div className={`glass rounded-2xl p-6 h-full border ${feature.borderColor} group cursor-pointer transition-all duration-300 hover:shadow-xl`}>
                <div 
                  className="w-12 h-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300"
                  style={{
                    background: `linear-gradient(135deg, ${feature.primaryColor}20 0%, ${feature.secondaryColor}10 100%)`,
                    border: `1px solid ${feature.primaryColor}30`,
                  }}
                >
                  <feature.icon 
                    className="w-6 h-6" 
                    style={{ color: feature.primaryColor }}
                  />
                </div>
                
                <h3 className="text-xl font-semibold text-white mb-2">{feature.title}</h3>
                <p className="text-white/70 text-sm leading-relaxed mb-4">{feature.description}</p>
                
                <div 
                  className="w-full h-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                  style={{
                    background: `linear-gradient(90deg, ${feature.primaryColor} 0%, ${feature.secondaryColor} 100%)`,
                  }}
                />
              </div>
            </Link>
          </motion.div>
        ))}
      </motion.div>

      {/* Recent Activity Preview */}
      {currentUser?.recentlyPlayed && currentUser.recentlyPlayed.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
          className="mt-8"
        >
          <h2 className="text-2xl font-bold text-white mb-4">Your Recent Activity</h2>
          <div className="glass rounded-2xl p-6">
            <div className="space-y-4">
              {currentUser.recentlyPlayed.slice(0, 3).map((item, index) => (
                <motion.div
                  key={item.track.id}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.7 + index * 0.1 }}
                  className="flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors"
                >
                  <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">{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>
                </motion.div>
              ))}
            </div>
          </div>
        </motion.div>
      )}
    </div>
  );
};
