/**
 * BulkResultsModal Component
 * 
 * Displays detailed results of bulk operations.
 * Features:
 * - Tabbed view (All / Available / Unavailable)
 * - Sortable table
 * - Export to CSV
 * - Retry failed operations
 */

import { useState, useMemo } from 'react';
import { X, CheckCircle, XCircle, Clock, Download, AlertCircle } from 'lucide-react';
import { Button } from './shared/Button';
import { BulkHealthCheckResponse } from '../services/bulk-operations-api';

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

type FilterTab = 'all' | 'available' | 'unavailable';

export function BulkResultsModal({
  isOpen,
  results,
  onClose,
  onRetryFailed
}: BulkResultsModalProps) {
  
  const [activeTab, setActiveTab] = useState<FilterTab>('all');
  const [sortBy, setSortBy] = useState<'name' | 'status' | 'response_time'>('name');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  // Filter and sort results
  const filteredResults = useMemo(() => {
    if (!results) return [];
    
    let filtered = results.results;
    
    // Apply filter
    switch (activeTab) {
      case 'available':
        filtered = filtered.filter(r => r.available);
        break;
      case 'unavailable':
        filtered = filtered.filter(r => !r.available);
        break;
      default:
        // all
        break;
    }
    
    // Apply sort
    return [...filtered].sort((a, b) => {
      let comparison = 0;
      
      switch (sortBy) {
        case 'name':
          comparison = a.machine_name.localeCompare(b.machine_name);
          break;
        case 'status':
          comparison = a.status.localeCompare(b.status);
          break;
        case 'response_time':
          comparison = (a.response_time_ms || 9999) - (b.response_time_ms || 9999);
          break;
      }
      
      return sortOrder === 'asc' ? comparison : -comparison;
    });
  }, [results, activeTab, sortBy, sortOrder]);

  // Export to CSV
  const handleExportCSV = () => {
    if (!results) return;
    
    const csvHeaders = ['Machine Name', 'Hostname', 'Status', 'Available', 'Response Time (ms)', 'Error'];
    const csvRows = results.results.map(r => [
      r.machine_name,
      r.hostname,
      r.status,
      r.available ? 'Yes' : 'No',
      r.response_time_ms?.toString() || 'N/A',
      r.error || ''
    ]);
    
    const csvContent = [
      csvHeaders.join(','),
      ...csvRows.map(row => row.map(cell => `"${cell}"`).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 = `health-check-results-${new Date().toISOString()}.csv`;
    link.click();
  };

  // Toggle sort
  const handleSort = (column: typeof sortBy) => {
    if (sortBy === column) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(column);
      setSortOrder('asc');
    }
  };

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

  const hasFailures = results.unavailable > 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-4xl 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">Health Check Results</h2>
              <p className="text-sm text-kaspersky-text-light mt-1">
                Completed in {(results.execution_time_ms / 1000).toFixed(2)}s
              </p>
            </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-4 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.available}</div>
              <div className="text-xs text-kaspersky-success mt-1">Available</div>
            </div>
            <div className="bg-red-50 p-3 rounded-lg text-center">
              <div className="text-2xl font-bold text-kaspersky-danger">{results.unavailable}</div>
              <div className="text-xs text-kaspersky-danger mt-1">Unavailable</div>
            </div>
            <div className="bg-blue-50 p-3 rounded-lg text-center">
              <div className="text-2xl font-bold text-blue-600">{results.success}</div>
              <div className="text-xs text-blue-600 mt-1">Success</div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-kaspersky-border px-6">
          <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('available')}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
              activeTab === 'available'
                ? 'border-kaspersky-success text-kaspersky-success'
                : 'border-transparent text-kaspersky-text-light hover:text-kaspersky-text-dark'
            }`}
          >
            Available ({results.available})
          </button>
          <button
            onClick={() => setActiveTab('unavailable')}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
              activeTab === 'unavailable'
                ? 'border-kaspersky-danger text-kaspersky-danger'
                : 'border-transparent text-kaspersky-text-light hover:text-kaspersky-text-dark'
            }`}
          >
            Unavailable ({results.unavailable})
          </button>
        </div>

        {/* Table */}
        <div className="flex-1 overflow-y-auto p-6">
          <table className="w-full">
            <thead>
              <tr className="border-b border-kaspersky-border">
                <th className="text-left p-2 text-sm font-semibold text-kaspersky-text-dark">Status</th>
                <th 
                  className="text-left p-2 text-sm font-semibold text-kaspersky-text-dark cursor-pointer hover:text-kaspersky-primary"
                  onClick={() => handleSort('name')}
                >
                  Machine Name {sortBy === 'name' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="text-left p-2 text-sm font-semibold text-kaspersky-text-dark">Hostname</th>
                <th 
                  className="text-left p-2 text-sm font-semibold text-kaspersky-text-dark cursor-pointer hover:text-kaspersky-primary"
                  onClick={() => handleSort('response_time')}
                >
                  Response {sortBy === 'response_time' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="text-left p-2 text-sm font-semibold text-kaspersky-text-dark">Error</th>
              </tr>
            </thead>
            <tbody>
              {filteredResults.map((result) => (
                <tr key={result.machine_id} className="border-b border-kaspersky-border hover:bg-kaspersky-bg transition-colors">
                  <td className="p-2">
                    <div title={result.available ? "Available" : result.status === 'timeout' ? "Timeout" : "Unavailable"}>
                      {result.available ? (
                        <CheckCircle size={18} className="text-kaspersky-success" />
                      ) : result.status === 'timeout' ? (
                        <Clock size={18} className="text-kaspersky-warning" />
                      ) : (
                        <XCircle size={18} className="text-kaspersky-danger" />
                      )}
                    </div>
                  </td>
                  <td className="p-2 text-sm font-medium text-kaspersky-text-dark">{result.machine_name}</td>
                  <td className="p-2 text-sm text-kaspersky-text-light">{result.hostname}</td>
                  <td className="p-2 text-sm text-kaspersky-text-light">
                    {result.response_time_ms ? `${result.response_time_ms}ms` : 'N/A'}
                  </td>
                  <td className="p-2 text-sm text-kaspersky-danger">
                    {result.error && (
                      <div className="flex items-center gap-1" title={result.error}>
                        <AlertCircle size={14} />
                        <span className="truncate max-w-[200px]">{result.error}</span>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          
          {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={<AlertCircle size={16} />}
              >
                Retry Failed ({results.unavailable})
              </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>
  );
}

