'use client';

import { useState, useEffect } from 'react';
import { InternalHeader } from '@/components/ui/internal-header';
import Footer from '@/components/ui/footer';
import {
  TestTube, Play, CheckCircle, XCircle, AlertTriangle, Clock,
  Download, RefreshCw, Plus, FileText, ChevronDown, ChevronRight,
  Filter, Search, BarChart3, Loader2, Package, Settings
} from 'lucide-react';

interface TestCase {
  id: string;
  testCaseId: string;
  scenario: string;
  objective: string;
  expectedOutcome: string;
  priority: string;
  category: string;
  lastResult?: string;
  lastRunAt?: string;
}

interface TestSuite {
  id: string;
  name: string;
  description?: string;
  version: string;
  status: string;
  environment: string;
  metadata: any;
  createdAt: string;
  E2ETestCase?: TestCase[];
  E2ETestRun?: any[];
  _count?: {
    E2ETestCase: number;
    E2ETestRun: number;
  };
}

interface TestRun {
  id: string;
  runNumber: number;
  status: string;
  totalCases: number;
  passedCases: number;
  failedCases: number;
  blockedCases: number;
  skippedCases: number;
  startedAt: string;
  completedAt?: string;
}

const priorityColors: Record<string, string> = {
  critical: 'bg-red-500/20 text-red-400 border-red-500/30',
  high: 'bg-orange-500/20 text-orange-400 border-orange-500/30',
  medium: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
  low: 'bg-blue-500/20 text-blue-400 border-blue-500/30'
};

const categoryColors: Record<string, string> = {
  happy_path: 'bg-green-500/20 text-green-400',
  edge_case: 'bg-brand-secondary/20 text-brand-secondary-light',
  error_handling: 'bg-red-500/20 text-red-400',
  integration: 'bg-brand-deep/20 text-brand'
};

const statusIcons: Record<string, JSX.Element> = {
  passed: <CheckCircle className="w-4 h-4 text-green-400" />,
  failed: <XCircle className="w-4 h-4 text-red-400" />,
  blocked: <AlertTriangle className="w-4 h-4 text-yellow-400" />,
  skipped: <Clock className="w-4 h-4 text-gray-400" />,
  pending: <Clock className="w-4 h-4 text-blue-400" />,
  running: <Loader2 className="w-4 h-4 text-brand animate-spin" />
};

