'use client';

import { useState } from 'react';
import {
  Zap,
  LogIn,
  UserPlus,
  Wallet,
  ShoppingCart,
  ArrowLeftRight,
  Gift,
  Bell,
  Globe,
  Database,
  PlayCircle,
  CheckCircle,
  XCircle,
  Loader2,
} from 'lucide-react';
import { apiService, type ApiTestResult } from '@/services/api.service';

interface QuickAction {
  label: string;
  icon: typeof Zap;
  action: 'login' | 'register' | 'wallet' | 'orders' | 'transactions' | 'referral' | 'notification' | 'api' | 'database' | 'system';
  color: string;
}

const actions: QuickAction[] = [
  { label: 'Test Login', icon: LogIn, action: 'login', color: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
  { label: 'Test Register', icon: UserPlus, action: 'register', color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20' },
  { label: 'Test Wallet', icon: Wallet, action: 'wallet', color: 'text-violet-400 bg-violet-500/10 border-violet-500/20' },
  { label: 'Test Orders', icon: ShoppingCart, action: 'orders', color: 'text-amber-400 bg-amber-500/10 border-amber-500/20' },
  { label: 'Test Transactions', icon: ArrowLeftRight, action: 'transactions', color: 'text-cyan-400 bg-cyan-500/10 border-cyan-500/20' },
  { label: 'Test Referral', icon: Gift, action: 'referral', color: 'text-pink-400 bg-pink-500/10 border-pink-500/20' },
  { label: 'Test Notification', icon: Bell, action: 'notification', color: 'text-rose-400 bg-rose-500/10 border-rose-500/20' },
  { label: 'Test API', icon: Globe, action: 'api', color: 'text-indigo-400 bg-indigo-500/10 border-indigo-500/20' },
  { label: 'Test Database', icon: Database, action: 'database', color: 'text-orange-400 bg-orange-500/10 border-orange-500/20' },
  { label: 'Run Complete System Test', icon: PlayCircle, action: 'system', color: 'text-white bg-gradient-to-r from-indigo-500/20 to-purple-500/20 border-indigo-500/30' },
];

interface TestResult {
  action: string;
  status: 'PASS' | 'FAIL' | 'RUNNING';
  details?: string;
}

export function QuickActions({ onRunSystemTest }: { onRunSystemTest?: () => void }) {
  const [results, setResults] = useState<TestResult[]>([]);
  const [runningAction, setRunningAction] = useState<string | null>(null);

  const executeAction = async (action: QuickAction) => {
    setRunningAction(action.label);
    
    const result: TestResult = { action: action.label, status: 'RUNNING' };
    setResults((prev) => [result, ...prev.filter((r) => r.action !== action.label)]);

    try {
      let endpoint = '';
      let method = 'GET';
      let payload: any = {};

      switch (action.action) {
        case 'login':
          method = 'POST';
          endpoint = '/auth/login';
          payload = { email: 'test@example.com', password: 'test' };
          break;
        case 'register':
          method = 'POST';
          endpoint = '/auth/register';
          payload = { email: 'test@example.com', password: 'test', name: 'Test' };
          break;
        case 'wallet':
          endpoint = '/wallet';
          break;
        case 'orders':
          endpoint = '/orders';
          break;
        case 'transactions':
          endpoint = '/transactions';
          break;
        case 'referral':
          endpoint = '/referrals';
          break;
        case 'notification':
          endpoint = '/notifications';
          break;
        case 'api':
          endpoint = '/health';
          break;
        case 'database':
          endpoint = '/health/database';
          break;
        case 'system':
          if (onRunSystemTest) onRunSystemTest();
          result.status = 'PASS';
          result.details = 'System test initiated';
          setResults((prev) => [result, ...prev.filter((r) => r.action !== action.label)]);
          setRunningAction(null);
          return;
      }

      const apiResult: ApiTestResult = method === 'POST'
        ? await apiService.testPost(endpoint, payload, `${method} ${endpoint}`)
        : await apiService.testGet(endpoint, `${method} ${endpoint}`);

      result.status = apiResult.status;
      result.details = `${apiResult.statusCode} (${apiResult.latency}ms)`;
    } catch (err: any) {
      result.status = 'FAIL';
      result.details = err?.message ?? 'Error';
    }

    setResults((prev) => [result, ...prev.filter((r) => r.action !== action.label)]);
    setRunningAction(null);
  };

  return (
    <div className="rounded-xl border border-white/5 bg-slate-900/50">
      <div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
        <div className="flex items-center gap-2">
          <Zap className="h-4 w-4 text-amber-400" />
          <h3 className="text-xs font-semibold text-white">Quick Tests</h3>
        </div>
        {results.length > 0 && (
          <span className="text-[10px] font-mono text-slate-500">
            {results.filter((r) => r.status === 'PASS').length}/{results.length} passed
          </span>
        )}
      </div>

      <div className="p-4">
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-2">
          {actions.map((action) => {
            const isRunning = runningAction === action.label;
            return (
              <button
                key={action.label}
                onClick={() => executeAction(action)}
                disabled={isRunning}
                className={`flex flex-col items-center gap-1.5 rounded-lg border px-3 py-2.5 text-[10px] font-medium transition-all ${
                  isRunning ? 'opacity-50 animate-pulse' : 'hover:scale-[1.02]'
                } ${action.color}`}
              >
                {isRunning ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <action.icon className="h-4 w-4" />
                )}
                <span className="text-center leading-tight">
                  {action.label}
                </span>
              </button>
            );
          })}
        </div>

        {/* Results Panel */}
        {results.length > 0 && (
          <div className="mt-4 space-y-1">
            <p className="text-[10px] font-medium text-slate-500 uppercase tracking-wider">Recent Results</p>
            <div className="max-h-[200px] overflow-y-auto space-y-1">
              {results.map((result, i) => (
                <div
                  key={`${result.action}-${i}`}
                  className="flex items-center justify-between rounded-lg border border-white/5 bg-white/[0.02] px-3 py-1.5"
                >
                  <div className="flex items-center gap-2">
                    {result.status === 'PASS' ? (
                      <CheckCircle className="h-3.5 w-3.5 text-emerald-400" />
                    ) : result.status === 'RUNNING' ? (
                      <Loader2 className="h-3.5 w-3.5 animate-spin text-amber-400" />
                    ) : (
                      <XCircle className="h-3.5 w-3.5 text-red-400" />
                    )}
                    <span className="text-xs text-slate-300">{result.action}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    {result.details && (
                      <span className="text-[9px] font-mono text-slate-500">{result.details}</span>
                    )}
                    <span className={`rounded px-1.5 py-0.5 text-[9px] font-mono font-medium ${
                      result.status === 'PASS' ? 'bg-emerald-500/10 text-emerald-400' :
                      result.status === 'RUNNING' ? 'bg-amber-500/10 text-amber-400' :
                      'bg-red-500/10 text-red-400'
                    }`}>
                      {result.status}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {results.length === 0 && (
          <div className="mt-4 flex items-center justify-center rounded-lg border border-dashed border-white/5 py-6">
            <div className="flex flex-col items-center gap-1">
              <Zap className="h-5 w-5 text-slate-600" />
              <p className="text-[10px] text-slate-500">Click any test button above to run a quick test</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

