import React, { useState } from 'react';
import { useApp } from '../context/AppContext';
import { Match, MatchCategory, MatchStatus } from '../types';
import { ArrowLeft, Clock, Award, ShieldAlert, Key, Upload, RefreshCw } from 'lucide-react';

export const MatchesView: React.FC = () => {
  const { matches, user, pushView, popView, viewPayload } = useApp();
  
  // Tab filters
  const [categoryFilter, setCategoryFilter] = useState<'ALL' | 'MY' | MatchCategory>(() => {
    return (viewPayload && viewPayload.category) ? viewPayload.category : 'ALL';
  });
  
  const [sizeFilter, setSizeFilter] = useState<'ALL' | 'SMALL' | 'BIG'>('ALL');

  // Filter implementation
  const filteredMatches = matches.filter(match => {
    // 1. Filter Category
    if (categoryFilter === 'MY') {
      // User is registered in this match
      return match.userJoinedName !== undefined;
    } else if (categoryFilter !== 'ALL' && match.category !== categoryFilter) {
      return false;
    }

    // 2. Filter Size
    if (sizeFilter === 'SMALL' && match.entryFee >= 500) {
      return false;
    } else if (sizeFilter === 'BIG' && match.entryFee < 500) {
      return false;
    }

    return true;
  });

  const getStatusColor = (status: MatchStatus) => {
    switch (status) {
      case 'ACTIVE': return 'bg-green-500/10 text-green-400';
      case 'FULL': return 'bg-amber-500/10 text-amber-400';
      case 'CLOSED': return 'bg-rose-500/10 text-rose-400';
      case 'COMPLETED': return 'bg-sky-500/10 text-sky-400';
    }
  };

  const handleMatchAction = (match: Match) => {
    if (match.status === 'CLOSED' || match.status === 'COMPLETED') {
      return;
    }

    // If user has already joined, and it's full, let them see room ID or upload evidence!
    if (match.userJoinedName) {
      if (match.status === 'FULL') {
        // Take to Evidence upload or show Room Code
        pushView('evidence', { matchId: match.id });
      } else {
        alert('আপনার এন্ট্রি নিশ্চিত করা হয়েছে! আরও খেলোয়াড় জয়েন করার জন্য অপেক্ষা করুন। রুম আইডি খেলা শুরুর পূর্বে দেওয়া হবে।');
      }
    } else {
      // Take to Match Detail detail page to join!
      pushView('match-detail', { matchId: match.id });
    }
  };

  return (
    <div className="space-y-5 pb-28">
      {/* Header with back icon */}
      <div className="flex items-center gap-3 border-b border-slate-800 pb-3">
        <button 
          onClick={popView} 
          className="p-1 px-2.5 rounded-lg bg-slate-800/100 hover:bg-slate-700 text-slate-100"
          id="matches-back-btn"
        >
          <ArrowLeft className="w-5 h-5 inline mr-1" />
          Back
        </button>
        <div>
          <h2 className="text-[#f8fafc] text-lg font-black tracking-tight leading-none">
            Ludo Matches
          </h2>
          <span className="text-xs text-slate-400 font-bold uppercase font-mono">
            {categoryFilter} Tournaments
          </span>
        </div>
      </div>

      {/* Categories Horizontal Tabs */}
      <div className="grid grid-cols-4 gap-1.5 bg-slate-900/100 p-1 rounded-xl border border-slate-800">
        {(['ALL', 'MY', 'SPECIAL', 'REGULAR'] as const).map(cat => (
          <button
            key={cat}
            onClick={() => setCategoryFilter(cat)}
            className={`py-2 text-[10px] font-black tracking-widest text-center uppercase rounded-lg transition-all ${
              categoryFilter === cat
                ? 'bg-gradient-to-r from-amber-500 to-yellow-400 text-slate-950 font-extrabold shadow-md'
                : 'text-slate-400 hover:text-slate-100'
            }`}
          >
            {cat}
          </button>
        ))}
      </div>

      {/* Sub-filters style: ALL, MY, SMALL, BIG (or BET SIZES) */}
      <div className="flex items-center justify-between">
        <span className="text-[10px] text-slate-400 font-black tracking-widest uppercase font-mono">
          BET RANGE FILTER:
        </span>
        <div className="flex gap-2">
          {(['ALL', 'SMALL', 'BIG'] as const).map(sz => (
            <button
              key={sz}
              onClick={() => setSizeFilter(sz)}
              className={`px-3 py-1 text-[9px] font-black tracking-wider uppercase rounded-full border transition-all ${
                sizeFilter === sz
                  ? 'bg-slate-100/100 text-slate-950 border-white'
                  : 'text-slate-400 hover:text-slate-100 border-slate-800 bg-slate-950/40'
              }`}
            >
              {sz}
            </button>
          ))}
        </div>
      </div>

      {/* Matches Cards lists container */}
      <div className="space-y-4">
        {filteredMatches.length === 0 ? (
          <div className="bg-slate-900 border border-slate-800 rounded-2xl p-10 flex flex-col items-center justify-center text-center">
            {/* Stopwatch icon replicas */}
            <div className="w-16 h-16 rounded-full bg-slate-800 flex items-center justify-center mb-4">
              <Clock className="w-8 h-8 text-rose-400 animate-pulse" />
            </div>
            <h4 className="text-white font-bold text-base">No matches matches available!</h4>
            <p className="text-[#94a3b8] text-xs max-w-xs mt-1">
              {categoryFilter === 'MY' 
                ? 'আপনি এখনও কোনো ম্যাচে অংশ নেননি। হোম স্ক্রিন থেকে যেকোনো ম্যাচে যুক্ত হন!' 
                : 'দয়া করে চেক ব্যাক করুন, কিছুক্ষণের মধ্যেই নতুন ম্যাচ প্রকাশিত হবে!'}
            </p>
          </div>
        ) : (
          filteredMatches.map(match => {
            const hasJoined = !!match.userJoinedName;
            const progressPercent = Math.min(100, (match.playersJoined / match.totalPlayersNeeded) * 100);

            return (
              <div 
                key={match.id}
                className={`relative overflow-hidden bg-slate-900 border rounded-2xl p-5 shadow-lg space-y-4 transition-all hover:border-slate-700 ${
                  hasJoined ? 'border-indigo-500/40' : 'border-slate-800'
                }`}
                id={`match-card-${match.id}`}
              >
                {/* Upper row: Titles & type representation */}
                <div className="flex items-start justify-between">
                  {/* Left Side Labels */}
                  <div className="space-y-1">
                    <h4 className="text-white font-extrabold text-base tracking-tight leading-tight">
                      {match.title}
                    </h4>
                    <div className="flex items-center gap-1.5 text-xs text-slate-400 font-bold">
                      <Clock className="w-3.5 h-3.5 text-yellow-400" />
                      <span>{match.time}</span>
                    </div>
                  </div>

                  {/* Badges status */}
                  <div className="flex flex-col items-end gap-1.5 shrink-0">
                    <span className="text-[9px] bg-slate-800 border border-slate-700 text-yellow-400 font-black tracking-wider uppercase px-2.5 py-0.5 rounded-full font-mono">
                      Game: {match.gameName}
                    </span>
                    <span className="text-[9px] bg-blue-500/10 text-cyan-400 font-black tracking-wider uppercase px-2.5 py-0.5 rounded-full font-mono">
                      Type: CLASSIC
                    </span>
                  </div>
                </div>

                {/* Highly highlighted notice warning */}
                <div className="bg-[#b91c1c]/10 border border-red-700/20 text-red-400 rounded-lg p-2 text-[10px] font-bold text-center">
                  সিট ফুল হলে রুম আইডি দেওয়া হবে
                </div>

                {/* Middle Section: Winning Prize VS Entry Fee */}
                <div className="grid grid-cols-2 gap-3 bg-slate-950/60 rounded-xl p-3 text-center border border-slate-800/60">
                  <div>
                    <span className="text-[10px] text-slate-400 font-bold block uppercase tracking-widest font-mono">
                      WINNING PRIZE
                    </span>
                    <span className="text-[#facc15] font-black text-2xl tracking-tight">
                      {match.winningPrize}
                    </span>
                  </div>
                  <div className="border-l border-slate-800/80">
                    <span className="text-[10px] text-slate-400 font-bold block uppercase tracking-widest font-mono">
                      ENTRY FEE
                    </span>
                    <span className="text-white font-black text-2xl tracking-tight">
                      {match.entryFee}
                    </span>
                  </div>
                </div>

                {/* Players joined seat counter and bar */}
                <div className="space-y-1.5">
                  <div className="flex items-center justify-between text-[11px] font-bold text-slate-400 uppercase">
                    <span>
                      {match.totalPlayersNeeded - match.playersJoined} Players Need
                    </span>
                    <span className="text-white">
                      {match.playersJoined}/{match.totalPlayersNeeded}
                    </span>
                  </div>
                  {/* Progress bar */}
                  <div className="w-full h-2 bg-slate-950 rounded-full overflow-hidden">
                    <div 
                      className="bg-gradient-to-r from-red-500 to-rose-600 h-full rounded-full transition-all duration-500"
                      style={{ width: `${progressPercent}%` }}
                    ></div>
                  </div>
                </div>

                {/* Complete Room Code details when joined and Full */}
                {hasJoined && match.status === 'FULL' && (
                  <div className="bg-emerald-500/10 border border-emerald-500/20 rounded-xl p-3.5 flex items-center justify-between">
                    <div>
                      <span className="text-[10px] text-slate-400 font-bold uppercase block leading-none mb-1 font-mono">
                        Ludo Room Code:
                      </span>
                      <span className="text-white font-mono font-black text-base tracking-wider select-all">
                        {match.roomCode || 'ROOM_412554'}
                      </span>
                    </div>
                    <button 
                      className="bg-emerald-500 py-1 px-3 rounded-lg text-slate-950 font-bold text-xs"
                      onClick={() => {
                        navigator.clipboard.writeText(match.roomCode || 'ROOM_412554');
                        alert('রুম কোড কপি করা হয়েছে! Ludo King-এ গিয়ে জয়েন করুন।');
                      }}
                    >
                      কপি করুন
                    </button>
                  </div>
                )}

                {/* Match Action button */}
                <div className="pt-1">
                  {match.status === 'CLOSED' || match.status === 'COMPLETED' ? (
                    <button className="w-full bg-[#1e293b] text-slate-500 border border-slate-800 font-black tracking-widest uppercase text-xs py-3 rounded-xl cursor-not-allowed">
                      {match.status === 'COMPLETED' ? 'COMPLETED' : 'CLOSED'}
                    </button>
                  ) : hasJoined ? (
                    match.status === 'FULL' ? (
                      <button 
                        onClick={() => handleMatchAction(match)}
                        className="w-full bg-gradient-to-r from-emerald-500 to-green-600 hover:from-emerald-600 hover:to-green-700 text-slate-950 font-black tracking-widest uppercase text-xs py-3 rounded-xl flex items-center justify-center gap-2 shadow-lg"
                      >
                        <Upload className="w-4 h-4 text-slate-950 stroke-[3]" />
                        UPLOAD EVIDENCE / SUBMIT WIN
                      </button>
                    ) : (
                      <button className="w-full bg-indigo-600 text-white font-black tracking-widest uppercase text-xs py-3 rounded-xl border border-indigo-500 shadow-md">
                        ✓ JOINED (WAITING FOR COMPANIONS)
                      </button>
                    )
                  ) : (
                    <button 
                      onClick={() => handleMatchAction(match)}
                      className="w-full bg-gradient-to-r from-[#22c55e] to-[#16a34a] hover:from-[#18a248] hover:to-[#128a3c] text-white font-black tracking-widest uppercase text-xs py-3 rounded-xl cursor-pointer shadow-lg active:scale-[0.98] transition-transform text-center block"
                    >
                      JOIN MATCH
                    </button>
                  )}
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};