export default function E2ETestsPage() {
  const [suites, setSuites] = useState<TestSuite[]>([]);
  const [selectedSuite, setSelectedSuite] = useState<TestSuite | null>(null);
  const [loading, setLoading] = useState(true);
  const [seeding, setSeeding] = useState(false);
  const [expandedCases, setExpandedCases] = useState<Set<string>>(new Set());
  const [filterPriority, setFilterPriority] = useState<string>('');
  const [filterCategory, setFilterCategory] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    fetchSuites();
  }, []);

  const fetchSuites = async () => {
    try {
      const res = await fetch('/api/e2e-tests');
      const data = await res.json();
      if (data.suites) {
        setSuites(data.suites);
      }
    } catch (error) {
      console.error('Error fetching suites:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchSuiteDetails = async (suiteId: string) => {
    try {
      const res = await fetch(`/api/e2e-tests?suiteId=${suiteId}&includeTestCases=true&includeRuns=true`);
      const data = await res.json();
      if (data.suite) {
        setSelectedSuite(data.suite);
      }
    } catch (error) {
      console.error('Error fetching suite details:', error);
    }
  };

  const seedStuffBalls = async () => {
    setSeeding(true);
    try {
      const res = await fetch('/api/e2e-tests/seed', { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        await fetchSuites();
        if (data.suiteId) {
          await fetchSuiteDetails(data.suiteId);
        }
      }
    } catch (error) {
      console.error('Error seeding:', error);
    } finally {
      setSeeding(false);
    }
  };

  const startTestRun = async () => {
    if (!selectedSuite) return;
    try {
      const res = await fetch('/api/e2e-tests', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'startRun',
          suiteId: selectedSuite.id,
          environment: 'staging',
          triggeredBy: 'Manual'
        })
      });
      const data = await res.json();
      if (data.success) {
        await fetchSuiteDetails(selectedSuite.id);
      }
    } catch (error) {
      console.error('Error starting run:', error);
    }
  };

  const toggleCase = (caseId: string) => {
    setExpandedCases(prev => {
      const next = new Set(prev);
      if (next.has(caseId)) {
        next.delete(caseId);
      } else {
        next.add(caseId);
      }
      return next;
    });
  };

  const filteredCases = selectedSuite?.E2ETestCase?.filter(tc => {
    if (filterPriority && tc.priority !== filterPriority) return false;
    if (filterCategory && tc.category !== filterCategory) return false;
    if (searchTerm && !tc.scenario.toLowerCase().includes(searchTerm.toLowerCase())) return false;
    return true;
  }) || [];

  const getStats = () => {
    if (!selectedSuite?.E2ETestCase) return { total: 0, critical: 0, high: 0, medium: 0, low: 0 };
    const cases = selectedSuite.E2ETestCase;
    return {
      total: cases.length,
      critical: cases.filter(c => c.priority === 'critical').length,
      high: cases.filter(c => c.priority === 'high').length,
      medium: cases.filter(c => c.priority === 'medium').length,
      low: cases.filter(c => c.priority === 'low').length
    };
  };

  const exportToCSV = () => {
    if (!selectedSuite?.E2ETestCase) return;
    const headers = ['Test Case ID', 'Scenario', 'Objective', 'Expected Outcome', 'Priority', 'Category'];
    const rows = selectedSuite.E2ETestCase.map(tc => [
      tc.testCaseId,
      `"${tc.scenario}"`,
      `"${tc.objective}"`,
      `"${tc.expectedOutcome}"`,
      tc.priority,
      tc.category
    ]);
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${selectedSuite.name.replace(/\s+/g, '_')}_test_cases.csv`;
    a.click();
  };

  const stats = getStats();

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />

      <main className="pt-24 pb-16 px-4">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-xl bg-gradient-to-r from-green-500/20 to-brand-deep/20">
                <TestTube className="w-8 h-8 text-green-400" />
              </div>
              <div>
                <h1 className="text-3xl font-bold text-white">E2E Test Management</h1>
                <p className="text-gray-400">Comprehensive end-to-end test suite management</p>
              </div>
            </div>

            <div className="flex gap-3">
              <button
                onClick={seedStuffBalls}
                disabled={seeding}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-secondary text-white hover:bg-brand-secondary-deep disabled:opacity-50"
              >
                {seeding ? <Loader2 className="w-4 h-4 animate-spin" /> : <Package className="w-4 h-4" />}
                {seeding ? 'Creating...' : 'Seed Stuff Balls Suite'}
              </button>
              <button
                onClick={fetchSuites}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-700 text-white hover:bg-slate-600"
              >
                <RefreshCw className="w-4 h-4" />
                Refresh
              </button>
            </div>
          </div>

          <div className="grid grid-cols-12 gap-6">
            {/* Suite List */}
            <div className="col-span-4">
              <div className="rounded-xl border border-slate-700 bg-slate-900 p-4">
                <h2 className="text-lg font-semibold text-white mb-4">Test Suites</h2>

                {loading ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-6 h-6 text-brand animate-spin" />
                  </div>
                ) : suites.length === 0 ? (
                  <div className="text-center py-8">
                    <TestTube className="w-12 h-12 text-gray-600 mx-auto mb-3" />
                    <p className="text-gray-400">No test suites found</p>
                    <p className="text-gray-500 text-sm mt-1">Click "Seed Stuff Balls Suite" to create the demo suite</p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {suites.map(suite => (
                      <button
                        key={suite.id}
                        onClick={() => fetchSuiteDetails(suite.id)}
                        className={`w-full text-left p-4 rounded-lg transition-colors ${
                          selectedSuite?.id === suite.id
                            ? 'bg-brand-deep/20 border border-brand-deep/30'
                            : 'bg-slate-800 hover:bg-slate-700'
                        }`}
                      >
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="font-medium text-white truncate pr-2">{suite.name}</h3>
                          <span className={`px-2 py-0.5 rounded text-xs ${
                            suite.status === 'active' ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'
                          }`}>
                            {suite.status}
                          </span>
                        </div>
                        <div className="flex items-center gap-3 text-sm text-gray-400">
                          <span className="flex items-center gap-1">
                            <FileText className="w-3 h-3" />
                            {suite._count?.E2ETestCase || 0} cases
                          </span>
                          <span className="flex items-center gap-1">
                            <Play className="w-3 h-3" />
                            {suite._count?.E2ETestRun || 0} runs
                          </span>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Suite Details */}
            <div className="col-span-8">
              {selectedSuite ? (
                <div className="space-y-6">
                  {/* Suite Header */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-6">
                    <div className="flex items-start justify-between mb-4">
                      <div>
                        <h2 className="text-2xl font-bold text-white">{selectedSuite.name}</h2>
                        <p className="text-gray-400 mt-1">{selectedSuite.description}</p>
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={exportToCSV}
                          className="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-700 text-white hover:bg-slate-600"
                        >
                          <Download className="w-4 h-4" />
                          Export
                        </button>
                        <button
                          onClick={startTestRun}
                          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-green-500 text-white hover:bg-green-600"
                        >
                          <Play className="w-4 h-4" />
                          Start Run
                        </button>
                      </div>
                    </div>

                    {/* Stats */}
                    <div className="grid grid-cols-5 gap-4">
                      <div className="p-3 rounded-lg bg-slate-800">
                        <p className="text-gray-400 text-sm">Total</p>
                        <p className="text-2xl font-bold text-white">{stats.total}</p>
                      </div>
                      <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                        <p className="text-red-400 text-sm">Critical</p>
                        <p className="text-2xl font-bold text-red-400">{stats.critical}</p>
                      </div>
                      <div className="p-3 rounded-lg bg-orange-500/10 border border-orange-500/20">
                        <p className="text-orange-400 text-sm">High</p>
                        <p className="text-2xl font-bold text-orange-400">{stats.high}</p>
                      </div>
                      <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
                        <p className="text-yellow-400 text-sm">Medium</p>
                        <p className="text-2xl font-bold text-yellow-400">{stats.medium}</p>
                      </div>
                      <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/20">
                        <p className="text-blue-400 text-sm">Low</p>
                        <p className="text-2xl font-bold text-blue-400">{stats.low}</p>
                      </div>
                    </div>
                  </div>

                  {/* Recent Runs */}
                  {selectedSuite.E2ETestRun && selectedSuite.E2ETestRun.length > 0 && (
                    <div className="rounded-xl border border-slate-700 bg-slate-900 p-4">
                      <h3 className="text-lg font-semibold text-white mb-3">Recent Runs</h3>
                      <div className="space-y-2">
                        {selectedSuite.E2ETestRun.slice(0, 5).map((run: TestRun) => (
                          <div key={run.id} className="flex items-center justify-between p-3 rounded-lg bg-slate-800">
                            <div className="flex items-center gap-3">
                              {statusIcons[run.status] || statusIcons.pending}
                              <span className="text-white font-medium">Run #{run.runNumber}</span>
                              <span className="text-gray-400 text-sm">
                                {new Date(run.startedAt).toLocaleString()}
                              </span>
                            </div>
                            <div className="flex items-center gap-4 text-sm">
                              <span className="text-green-400">{run.passedCases} passed</span>
                              <span className="text-red-400">{run.failedCases} failed</span>
                              <span className="text-yellow-400">{run.blockedCases} blocked</span>
                              <span className="text-gray-400">{run.skippedCases} skipped</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Test Cases */}
                  <div className="rounded-xl border border-slate-700 bg-slate-900 p-4">
                    <div className="flex items-center justify-between mb-4">
                      <h3 className="text-lg font-semibold text-white">Test Cases ({filteredCases.length})</h3>
                      <div className="flex items-center gap-3">
                        <div className="relative">
                          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                          <input
                            type="text"
                            placeholder="Search..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pl-9 pr-3 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white text-sm w-48"
                          />
                        </div>
                        <select
                          value={filterPriority}
                          onChange={(e) => setFilterPriority(e.target.value)}
                          className="px-3 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white text-sm"
                        >
                          <option value="">All Priorities</option>
                          <option value="critical">Critical</option>
                          <option value="high">High</option>
                          <option value="medium">Medium</option>
                          <option value="low">Low</option>
                        </select>
                        <select
                          value={filterCategory}
                          onChange={(e) => setFilterCategory(e.target.value)}
                          className="px-3 py-2 rounded-lg bg-slate-800 border border-slate-600 text-white text-sm"
                        >
                          <option value="">All Categories</option>
                          <option value="happy_path">Happy Path</option>
                          <option value="edge_case">Edge Case</option>
                          <option value="error_handling">Error Handling</option>
                          <option value="integration">Integration</option>
                        </select>
                      </div>
                    </div>

                    <div className="space-y-2 max-h-[600px] overflow-y-auto">
                      {filteredCases.map(tc => (
                        <div
                          key={tc.id}
                          className="rounded-lg bg-slate-800 overflow-hidden"
                        >
                          <button
                            onClick={() => toggleCase(tc.id)}
                            className="w-full flex items-center justify-between p-4 hover:bg-slate-700/50"
                          >
                            <div className="flex items-center gap-3">
                              {expandedCases.has(tc.id) ? (
                                <ChevronDown className="w-4 h-4 text-gray-400" />
                              ) : (
                                <ChevronRight className="w-4 h-4 text-gray-400" />
                              )}
                              <span className="font-mono text-brand text-sm">{tc.testCaseId}</span>
                              <span className="text-white">{tc.scenario}</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <span className={`px-2 py-0.5 rounded text-xs border ${priorityColors[tc.priority]}`}>
                                {tc.priority}
                              </span>
                              <span className={`px-2 py-0.5 rounded text-xs ${categoryColors[tc.category]}`}>
                                {tc.category.replace('_', ' ')}
                              </span>
                              {tc.lastResult && statusIcons[tc.lastResult]}
                            </div>
                          </button>

                          {expandedCases.has(tc.id) && (
                            <div className="px-4 pb-4 border-t border-slate-700">
                              <div className="grid grid-cols-2 gap-4 mt-4">
                                <div>
                                  <h4 className="text-gray-400 text-sm font-medium mb-1">Objective</h4>
                                  <p className="text-white text-sm">{tc.objective}</p>
                                </div>
                                <div>
                                  <h4 className="text-gray-400 text-sm font-medium mb-1">Expected Outcome</h4>
                                  <p className="text-green-400 text-sm">{tc.expectedOutcome}</p>
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              ) : (
                <div className="rounded-xl border border-slate-700 bg-slate-900 p-12 text-center">
                  <BarChart3 className="w-16 h-16 text-gray-600 mx-auto mb-4" />
                  <h3 className="text-xl font-semibold text-white mb-2">Select a Test Suite</h3>
                  <p className="text-gray-400">Choose a test suite from the left panel to view details and manage test cases.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}
