import { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Crosshair, ArrowRight, Radio, Server, Gamepad2 } from 'lucide-react';
import { useQueueStore } from '@/stores/queueStore';
import { queueAPI } from '@/api/client';

function formatElapsed(startedAt: number) {
  const seconds = Math.floor((Date.now() - startedAt) / 1000);
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

export function ActiveMatchBanner() {
  const location = useLocation();
  const { phase, gameMode, searchStartedAt, match } = useQueueStore();
  const [elapsed, setElapsed] = useState('0:00');

  const isQueuePage = location.pathname === '/queue';
  const isMatchPage = location.pathname.startsWith('/match/');

  const isActive = phase === 'searching' || phase === 'found' || phase === 'server_loading' || phase === 'ready';

  useEffect(() => {
    if (!isActive) return;
    function poll() {
      queueAPI.status().then(({ data }) => {
        const store = useQueueStore.getState();
        if (data.phase) store.setPhase(data.phase);
        if (data.match) store.setMatch(data.match);
        if (data.players_in_queue) store.setPlayersFound(data.players_in_queue);
      }).catch(() => {});
    }
    const interval = setInterval(poll, 5000);
    return () => clearInterval(interval);
  }, [isActive]);

  useEffect(() => {
    if (phase !== 'searching' || !searchStartedAt) return;
    const tick = () => setElapsed(formatElapsed(searchStartedAt));
    tick();
    const interval = setInterval(tick, 1000);
    return () => clearInterval(interval);
  }, [phase, searchStartedAt]);

  if (phase === 'idle') return null;
  if (isQueuePage || isMatchPage) return null;

  const getConfig = () => {
    switch (phase) {
      case 'searching':
        return {
          icon: Radio,
          label: 'Searching for match',
          detail: `${gameMode === 'competitive' ? 'Competitive' : 'Casual'}, ${elapsed}`,
          color: '#ff6b2c',
          href: '/queue',
          cta: 'View Queue',
          pulse: true,
        };
      case 'found':
      case 'server_loading':
        return {
          icon: Server,
          label: 'Match found, server loading',
          detail: match ? `${match.map.replace('de_', '')}, ${match.game_mode}` : 'Setting up...',
          color: '#6366f1',
          href: '/queue',
          cta: 'View Match',
          pulse: true,
        };
      case 'ready':
        return {
          icon: Gamepad2,
          label: 'Server ready, connect now!',
          detail: match?.connect_string || 'Waiting...',
          color: '#10b981',
          href: match ? `/queue` : '/queue',
          cta: 'Connect',
          pulse: true,
        };
      default:
        return null;
    }
  };

  const config = getConfig();
  if (!config) return null;

  return (
    <AnimatePresence>
      <motion.div
        initial={{ y: -40, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={{ y: -40, opacity: 0 }}
        transition={{ type: 'spring', stiffness: 300, damping: 25 }}
        className="relative z-40"
      >
        <div
          className="border-b"
          style={{ borderColor: `${config.color}20`, background: `${config.color}06` }}
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-11">
              <div className="flex items-center gap-3 min-w-0">
                <div className="relative flex-shrink-0">
                  <config.icon className="w-3.5 h-3.5" style={{ color: config.color }} />
                  {config.pulse && (
                    <span
                      className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full animate-ping"
                      style={{ background: config.color, opacity: 0.6 }}
                    />
                  )}
                </div>
                <span className="text-xs font-bold text-[#f0f0f5] truncate">
                  {config.label}
                </span>
                <span className="hidden sm:block text-[10px] font-medium text-[#5a5a72] truncate">
                  {config.detail}
                </span>
              </div>

              <Link
                to={config.href}
                className="flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-bold transition-all duration-200 flex-shrink-0"
                style={{
                  color: config.color,
                  background: `${config.color}12`,
                  border: `1px solid ${config.color}25`,
                }}
              >
                {config.cta}
                <ArrowRight className="w-3 h-3" />
              </Link>
            </div>
          </div>
        </div>
      </motion.div>
    </AnimatePresence>
  );
}
