import React, { useState, useEffect } from 'react';
import { documentService } from '../services/documentService';
import { cn } from '../utils/cn';

interface AgenticRAGSession {
  id: string;
  strategy: string;
  status: string;
  totalAgents: number;
  completedAgents: number;
  failedAgents: number;
  overallValidationScore: number;
  processingTimeMs: number;
  apiCallsCount: number;
  totalCost: number;
  createdAt: string;
  completedAt?: string;
}

interface AgentExecution {
  id: string;
  agentName: string;
  stepNumber: number;
  status: string;
  processingTimeMs: number;
  retryCount: number;
  errorMessage?: string;
  createdAt: string;
  updatedAt: string;
}

interface QualityMetric {
  id: string;
  metricType: string;
  metricValue: number;
  metricDetails: any;
  createdAt: string;
}

interface SessionDetails {
  session: AgenticRAGSession;
  executions: AgentExecution[];
  qualityMetrics: QualityMetric[];
}

interface AgenticRAGSessionDetailsProps {
  sessionId: string;
  onClose?: () => void;
}

const AgenticRAGSessionDetails: React.FC<AgenticRAGSessionDetailsProps> = ({ 
  sessionId, 
  onClose 
}) => {
  const [sessionDetails, setSessionDetails] = useState<SessionDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadSessionDetails();
  }, [sessionId]);

  const loadSessionDetails = async () => {
    try {
      setLoading(true);
      setError(null);
      const details = await documentService.getAgenticRAGSessionDetails(sessionId);
      setSessionDetails(details);
    } catch (err) {
      setError('Failed to load session details');
      console.error('Session details loading error:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatTime = (ms: number): string => {
    if (ms < 1000) return `${Math.round(ms)}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}m`;
  };

  const formatCost = (cost: number): string => {
    return `$${cost.toFixed(4)}`;
  };

  const getStatusColor = (status: string): string => {
    switch (status.toLowerCase()) {
      case 'completed':
        return 'text-green-600 bg-green-100';
      case 'failed':
        return 'text-red-600 bg-red-100';
      case 'processing':
        return 'text-yellow-600 bg-yellow-100';
      case 'pending':
        return 'text-blue-600 bg-blue-100';
      default:
        return 'text-gray-600 bg-gray-100';
    }
  };

  const getAgentDisplayName = (agentName: string): string => {
    return agentName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex">
          <div className="flex-shrink-0">
            <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <h3 className="text-sm font-medium text-red-800">Error loading session details</h3>
            <p className="mt-1 text-sm text-red-700">{error}</p>
          </div>
        </div>
      </div>
    );
  }

  if (!sessionDetails) {
    return (
      <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
        <p className="text-yellow-800">No session details found</p>
      </div>
    );
  }

  const { session, executions, qualityMetrics } = sessionDetails;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-gray-900">Session Details</h2>
          <p className="text-sm text-gray-600">Session ID: {session.id}</p>
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        )}
      </div>

      {/* Session Overview */}
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Session Overview</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">Strategy</p>
            <p className="text-lg font-semibold text-gray-900">
              {session.strategy.replace(/_/g, ' ').toUpperCase()}
            </p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <div className="flex items-center">
              <span className={cn(
                "inline-flex px-2 py-1 text-xs font-semibold rounded-full",
                getStatusColor(session.status)
              )}>
                {session.status}
              </span>
            </div>
            <p className="text-sm font-medium text-gray-500 mt-1">Status</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">Processing Time</p>
            <p className="text-lg font-semibold text-gray-900">
              {formatTime(session.processingTimeMs)}
            </p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">Total Cost</p>
            <p className="text-lg font-semibold text-gray-900">
              {formatCost(session.totalCost)}
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">Agents Progress</p>
            <p className="text-lg font-semibold text-gray-900">
              {session.completedAgents}/{session.totalAgents} completed
            </p>
            <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
              <div 
                className="bg-blue-600 h-2 rounded-full" 
                style={{ width: `${(session.completedAgents / session.totalAgents) * 100}%` }}
              ></div>
            </div>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">API Calls</p>
            <p className="text-lg font-semibold text-gray-900">
              {session.apiCallsCount}
            </p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-sm font-medium text-gray-500">Validation Score</p>
            <p className="text-lg font-semibold text-gray-900">
              {session.overallValidationScore ? `${(session.overallValidationScore * 100).toFixed(1)}%` : 'N/A'}
            </p>
          </div>
        </div>

        <div className="mt-4 text-sm text-gray-600">
          <p><strong>Created:</strong> {new Date(session.createdAt).toLocaleString()}</p>
          {session.completedAt && (
            <p><strong>Completed:</strong> {new Date(session.completedAt).toLocaleString()}</p>
          )}
        </div>
      </div>

      {/* Agent Executions */}
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Agent Executions</h3>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Step</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Agent</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Time</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Retries</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Error</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {executions.map((execution) => (
                <tr key={execution.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {execution.stepNumber}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {getAgentDisplayName(execution.agentName)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={cn(
                      "inline-flex px-2 py-1 text-xs font-semibold rounded-full",
                      getStatusColor(execution.status)
                    )}>
                      {execution.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {formatTime(execution.processingTimeMs)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {execution.retryCount}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-900">
                    {execution.errorMessage ? (
                      <span className="text-red-600 text-xs">{execution.errorMessage}</span>
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Quality Metrics */}
      {qualityMetrics.length > 0 && (
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Quality Metrics</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {qualityMetrics.map((metric) => (
              <div key={metric.id} className="bg-gray-50 rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-900 mb-2">
                  {metric.metricType.charAt(0).toUpperCase() + metric.metricType.slice(1)}
                </h4>
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-xs text-gray-600">Score:</span>
                    <span className="text-sm font-medium">
                      {(metric.metricValue * 100).toFixed(1)}%
                    </span>
                  </div>
                  {metric.metricDetails && (
                    <div className="text-xs text-gray-600">
                      <details>
                        <summary className="cursor-pointer hover:text-gray-800">Details</summary>
                        <pre className="mt-1 text-xs bg-white p-2 rounded border overflow-auto">
                          {JSON.stringify(metric.metricDetails, null, 2)}
                        </pre>
                      </details>
                    </div>
                  )}
                  <div className="text-xs text-gray-500">
                    {new Date(metric.createdAt).toLocaleString()}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default AgenticRAGSessionDetails; 