/**
 * BulkSSHResultsModal Component
 * 
 * Displays detailed results of bulk SSH command execution.
 * Features:
 * - Tabbed view (All / Success / Failed)
 * - Expandable stdout/stderr
 * - Export to CSV
 * - Retry failed
 */

import { useState, useMemo } from 'react';
import { X, CheckCircle, XCircle, Terminal, Download, AlertCircle, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from './shared/Button';

interface SSHResult {
  machine_id: string;
  machine_name: string;
  hostname: string;
  status: 'success' | 'failed' | 'timeout' | 'no_credentials';
  exit_code?: number;
  stdout?: string;
  stderr?: string;
  error?: string;
  execution_time_ms?: number;
  executed_at: string;
}

interface SSHResponse {
  total: number;
  success: number;
  failed: number;
  results: SSHResult[];
  execution_time_ms: number;
  command: string;
  started_at: string;
  completed_at: string;
}

interface BulkSSHResultsModalProps {
  isOpen: boolean;
  results: SSHResponse | null;
  onClose: () => void;
  onRetryFailed?: () => void;
}

type FilterTab = 'all' | 'success' | 'failed';

export function BulkSSHResultsModal({
  isOpen,
  results,
  onClose,
  onRetryFailed
}: BulkSSHResultsModalProps) {
  
  const [activeTab, setActiveTab] = useState<FilterTab>('all');
  const [expandedMachines, setExpandedMachines] = useState<Set<string>>(new Set());

  // Filter results
  const filteredResults = useMemo(() => {
    if (!results) return [];
    
    switch (activeTab) {
      case 'success':
        return results.results.filter(r => r.status === 'success');
      case 'failed':
        return results.results.filter(r => r.status !== 'success');
      default:
        return results.results;
    }
  }, [results, activeTab]);

  // Toggle expand/collapse for machine
  const toggleExpand = (machineId: string) => {
    setExpandedMachines(prev => {
      const newSet = new Set(prev);
      if (newSet.has(machineId)) {
        newSet.delete(machineId);
      } else {
        newSet.add(machineId);
      }
      return newSet;
    });
  };

  // Expand all
  const expandAll = () => {
    setExpandedMachines(new Set(filteredResults.map(r => r.machine_id)));
  };

  // Collapse all
  const collapseAll = () => {
    setExpandedMachines(new Set());
  };

  // Export to CSV
  const handleExportCSV = () => {
    if (!results) return;
    
    const csvHeaders = ['Machine Name', 'Hostname', 'Status', 'Exit Code', 'Stdout', 'Stderr', 'Error'];
    const csvRows = results.results.map(r => [
      r.machine_name,
      r.hostname,
      r.status,
      r.exit_code?.toString() || 'N/A',
      r.stdout || '',
      r.stderr || '',
      r.error || ''
    ]);
    
    const csvContent = [
      csvHeaders.join(','),
      ...csvRows.map(row => row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `ssh-results-${new Date().toISOString()}.csv`;
    link.click();
  };

  if (!isOpen || !results) return null;

  const hasFailures = results.failed > 0;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
      <div className="bg-kaspersky-bg-card rounded-lg shadow-2xl border border-kaspersky-border max-w-5xl w-full mx-4 max-h-[90vh] flex flex-col select-none">
        
        {/* Header */}
        <div className="p-6 border-b border-kaspersky-border">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-bold text-kaspersky-text-dark">SSH Command Results</h2>
              <p className="text-sm text-kaspersky-text-light mt-1">
                Completed in {(results.execution_time_ms / 1000).toFixed(2)}s
              </p>
              <code className="text-xs bg-kaspersky-bg px-2 py-1 rounded mt-2 inline-block">
                {results.command}
              </code>
            </div>
            <button
              onClick={onClose}
              className="text-kaspersky-text-light hover:text-kaspersky-text-dark transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          {/* Summary Stats */}
          <div className="grid grid-cols-3 gap-3 mt-4">
            <div className="bg-kaspersky-bg p-3 rounded-lg text-center">
              <div className="text-2xl font-bold text-kaspersky-text-dark">{results.total}</div>
              <div className="text-xs text-kaspersky-text-light mt-1">Total</div>
            </div>
            <div className="bg-green-50 p-3 rounded-lg text-center">
              <div className="text-2xl font-bold text-kaspersky-success">{results.success}</div>
              <div className="text-xs text-kaspersky-success mt-1">Success</div>
            </div>
            <div className="bg-red-50 p-3 rounded-lg text-center">
              <div className="text-2xl font-bold text-kaspersky-danger">{results.failed}</div>
              <div className="text-xs text-kaspersky-danger mt-1">Failed</div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-kaspersky-border px-6 justify-between items-center">
          <div className="flex">
            <button
              onClick={() => setActiveTab('all')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'all'
                  ? 'border-kaspersky-primary text-kaspersky-primary'
                  : 'border-transparent text-kaspersky-text-light hover:text-kaspersky-text-dark'
              }`}
            >
              All ({results.total})
            </button>
            <button
              onClick={() => setActiveTab('success')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'success'
                  ? 'border-kaspersky-success text-kaspersky-success'
                  : 'border-transparent text-kaspersky-text-light hover:text-kaspersky-text-dark'
              }`}
            >
              Success ({results.success})
            </button>
            <button
              onClick={() => setActiveTab('failed')}
              className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === 'failed'
                  ? 'border-kaspersky-danger text-kaspersky-danger'
                  : 'border-transparent text-kaspersky-text-light hover:text-kaspersky-text-dark'
              }`}
            >
              Failed ({results.failed})
            </button>
          </div>

          {/* Expand/Collapse controls */}
          <div className="flex gap-2">
            <button
              onClick={expandAll}
              className="text-xs text-kaspersky-primary hover:underline"
            >
              Expand All
            </button>
            <span className="text-kaspersky-text-light">|</span>
            <button
              onClick={collapseAll}
              className="text-xs text-kaspersky-primary hover:underline"
            >
              Collapse All
            </button>
          </div>
        </div>

        {/* Results List */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="space-y-2">
            {filteredResults.map((result) => {
              const isExpanded = expandedMachines.has(result.machine_id);
              const hasOutput = result.stdout || result.stderr;

              return (
                <div
                  key={result.machine_id}
                  className="border border-kaspersky-border rounded-lg overflow-hidden"
                >
                  {/* Machine Header */}
                  <button
                    onClick={() => hasOutput && toggleExpand(result.machine_id)}
                    className="w-full p-4 flex items-center justify-between hover:bg-kaspersky-bg transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      {/* Status Icon */}
                      <div title={result.status}>
                        {result.status === 'success' ? (
                          <CheckCircle size={20} className="text-kaspersky-success" />
                        ) : result.status === 'timeout' ? (
                          <AlertCircle size={20} className="text-kaspersky-warning" />
                        ) : (
                          <XCircle size={20} className="text-kaspersky-danger" />
                        )}
                      </div>

                      {/* Machine Info */}
                      <div className="text-left">
                        <div className="font-medium text-kaspersky-text-dark">{result.machine_name}</div>
                        <div className="text-sm text-kaspersky-text-light">{result.hostname}</div>
                      </div>

                      {/* Exit Code Badge */}
                      {result.exit_code !== undefined && (
                        <span className={`px-2 py-1 rounded text-xs font-mono ${
                          result.exit_code === 0
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'
                        }`}>
                          Exit: {result.exit_code}
                        </span>
                      )}

                      {/* Error Badge */}
                      {result.error && (
                        <span className="px-2 py-1 rounded text-xs bg-red-100 text-red-800 max-w-xs truncate">
                          {result.error}
                        </span>
                      )}

                      {/* Execution Time */}
                      {result.execution_time_ms && (
                        <span className="text-xs text-kaspersky-text-light">
                          {result.execution_time_ms}ms
                        </span>
                      )}
                    </div>

                    {/* Expand/Collapse Icon */}
                    {hasOutput && (
                      <div>
                        {isExpanded ? (
                          <ChevronUp size={20} className="text-kaspersky-text-light" />
                        ) : (
                          <ChevronDown size={20} className="text-kaspersky-text-light" />
                        )}
                      </div>
                    )}
                  </button>

                  {/* Expanded Output */}
                  {isExpanded && hasOutput && (
                    <div className="border-t border-kaspersky-border bg-kaspersky-bg p-4 space-y-3">
                      {/* Stdout */}
                      {result.stdout && (
                        <div>
                          <div className="text-xs font-semibold text-kaspersky-text-dark mb-1">STDOUT:</div>
                          <pre className="bg-white border border-kaspersky-border rounded p-3 text-xs overflow-x-auto font-mono whitespace-pre-wrap">
                            {result.stdout}
                          </pre>
                        </div>
                      )}

                      {/* Stderr */}
                      {result.stderr && (
                        <div>
                          <div className="text-xs font-semibold text-kaspersky-danger mb-1">STDERR:</div>
                          <pre className="bg-red-50 border border-red-200 rounded p-3 text-xs overflow-x-auto font-mono whitespace-pre-wrap text-red-800">
                            {result.stderr}
                          </pre>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
          
          {filteredResults.length === 0 && (
            <div className="text-center py-8 text-kaspersky-text-light">
              No results to display
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-6 border-t border-kaspersky-border flex justify-between items-center">
          <div className="flex gap-2">
            {hasFailures && onRetryFailed && (
              <Button
                onClick={onRetryFailed}
                variant="secondary"
                size="sm"
                leftIcon={<Terminal size={16} />}
              >
                Retry Failed ({results.failed})
              </Button>
            )}
          </div>
          
          <div className="flex gap-2">
            <Button
              onClick={handleExportCSV}
              variant="secondary"
              size="sm"
              leftIcon={<Download size={16} />}
            >
              Export CSV
            </Button>
            <Button
              onClick={onClose}
              variant="primary"
              size="sm"
            >
              Close
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

