import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Crosshair, ArrowRight, TrendingUp, TrendingDown, Minus, Calendar, Map as MapIcon } from 'lucide-react';
import { PageTransition } from '@/components/layout/PageTransition';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { matchAPI } from '@/api/client';
import { cn } from '@/lib/cn';
import { formatRelativeTime } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

type FilterType = 'all' | 'wins' | 'losses' | 'draws';

export default function MatchHistory() {
  const [matches, setMatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<FilterType>('all');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 20;
  const totalPages = Math.max(1, Math.ceil(total / limit));

  useEffect(() => {
    setLoading(true);
    matchAPI.list({ page, limit })
      .then(({ data }) => {
        setMatches(data.matches || []);
        setTotal(data.total || 0);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [page]);

  const filteredMatches = matches.filter((entry) => {
    if (filter === 'all') return true;
    const m = entry.match || entry;
    const p = entry.player || {};
    const playerTeam = p.team;
    const team1Score = m.team1_score || 0;
    const team2Score = m.team2_score || 0;
    const isDraw = team1Score === team2Score;
    const isWin = playerTeam === 1 ? team1Score > team2Score : team2Score > team1Score;

    if (filter === 'draws') return isDraw;
    if (filter === 'wins') return isWin && !isDraw;
    if (filter === 'losses') return !isWin && !isDraw;
    return true;
  });

  const filters: { key: FilterType; label: string; count?: number }[] = [
    { key: 'all', label: 'All' },
    { key: 'wins', label: 'Wins' },
    { key: 'losses', label: 'Losses' },
    { key: 'draws', label: 'Draws' },
  ];

  return (
    <PageTransition className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex items-center justify-between mb-8">
        <div>
          <motion.h1
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-2xl sm:text-3xl font-extrabold text-[#f0f0f5] tracking-tight"
          >
            Match History
          </motion.h1>
          <motion.p
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 }}
            className="text-sm text-[#a0a0b8] mt-1"
          >
            {total} total match{total !== 1 ? 'es' : ''}
          </motion.p>
        </div>
      </div>

      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="flex gap-1 mb-6 p-1 bg-[#0f0f18] rounded-xl border border-[#1e1e30] w-fit"
      >
        {filters.map((f) => (
          <button
            key={f.key}
            onClick={() => { setFilter(f.key); }}
            className={cn(
              'relative px-4 py-2 text-sm font-medium rounded-lg transition-colors',
              filter === f.key ? 'text-[#f0f0f5]' : 'text-[#5a5a72] hover:text-[#a0a0b8]'
            )}
          >
            {filter === f.key && (
              <motion.div
                layoutId="history-filter"
                className="absolute inset-0 bg-[#1e1e30] rounded-lg border border-[#1e1e30]"
                transition={{ type: 'spring', stiffness: 400, damping: 30 }}
              />
            )}
            <span className="relative z-10">{f.label}</span>
          </button>
        ))}
      </motion.div>

      {loading ? (
        <div className="space-y-3">
          {[...Array(8)].map((_, i) => <SkeletonRow key={i} />)}
        </div>
      ) : filteredMatches.length > 0 ? (
        <motion.div
          variants={staggerContainer}
          initial="initial"
          animate="animate"
          className="space-y-2"
        >
          <AnimatePresence mode="popLayout">
            {filteredMatches.map((entry) => {
              const m = entry.match || entry;
              const p = entry.player || {};
              const stats = entry.stats || {};
              const matchId = m.id || m.match_id;
              const playerTeam = p.team;
              const team1Score = m.team1_score || 0;
              const team2Score = m.team2_score || 0;
              const isDraw = team1Score === team2Score;
              const isWin = playerTeam === 1
                ? team1Score > team2Score
                : team2Score > team1Score;
              const result = isDraw ? 'draw' : isWin ? 'win' : 'loss';
              const mmrDelta = stats.mmr_delta || p.mmr_delta || 0;
              const mapName = (m.map || '').replace('de_', '');

              return (
                <motion.div
                  key={matchId}
                  variants={staggerItem}
                  layout
                  exit={{ opacity: 0, x: -20 }}
                >
                  <Link to={`/match/${matchId}`}>
                    <Card
                      variant="interactive"
                      className="flex items-center gap-3 sm:gap-4 group"
                    >
                      <div className={cn(
                        'w-1 self-stretch rounded-full flex-shrink-0 -ml-2',
                        result === 'win' ? 'bg-emerald-500' : result === 'loss' ? 'bg-red-500' : 'bg-[#1e1e30]'
                      )} />

                      <Badge
                        variant={result === 'win' ? 'success' : result === 'loss' ? 'danger' : 'default'}
                        className="w-16 text-center flex-shrink-0 justify-center"
                      >
                        {result === 'win' ? 'WIN' : result === 'loss' ? 'LOSS' : 'DRAW'}
                      </Badge>

                      <div className="flex items-center gap-1.5 w-24 flex-shrink-0">
                        <MapIcon className="w-3.5 h-3.5 text-[#5a5a72]" />
                        <span className="text-sm text-[#f0f0f5] font-medium capitalize truncate">
                          {mapName}
                        </span>
                      </div>

                      <span className="text-sm font-mono text-[#f0f0f5] font-bold flex-shrink-0 w-14 text-center">
                        {team1Score} - {team2Score}
                      </span>

                      <div className={cn(
                        'flex items-center gap-1 flex-shrink-0 w-16',
                        mmrDelta > 0 ? 'text-emerald-400' : mmrDelta < 0 ? 'text-red-400' : 'text-[#5a5a72]'
                      )}>
                        {mmrDelta > 0 ? (
                          <TrendingUp className="w-3.5 h-3.5" />
                        ) : mmrDelta < 0 ? (
                          <TrendingDown className="w-3.5 h-3.5" />
                        ) : (
                          <Minus className="w-3.5 h-3.5" />
                        )}
                        <span className="text-sm font-mono font-medium">
                          {mmrDelta > 0 ? '+' : ''}{mmrDelta}
                        </span>
                      </div>

                      <span className="text-sm text-[#5a5a72] font-mono flex-shrink-0 hidden sm:block w-20 text-center">
                        {stats.kills || 0}/{stats.deaths || 0}/{stats.assists || 0}
                      </span>

                      <div className="flex items-center gap-1 ml-auto flex-shrink-0">
                        <Calendar className="w-3 h-3 text-[#5a5a72] hidden sm:block" />
                        <span className="text-xs text-[#5a5a72]">
                          {m.finished_at ? formatRelativeTime(m.finished_at) : ''}
                        </span>
                      </div>

                      <ArrowRight className="w-4 h-4 text-[#5a5a72] opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
                    </Card>
                  </Link>
                </motion.div>
              );
            })}
          </AnimatePresence>
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          <Card className="text-center py-16">
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ delay: 0.3, type: 'spring', stiffness: 200 }}
            >
              <Crosshair className="w-16 h-16 text-[#5a5a72] mx-auto mb-4 opacity-20" />
            </motion.div>
            <h3 className="text-lg font-semibold text-[#f0f0f5] mb-1">No matches yet</h3>
            <p className="text-sm text-[#a0a0b8] mb-6">
              {filter !== 'all' ? `No ${filter} found. Try a different filter.` : 'Queue up and start playing!'}
            </p>
            {filter !== 'all' ? (
              <Button variant="secondary" onClick={() => setFilter('all')}>
                Show All Matches
              </Button>
            ) : (
              <Link to="/queue">
                <Button>
                  Find a Match <ArrowRight className="w-4 h-4" />
                </Button>
              </Link>
            )}
          </Card>
        </motion.div>
      )}

      {totalPages > 1 && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.3 }}
          className="flex items-center justify-center gap-1.5 mt-8"
        >
          <button
            onClick={() => setPage(Math.max(1, page - 1))}
            disabled={page === 1}
            className={cn(
              'w-9 h-9 rounded-lg text-sm font-medium transition-colors flex items-center justify-center',
              page === 1 ? 'text-[#5a5a72]/30 cursor-not-allowed' : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
            )}
          >
            &lsaquo;
          </button>
          {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
            let p: number;
            if (totalPages <= 7) {
              p = i + 1;
            } else if (page <= 4) {
              p = i + 1;
            } else if (page >= totalPages - 3) {
              p = totalPages - 6 + i;
            } else {
              p = page - 3 + i;
            }
            return (
              <button
                key={p}
                onClick={() => setPage(p)}
                className={cn(
                  'w-9 h-9 rounded-lg text-sm font-medium transition-all duration-200 relative',
                  p === page
                    ? 'text-white'
                    : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
                )}
              >
                {p === page && (
                  <motion.div
                    layoutId="pagination-active"
                    className="absolute inset-0 bg-[#ff6b2c] rounded-lg"
                    transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                  />
                )}
                <span className="relative z-10">{p}</span>
              </button>
            );
          })}
          <button
            onClick={() => setPage(Math.min(totalPages, page + 1))}
            disabled={page === totalPages}
            className={cn(
              'w-9 h-9 rounded-lg text-sm font-medium transition-colors flex items-center justify-center',
              page === totalPages ? 'text-[#5a5a72]/30 cursor-not-allowed' : 'text-[#5a5a72] hover:text-[#f0f0f5] hover:bg-[#0f0f18]'
            )}
          >
            &rsaquo;
          </button>
        </motion.div>
      )}
    </PageTransition>
  );
}
