import React from 'react';
import { useApp } from '../context/AppContext';
import { ArrowLeft, Cpu, Zap, RefreshCw, PlusCircle, Award, CheckCircle } from 'lucide-react';

export const DeveloperPanel: React.FC = () => {
  const { 
    matches, 
    user, 
    transactions,
    pushView, 
    popView, 
    simulateMatchResult, 
    adminAddPlayer, 
    adminResetMatches, 
    depositFunds,
    adminApproveTransaction,
    adminCancelTransaction 
  } = useApp();

  const handleSimulateWin = async (matchId: string) => {
    await simulateMatchResult(matchId, 'WIN');
    alert('অভিনন্দন! আপনি ম্যাচটি জিতেছেন। পুরো উইনিং প্রাইজ আপনার ওয়ালেটের Winning Balance এ যোগ করা হয়েছে!');
  };

  const handleSimulateLose = async (matchId: string) => {
    await simulateMatchResult(matchId, 'LOSE');
    alert('ম্যাচটি সমাপ্ত হয়েছে এবং অন্য প্রতিপক্ষ জিতেছে। পুনরায় ম্যাচে অংশ নিন!');
  };

  const handleAddFastFunds = async () => {
    await depositFunds('bKash', 2500, '01712234556', 'SIM_ADMIN_' + Math.floor(Math.random() * 99999));
    alert('২৫০০ টাকা মূল ব্যালেন্সে যুক্ত করা হয়েছে! এবার আপনি স্পেশাল ও রেগুলার যেকোনো ম্যাচ খেলতে পারবেন।');
  };

  // Find joined matches that are either ACTIVE or FULL
  const activeJoinedMatches = matches.filter(m => m.userJoinedName && m.status !== 'COMPLETED');

  return (
    <div className="space-y-6 pb-28">
      {/* Header back */}
      <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">
          <ArrowLeft className="w-5 h-5 inline mr-1" />
          Back
        </button>
        <div>
          <h2 className="text-[#f8fafc] text-lg font-black tracking-tight leading-none text-sky-400">
            Developer Console
          </h2>
          <span className="text-xs text-slate-400 font-bold uppercase font-mono">
            Full App Flow Simulator
          </span>
        </div>
      </div>

      {/* Info notice block */}
      <div className="bg-sky-500/10 border border-sky-500/20 rounded-2xl p-4.5 space-y-2 text-xs font-semibold leading-relaxed text-slate-300">
        <div className="flex items-center gap-1.5 text-sky-400 font-black uppercase font-mono">
          <Cpu className="w-4 h-4 text-sky-400 animate-spin" />
          How to test everything:
        </div>
        <p>১. নিচের <span className="text-yellow-400">"Instant Wallet Fund"</span> বাটনে ক্লিক করে ফ্রি টাকা এড করুন।</p>
        <p>২. ম্যাচে যান এবং যেকোনো পেইড টুর্নামেন্টে জয়েন করুন।</p>
        <p>৩. নিচে <span className="text-yellow-400">"Add Simulated Player"</span> দিয়ে সিট ফুল করুন। ফুল হলে আপনি লবি রুম কোড পেয়ে যাবেন!</p>
        <p>৪. গেম শেষে উইনিং স্ক্রিনশট উইন প্রমাণের মাধ্যমে আপলোড দিন অথবা নিচের সিমুলেটরে <span className="text-green-400">"Force User WIN 🏆"</span> দিন। সাথে সাথে টাকা পাবেন!</p>
      </div>

      {/* Fast Shortcuts */}
      <div className="space-y-3.5 pt-2">
        <h3 className="text-[10px] text-slate-500 font-black tracking-widest font-mono uppercase block">
          FAST ACTION TOOLS
        </h3>

        <div className="grid grid-cols-2 gap-3">
          {/* Fund shortcut */}
          <button 
            type="button"
            onClick={handleAddFastFunds}
            className="bg-sky-600 hover:bg-sky-700 text-white font-extrabold text-xs py-4 px-3 rounded-xl shadow-lg flex items-center justify-center gap-2"
          >
            <Zap className="w-4 h-4 fill-current text-yellow-300" />
            + ৳২৫০০ FREE CASH
          </button>

          {/* Reset shortcut */}
          <button 
            type="button"
            onClick={async () => {
              await adminResetMatches();
              alert('সকল ডেটা সফলভাবে ফেক্টরি রিসেট করা হয়েছে!');
            }}
            className="bg-slate-850 hover:bg-slate-800 text-slate-200 border border-slate-700 font-extrabold text-xs py-4 px-3 rounded-xl shadow"
          >
            <RefreshCw className="w-4 h-4 inline mr-1" />
            RESET APP DATA
          </button>
        </div>
      </div>

      {/* Pending Transactions Simulator */}
      <div className="bg-[#131b2e] border border-slate-850 p-5 rounded-2xl shadow-lg space-y-4">
        <div className="border-b border-slate-800 pb-2 flex items-center justify-between">
          <div>
            <h4 className="text-white text-xs font-black tracking-widest uppercase font-mono text-yellow-400">
              TRANSACTIONS NOTIFICATIONS
            </h4>
            <span className="text-[10px] text-slate-400 font-bold block pt-0.5">
              (ডিপোজিট ও উইথড্র নোটিফিকেশন রিসিভ ট্রায়াল ফ্লো)
            </span>
          </div>
          <span className="bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[9px] font-black px-2 py-0.5 rounded-full font-mono">
            LIVE
          </span>
        </div>

        <div className="space-y-3">
          {transactions.filter(t => t.status === 'PENDING').map(t => (
            <div key={t.id} className="p-3 bg-slate-950 border border-slate-850 rounded-xl space-y-2 text-left">
              <div className="flex items-center justify-between">
                <span className={`text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded ${
                  t.type === 'DEPOSIT' ? 'bg-emerald-500/10 text-emerald-400' : 'bg-pink-500/10 text-pink-400'
                }`}>
                  {t.type} ({t.paymentChannel})
                </span>
                <span className="text-white font-extrabold text-xs">৳{t.amount}</span>
              </div>
              <p className="text-[10px] text-slate-400 font-bold leading-tight font-mono">
                No: {t.accountNo} {t.transactionId ? `| Trx: ${t.transactionId}` : ''}
              </p>
              
              <div className="grid grid-cols-2 gap-2 text-center pt-1">
                <button 
                  type="button"
                  onClick={async () => await adminApproveTransaction(t.id)}
                  className="bg-emerald-500 hover:bg-emerald-600 active:scale-95 text-slate-950 text-[10px] font-black py-1.5 rounded-lg transition-transform"
                >
                  ✓ Approve (Success)
                </button>
                <button 
                  type="button"
                  onClick={async () => await adminCancelTransaction(t.id)}
                  className="bg-rose-600 hover:bg-rose-700 active:scale-95 text-white text-[10px] font-black py-1.5 rounded-lg transition-transform"
                >
                  ✕ Reject (Cancel)
                </button>
              </div>
            </div>
          ))}

          {transactions.filter(t => t.status === 'PENDING').length === 0 && (
            <div className="text-center py-4 text-slate-500 border border-dashed border-slate-800 rounded-xl space-y-2">
              <p className="text-slate-400 text-[11px] font-bold">কোনো পেন্ডিং ডিপোজিট বা উইথড্র রিকোয়েস্ট নেই।</p>
              <p className="text-slate-500 text-[9px] pt-0.5 max-w-[280px] mx-auto leading-relaxed">
                উইথড্র বা ডিপোজিটের জন্য নোটিফিকেশন চেক করতে প্রথমে ওয়ালেট পেজে গিয়ে একটি রিকোয়েস্ট প্লেস করুন।
              </p>
              <div className="flex justify-center gap-2 pt-1">
                <button 
                  type="button"
                  onClick={() => pushView('wallet')}
                  className="bg-[#1e293b] text-yellow-400 hover:bg-slate-800 text-[10px] px-3 py-1 font-black rounded-lg transition-all"
                >
                  Wallet-এ যান
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Matches seats builder */}
      <div className="bg-[#131b2e] border border-slate-850 p-5 rounded-2xl shadow-lg space-y-4">
        <div className="border-b border-slate-800 pb-2">
          <h4 className="text-white text-xs font-black tracking-widest uppercase font-mono">
            ADD SIMULATED PLAYERS TO ANY SEATS
          </h4>
          <span className="text-[10px] text-slate-400 font-bold block pt-0.5">
            (সিট ফুল করে রুম কোড দেখতে এই বাটনগুলি চাপুন)
          </span>
        </div>

        <div className="space-y-3.5">
          {matches.filter(m => m.status === 'ACTIVE').map(m => (
            <div key={m.id} className="flex items-center justify-between p-3 bg-slate-950 border border-slate-850 rounded-xl">
              <div className="space-y-0.5 text-left">
                <span className="text-white font-bold text-xs block">{m.title}</span>
                <span className="text-[10px] text-slate-500 font-medium font-mono leading-none block">
                  Seats: {m.playersJoined}/{m.totalPlayersNeeded}
                </span>
              </div>
              <button 
                type="button"
                onClick={async () => await adminAddPlayer(m.id)}
                className="bg-indigo-600 hover:bg-indigo-700 text-white text-[10px] font-black px-3.5 py-2 rounded-lg py-1.5 transition-transform active:scale-95 text-center"
              >
                + ADD PLAYERS
              </button>
            </div>
          ))}
          {matches.filter(m => m.status === 'ACTIVE').length === 0 && (
            <p className="text-slate-500 text-xs font-bold text-center">কোনো সক্রিয় ম্যাচ খালি নেই।</p>
          )}
        </div>
      </div>

      {/* Outcom flow simulator */}
      <div className="bg-[#131b2e] border border-slate-850 p-5 rounded-2xl shadow-lg space-y-4">
        <div className="border-b border-slate-800 pb-2">
          <h4 className="text-white text-xs font-black tracking-widest uppercase font-mono">
            OUTCOME FLOW MATCH SIMULATOR
          </h4>
          <span className="text-[10px] text-slate-400 font-bold block pt-0.5">
            (আপনার অংশগ্রহনকৃত ম্যাচগুলোতে জয়-পরাজয় সিমুলেট করুন)
          </span>
        </div>

        <div className="space-y-4">
          {activeJoinedMatches.map(m => (
            <div key={m.id} className="bg-slate-950 border-2 border-indigo-500/10 p-4 rounded-xl space-y-3">
              <div className="flex items-center justify-between">
                <div>
                  <span className="text-white font-extrabold text-xs block">{m.title}</span>
                  <span className="text-[9px] text-[#facc15] font-black uppercase font-mono bg-yellow-400/10 px-2 py-0.5 rounded">
                    Status: {m.status}
                  </span>
                </div>
                <div className="text-right text-[10px]">
                  <span className="text-slate-400 leading-none block uppercase font-mono">WIN PRIZE:</span>
                  <span className="text-green-400 font-black text-sm block">৳ {m.winningPrize}</span>
                </div>
              </div>

              {/* Victory action choices */}
              <div className="grid grid-cols-2 gap-2 text-center pt-1">
                <button 
                  type="button"
                  onClick={() => handleSimulateWin(m.id)}
                  className="bg-emerald-500 hover:bg-green-600 text-slate-950 text-[10px] font-extrabold tracking-wider uppercase py-2.5 rounded-lg flex items-center justify-center gap-1 shadow-lg"
                >
                  <Award className="w-3.5 h-3.5 stroke-[3.5]" />
                  Force WIN 🏆
                </button>
                <button 
                  type="button"
                  onClick={() => handleSimulateLose(m.id)}
                  className="bg-rose-600 hover:bg-rose-700 text-white text-[10px] font-extrabold tracking-wider uppercase py-2.5 rounded-lg text-center"
                >
                  Force Lose ❌
                </button>
              </div>

            </div>
          ))}
          {activeJoinedMatches.length === 0 && (
            <div className="text-center py-6 text-slate-500 font-bold text-xs space-y-2">
              <p>আপনার অংশগ্রহনকৃত কোনো রানিং ম্যাচ খুজে পাওয়া যায়নি।</p>
              <button 
                type="button"
                onClick={() => pushView('home')}
                className="bg-indigo-600 text-white font-bold text-[10px] px-3.5 py-1.5 rounded-lg"
              >
                Go to Home to Join Match
              </button>
            </div>
          )}
        </div>
      </div>

    </div>
  );
};
