import React, { useState, useCallback } from 'react';
import { generateProResponse } from '../services/geminiService';
import { Spinner } from '../components/Spinner';
import { MarkdownRenderer } from '../components/MarkdownRenderer';

const SystemMaintenanceModule: React.FC = () => {
  const [anomaly, setAnomaly] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [protocol, setProtocol] = useState<string | null>(null);

  const handleQuery = useCallback(async () => {
    if (!anomaly.trim()) {
      setError('Please describe the system anomaly.');
      return;
    }
    setIsLoading(true);
    setError(null);
    setProtocol(null);

    const prompt = `Acting as the Maintenance and Self-Healing AI for the Sentient Constellation Codex, a complex autonomous system has reported the following anomaly: "${anomaly}". 
    
    Provide a detailed maintenance and auto-healing protocol. Your response should include:
    1. A preliminary diagnosis of potential root causes.
    2. Immediate containment procedures to prevent system-wide failure.
    3. A step-by-step automated self-healing sequence.
    4. Recommendations for long-term preventative measures.
    
    Your language should be technical, precise, and reassuring, as befits a master systems AI.`;

    try {
      const result = await generateProResponse(prompt);
      setProtocol(result.text);
    } catch (e: any) {
      setError(e.message || 'An unknown error occurred while generating protocols.');
    } finally {
      setIsLoading(false);
    }
  }, [anomaly]);

  return (
    <div className="flex flex-col h-full w-full max-w-5xl mx-auto">
      <h2 className="text-2xl font-bold text-cyan-300 mb-4 text-center">System Maintenance & Self-Healing</h2>
      <p className="text-gray-400 mb-6 text-center">Describe a system anomaly to receive AI-generated maintenance advice and auto-healing protocols.</p>
      
      <div className="flex flex-col sm:flex-row gap-2 mb-4">
        <input
          type="text"
          value={anomaly}
          onChange={(e) => setAnomaly(e.target.value)}
          placeholder="e.g., Unexplained latency spikes in the Pleiades data cluster..."
          className="flex-grow bg-gray-700 border border-gray-600 rounded-md p-3 focus:outline-none focus:ring-2 focus:ring-cyan-500 text-white"
          disabled={isLoading}
          onKeyPress={(e) => e.key === 'Enter' && !isLoading && handleQuery()}
        />
        <button
          onClick={handleQuery}
          disabled={isLoading}
          className="bg-cyan-600 hover:bg-cyan-500 text-white font-bold py-3 px-6 rounded-md disabled:bg-gray-500 transition-colors"
        >
          {isLoading ? 'Diagnosing...' : 'Generate Protocol'}
        </button>
      </div>
      
      <div className="flex-grow overflow-y-auto p-4 bg-gray-800/50 rounded-lg border border-cyan-500/10 min-h-[50vh] mt-4">
        {isLoading && <Spinner text="Running diagnostics..." />}
        {error && <p className="text-red-400 text-center">{error}</p>}
        {protocol && <MarkdownRenderer content={protocol} />}
        {!isLoading && !protocol && !error && <p className="text-gray-500 text-center">Awaiting anomaly report.</p>}
      </div>
    </div>
  );
};

export default SystemMaintenanceModule;