'use client';

import { useState, useEffect } from 'react';
import {
  detectJiraAnomalies,
  updateAnomalyDetectionConfig,
  getAnomalyDetectionConfig,
} from '@/actions/jira-anomalies';
import {
  JiraAnomaly,
  AnomalyDetectionConfig,
} from '@/services/integrations/jira/anomaly-detection';
import { Button } from '@/components/ui/Button';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { AnomalySummary } from './anomaly/AnomalySummary';
import { AnomalyList } from './anomaly/AnomalyList';
import { AnomalyConfigModal } from './anomaly/AnomalyConfigModal';
import { formatDateForDisplay, getToday } from '@/lib/date-utils';

interface AnomalyDetectionPanelProps {
  className?: string;
}

export default function AnomalyDetectionPanel({
  className = '',
}: AnomalyDetectionPanelProps) {
  const [anomalies, setAnomalies] = useState<JiraAnomaly[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showConfig, setShowConfig] = useState(false);
  const [config, setConfig] = useState<AnomalyDetectionConfig | null>(null);
  const [lastUpdate, setLastUpdate] = useState<string | null>(null);
  const [isExpanded, setIsExpanded] = useState(false);

  // Charger la config au montage, les anomalies seulement si expanded
  useEffect(() => {
    loadConfig();
  }, []);

  // Charger les anomalies quand on ouvre le panneau
  useEffect(() => {
    if (isExpanded && anomalies.length === 0) {
      loadAnomalies();
    }
  }, [isExpanded, anomalies.length]);

  const loadAnomalies = async (forceRefresh = false) => {
    setLoading(true);
    setError(null);

    try {
      const result = await detectJiraAnomalies(forceRefresh);

      if (result.success && result.data) {
        setAnomalies(result.data);
        setLastUpdate(formatDateForDisplay(getToday(), 'DISPLAY_LONG'));
      } else {
        setError(result.error || 'Erreur lors de la détection');
      }
    } catch {
      setError('Erreur de connexion');
    } finally {
      setLoading(false);
    }
  };

  const loadConfig = async () => {
    try {
      const result = await getAnomalyDetectionConfig();
      if (result.success && result.data) {
        setConfig(result.data);
      }
    } catch (err) {
      console.error('Erreur lors du chargement de la config:', err);
    }
  };

  const handleConfigUpdate = async (newConfig: AnomalyDetectionConfig) => {
    try {
      const result = await updateAnomalyDetectionConfig(newConfig);
      if (result.success && result.data) {
        setConfig(result.data);
        setShowConfig(false);
        // Recharger les anomalies avec la nouvelle config
        loadAnomalies(true);
      }
    } catch (err) {
      console.error('Erreur lors de la mise à jour de la config:', err);
    }
  };

  return (
    <Card className={className}>
      <CardHeader>
        <AnomalySummary
          anomalies={anomalies}
          isExpanded={isExpanded}
          onToggleExpanded={() => setIsExpanded(!isExpanded)}
        />

        {isExpanded && (
          <div className="flex items-center justify-between mt-4">
            <div className="flex gap-2">
              <Button
                onClick={() => setShowConfig(true)}
                variant="secondary"
                size="sm"
                className="text-xs"
              >
                ⚙️ Config
              </Button>
              <Button
                onClick={() => loadAnomalies(true)}
                disabled={loading}
                size="sm"
                className="text-xs"
              >
                {loading ? '🔄' : '🔍'} {loading ? 'Analyse...' : 'Analyser'}
              </Button>
            </div>

            {lastUpdate && (
              <p className="text-xs text-[var(--muted-foreground)]">
                Dernière analyse: {lastUpdate}
              </p>
            )}
          </div>
        )}
      </CardHeader>

      {isExpanded && (
        <CardContent>
          <AnomalyList anomalies={anomalies} loading={loading} error={error} />
        </CardContent>
      )}

      <AnomalyConfigModal
        isOpen={showConfig && !!config}
        onClose={() => setShowConfig(false)}
        config={config}
        onConfigUpdate={handleConfigUpdate}
      />
    </Card>
  );
}
