// ToolHealthPanelRefactored - Refactored tool health panel with separated concerns
import React, { useState, useCallback, useEffect } from 'react';
import { get, post } from '../../api.js';
import Card from '../Card';
import ToolHealthDisplay from './ToolHealthDisplay';
import ToolHealthCard from './ToolHealthCard';
import BulkAutoFix from './BulkAutoFix';

function ToolHealthPanelRefactored() {
  // State management
  const [health, setHealth] = useState(null);
  const [loading, setLoading] = useState(true);
  const [providers, setProviders] = useState({});
  const [availableProviders, setAvailableProviders] = useState([]);
  const [saving, setSaving] = useState(null);
  const [fixing, setFixing] = useState({});  // tool -> {action, status}
  const [bulkFixing, setBulkFixing] = useState(false);
  const [fixResults, setFixResults] = useState([]);

  // Fix action styling
  const fixActionClass = {
    install: "bg-emerald-100 text-emerald-700",
    config: "bg-blue-100 text-blue-700",
    start_container: "bg-purple-100 text-purple-700",
    start_vm: "bg-orange-100 text-orange-700",
    info: "bg-gray-100 text-gray-600",
    retry: "bg-amber-100 text-amber-700",
  };

  // Load cached readiness snapshot (fast, no re-probe)
  const loadReadiness = useCallback(async () => {
    try {
      const data = await get("/dashboard/tools/readiness");
      if (data && data.tools && data.tools.length > 0) {
        setHealth(data);
        setAvailableProviders(data.providers_configured || []);
        setLoading(false);
        return true;
      }
    } catch (e) {
      console.warn("Readiness snapshot not available, falling back to healthcheck", e);
    }
    return false;
  }, []);

  // Full health check (slow, re-probes everything)
  const loadHealth = useCallback(async () => {
    setLoading(true);
    try {
      const data = await get("/dashboard/tools/healthcheck");
      setHealth(data || null);
      setProviders(data?.tool_providers || {});
      setAvailableProviders(data?.providers_configured || []);
    } catch (e) {
      console.error("Healthcheck failed:", e);
    } finally {
      setLoading(false);
    }
  }, []);

  // Initialize: fast snapshot first, then full check only if needed
  useEffect(() => {
    loadReadiness().then(ok => { if (!ok) loadHealth(); });
  }, [loadReadiness, loadHealth]);

  // Subscribe to SSE for live tool readiness updates
  useEffect(() => {
    if (!globalThis.SSEService) return;
    const events = new Set(["ToolStartupComplete"]);
    return globalThis.SSEService.subscribe(
      "ToolHealthPanel",
      events,
      () => { loadReadiness(); }
    );
  }, [loadReadiness]);

  // Handle provider change
  const handleProviderChange = async (toolName, provider) => {
    setSaving(toolName);
    try {
      await post("/dashboard/tools/provider", { tool: toolName, provider });
      setProviders(prev => ({ ...prev, [toolName]: provider }));
    } catch (e) {
      console.error("Provider change failed:", e);
    } finally {
      setSaving(null);
    }
  };

  // Handle auto-fix for individual tools
  const handleAutoFix = async (toolName, fix) => {
    const action = fix.action;
    setFixing(prev => ({ ...prev, [toolName]: { action, status: 'running' } }));
    
    try {
      const result = await post("/dashboard/tools/autofix", {
        tool_name: toolName,
        fix_action: action,
        command: fix.command || "",
      });
      
      setFixResults(prev => [...prev, { tool: toolName, action, result, time: Date.now() }]);
      
      if (result.ticket_created) {
        alert(`Ticket created for human action: ${result.ticket_created.id}`);
      }
      
      // Refresh health check to see if issue was resolved
      await loadHealth();
    } catch (e) {
      console.error("Auto-fix failed:", e);
      setFixResults(prev => [...prev, { tool: toolName, action, error: e.message, time: Date.now() }]);
    } finally {
      setFixing(prev => ({ ...prev, [toolName]: null }));
    }
  };

  // Handle bulk auto-fix
  const handleBulkAutoFix = async () => {
    setBulkFixing(true);
    setFixResults([]);
    
    try {
      const result = await post("/dashboard/tools/autofix/bulk", {});
      
      const executed = result.executed || 0;
      const humanRequired = result.human_required || 0;
      const failed = result.failed || 0;
      
      let message = `Auto-fix complete:\n`;
      message += `- ${executed} fixes executed automatically\n`;
      message += `- ${humanRequired} tickets created for human action\n`;
      if (failed > 0) {
        message += `- ${failed} fixes failed\n`;
      }
      
      alert(message);
      
      // Refresh health check
      await loadHealth();
    } catch (e) {
      console.error("Bulk auto-fix failed:", e);
      alert(`Bulk auto-fix failed: ${e.message || 'Unknown error'}`);
    } finally {
      setBulkFixing(false);
    }
  };

  // Extract data for components
  const summary = health?.summary;
  const tools = Array.isArray(health?.tools) ? health.tools : [];
  const degradedCount = (summary?.degraded || 0) + (summary?.unavailable || 0);

  return (
    <Card title={
      summary 
        ? `Tool Health (${summary.ok} ok, ${summary.degraded} degraded, ${summary.unavailable} unavailable)`
        : "Tool Health"
    }>
      {/* Health Display */}
      <ToolHealthDisplay 
        health={health} 
        loading={loading} 
        onRefresh={loadHealth} 
      />

      {/* Bulk Auto-fix */}
      <BulkAutoFix
        degradedCount={degradedCount}
        isBulkFixing={bulkFixing}
        onBulkAutoFix={handleBulkAutoFix}
        fixResults={fixResults}
      />

      {/* Tool Cards */}
      {tools.length > 0 && (
        <div className="space-y-3">
          {tools.map(tool => (
            <ToolHealthCard
              key={tool.name}
              tool={tool}
              currentProvider={providers[tool.name]}
              availableProviders={availableProviders}
              onProviderChange={handleProviderChange}
              isSaving={saving}
              isFixing={fixing}
              onAutoFix={handleAutoFix}
              fixActionClass={fixActionClass}
            />
          ))}
        </div>
      )}
    </Card>
  );
}

export default ToolHealthPanelRefactored;
