import { useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { useStore } from '../store/useStore';
import { apiGet } from '../utils/api';

function computeHarmony(a: any, b: any): number {
  if (!a || !b) return 0;
  // Simple match using energy and valence when available
  const fields = ['energy', 'valence'];
  let score = 0;
  let count = 0;
  for (const f of fields) {
    if (typeof a[f] === 'number' && typeof b[f] === 'number') {
      score += 1 - Math.min(1, Math.abs(a[f] - b[f]));
      count++;
    }
  }
  if (!count) return 0;
  return Math.round((score / count) * 100);
}

export const LiveDashboardPage = () => {
  const { currentUser, partnerUser } = useStore();
  const [nowA, setNowA] = useState<any>(null);
  const [nowB, setNowB] = useState<any>(null);
  const [featA, setFeatA] = useState<any>(null);
  const [featB, setFeatB] = useState<any>(null);

  useEffect(() => {
    let timer: any;
    const poll = async () => {
      try {
        const uidA = currentUser?.user?.id;
        if (uidA) {
          const dataA = await apiGet(`/users/${uidA}/now-playing`);
          setNowA(dataA);
          const idA = dataA?.item?.id;
          if (idA) {
            const fa = await apiGet(`/users/${uidA}/audio-features?ids=${idA}`);
            setFeatA((fa?.audio_features || [])[0] || null);
          }
        }
        const uidB = partnerUser?.user?.id;
        if (uidB) {
          const dataB = await apiGet(`/users/${uidB}/now-playing`);
          setNowB(dataB);
          const idB = dataB?.item?.id;
          if (idB) {
            const fb = await apiGet(`/users/${uidB}/audio-features?ids=${idB}`);
            setFeatB((fb?.audio_features || [])[0] || null);
          }
        }
      } catch {}
      timer = setTimeout(poll, 8000);
    };
    poll();
    return () => clearTimeout(timer);
  }, [currentUser?.user?.id, partnerUser?.user?.id]);

  const harmony = useMemo(() => computeHarmony(featA, featB), [featA, featB]);

  const Card = ({ data, who }: { data: any; who: string }) => {
    if (!data?.is_playing || !data?.item) {
      return (
        <div className="glass rounded-2xl p-6 text-white/70">{who} is not playing</div>
      );
    }
    const item = data.item;
    return (
      <div className="glass rounded-2xl p-6 flex items-center gap-4">
        <img src={item?.album?.images?.[0]?.url || '/placeholder-album.png'} alt={item?.name} className="w-16 h-16 rounded" />
        <div className="flex-1 min-w-0">
          <div className="text-white font-semibold truncate">{item?.name}</div>
          <div className="text-white/70 text-sm truncate">{(item?.artists || []).map((a: any) => a.name).join(', ')}</div>
        </div>
        <div className="flex gap-1">
          {[...Array(12)].map((_, i) => (
            <div key={i} className="w-1 bg-spotify-green/60 animate-pulse" style={{ height: `${(Math.sin(i) * 0.5 + 0.5) * 32 + 8}px`, animationDelay: `${i * 50}ms` }} />
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="max-w-6xl 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-6">
        <h1 className="text-3xl font-bold text-white">Live Dashboard</h1>
        <p className="text-white/70">See what you are both playing right now</p>
      </motion.div>
      <div className="grid md:grid-cols-2 gap-6">
        <Card data={nowA} who="You" />
        <Card data={nowB} who="Partner" />
      </div>
      {nowA?.is_playing && nowB?.is_playing && (
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="glass rounded-2xl p-6 mt-6 text-center">
          <div className="text-white/80">Harmony Match</div>
          <div className="text-4xl font-extrabold text-white mt-1">{harmony}%</div>
        </motion.div>
      )}
    </div>
  );
};

export default LiveDashboardPage;


