'use client';

import { useState } from 'react';
import { useTranslation } from '@/lib/i18n';

interface Anomaly {
  anomaly_type: string;
  labels: Record<string, string>;
  detail: {
    observed_value: number;
    z_score: number | null;
    peer_median: number;
    peer_mad: number;
    peer_count: number;
  };
}

interface Profile {
  profile_name: string;
  anomalies: Anomaly[];
}

interface MetricItem {
  metrics_name: string;
  profiles: Profile[];
}

interface MetricCategory {
  name: string;
  metrics: MetricItem[];
}

interface DiagnosticData {
  metadata: {
    analysis_uuid: string;
    cluster_id: string;
    cluster_topology: string;
    created_at: string;
    time_range_start_ts: number;
    time_range_end_ts: number;
  };
  metrics: MetricCategory[];
}

interface CriticalAnomaly {
  metric_name: string;
  metric_stage: string;
  panel_id: number;
  screenshot_path: string;
  severity_level: string;
  severity_score: number;
  anomaly_type: string;
  anomaly_time_range: string;
  peak_value: string;
  baseline_value: string;
  deviation_percentage: number | null;
  visual_description: string;
  key_observations: string[];
}

interface AnomaliesPanelProps {
  data: DiagnosticData;
  resourceWorkerData?: any;
}

export default function AnomaliesPanel({ data, resourceWorkerData }: AnomaliesPanelProps) {
  const { t } = useTranslation();
  const [expandedCategories, setExpandedCategories] = useState<Record<string, boolean>>({
    resources: true,
    workload: false,
    latency: false,
  });

  const [expandedMetrics, setExpandedMetrics] = useState<Record<string, boolean>>({});

  // Collect all anomalies
  const anomaliesByCategory: Record<string, { metricName: string; profileName: string; anomalies: Anomaly[] }[]> = {};
  
  data.metrics.forEach(category => {
    const categoryAnomalies: { metricName: string; profileName: string; anomalies: Anomaly[] }[] = [];
    category.metrics.forEach(metric => {
      metric.profiles.forEach(profile => {
        if (profile.anomalies && profile.anomalies.length > 0) {
          categoryAnomalies.push({
            metricName: metric.metrics_name,
            profileName: profile.profile_name,
            anomalies: profile.anomalies,
          });
        }
      });
    });
    if (categoryAnomalies.length > 0) {
      anomaliesByCategory[category.name] = categoryAnomalies;
    }
  });

  const totalAnomalies = Object.values(anomaliesByCategory).reduce(
    (sum, items) => sum + items.reduce((s, item) => s + item.anomalies.length, 0),
    0
  );

  const toggleCategory = (categoryName: string) => {
    setExpandedCategories(prev => ({
      ...prev,
      [categoryName]: !prev[categoryName],
    }));
  };

  const toggleMetric = (key: string) => {
    setExpandedMetrics(prev => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const formatValue = (value: number): string => {
    if (value === null || value === undefined) return 'N/A';
    if (Math.abs(value) < 0.01) return value.toExponential(2);
    if (Math.abs(value) > 1000000) return value.toExponential(2);
    return value.toFixed(4);
  };

  const getSeverityColor = (zScore: number | null): string => {
    if (zScore === null) return '#ff9800'; // orange
    const absZ = Math.abs(zScore);
    if (absZ > 100) return '#f44336'; // red - critical
    if (absZ > 10) return '#ff9800'; // orange - warning
    if (absZ > 3) return '#ffc107'; // yellow - moderate
    return '#4caf50'; // green - low
  };

  const getSeverityLabel = (zScore: number | null): string => {
    if (zScore === null) return t('anomalies.severityUnknown');
    const absZ = Math.abs(zScore);
    if (absZ > 100) return t('anomalies.severityCritical');
    if (absZ > 10) return t('anomalies.severityHigh');
    if (absZ > 3) return t('anomalies.severityModerate');
    return t('anomalies.severityLow');
  };

  const getSeverityColorByLevel = (level: string): string => {
    switch (level.toLowerCase()) {
      case 'critical':
        return '#f44336'; // red
      case 'warning':
        return '#ff9800'; // orange
      case 'info':
        return '#2196f3'; // blue
      default:
        return '#9e9e9e'; // gray
    }
  };

  // Get critical anomalies with screenshots from resource_worker_insight.json
  const criticalAnomalies: CriticalAnomaly[] = 
    ((resourceWorkerData as any)?.phase2_summary?.critical_anomalies || []) as CriticalAnomaly[];

  // Debug logging
  console.log('Resource Worker Data:', resourceWorkerData);
  console.log('Critical Anomalies Count:', criticalAnomalies.length);
  console.log('Critical Anomalies:', criticalAnomalies);

  return (
    <div style={{
      padding: '20px',
      backgroundColor: '#f5f5f5',
      borderBottom: '1px solid #e0e0e0',
    }}>
      {/* Header */}
      <div style={{ marginBottom: '20px' }}>
        <h2 style={{ 
          margin: '0 0 10px 0', 
          fontSize: '20px', 
          fontWeight: '600',
          color: '#333',
        }}>
          🔍 {t('anomalies.title')}
        </h2>
        <div style={{
          fontSize: '14px',
          color: '#666',
          display: 'flex',
          gap: '20px',
          flexWrap: 'wrap',
        }}>
          <span><strong>{t('anomalies.clusterId')}:</strong> {data.metadata.cluster_id}</span>
          <span><strong>{t('anomalies.analysisTime')}:</strong> {new Date(data.metadata.created_at).toLocaleString('en-US')}</span>
          <span style={{
            backgroundColor: totalAnomalies > 0 ? '#ff5252' : '#4caf50',
            color: 'white',
            padding: '2px 8px',
            borderRadius: '12px',
            fontWeight: '600',
          }}>
            {t('anomalies.totalAnomalies')}: {totalAnomalies}
          </span>
        </div>
      </div>

      {/* Critical Anomalies with Screenshots */}
      {criticalAnomalies.length > 0 && (
        <div style={{
          marginBottom: '20px',
          backgroundColor: 'white',
          borderRadius: '8px',
          overflow: 'hidden',
          boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
        }}>
          <div style={{
            padding: '12px 16px',
            backgroundColor: '#fafafa',
            borderBottom: '1px solid #e0e0e0',
            fontSize: '16px',
            fontWeight: '600',
          }}>
            📸 {t('anomalies.criticalWithScreenshots')} ({criticalAnomalies.length})
          </div>
          <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {criticalAnomalies.map((anomaly, idx) => (
              <div
                key={idx}
                style={{
                  border: '1px solid #e0e0e0',
                  borderRadius: '8px',
                  overflow: 'hidden',
                  boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
                }}
              >
                {/* Anomaly Header */}
                <div style={{
                  padding: '12px',
                  backgroundColor: '#f9f9f9',
                  borderBottom: '1px solid #e0e0e0',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  flexWrap: 'wrap',
                  gap: '8px',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span style={{
                      backgroundColor: getSeverityColorByLevel(anomaly.severity_level),
                      color: 'white',
                      padding: '3px 10px',
                      borderRadius: '12px',
                      fontSize: '11px',
                      fontWeight: '600',
                      textTransform: 'uppercase',
                    }}>
                      {anomaly.severity_level}
                    </span>
                    <span style={{ fontSize: '15px', fontWeight: '600', color: '#333' }}>
                      {anomaly.metric_name}
                    </span>
                    <span style={{ fontSize: '12px', color: '#666' }}>
                      ({anomaly.metric_stage})
                    </span>
                  </div>
                  <span style={{
                    backgroundColor: '#e3f2fd',
                    color: '#1976d2',
                    padding: '2px 8px',
                    borderRadius: '10px',
                    fontSize: '11px',
                    fontWeight: '600',
                  }}>
                    {t('anomalies.score')}: {anomaly.severity_score}
                  </span>
                </div>

                {/* Anomaly Details */}
                <div style={{ padding: '12px' }}>
                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
                    gap: '8px',
                    marginBottom: '12px',
                    fontSize: '13px',
                    color: '#555',
                  }}>
                    <div><strong>{t('anomalies.type')}:</strong> {anomaly.anomaly_type}</div>
                    <div><strong>{t('anomalies.timeRange')}:</strong> {anomaly.anomaly_time_range}</div>
                    <div><strong>{t('anomalies.peakValue')}:</strong> {anomaly.peak_value}</div>
                    <div><strong>{t('anomalies.baseline')}:</strong> {anomaly.baseline_value}</div>
                  </div>

                  <div style={{
                    padding: '10px',
                    backgroundColor: '#fffbf0',
                    borderLeft: '4px solid #ff9800',
                    borderRadius: '4px',
                    fontSize: '13px',
                    color: '#555',
                    marginBottom: '12px',
                  }}>
                    <strong>{t('anomalies.visualDescription')}:</strong> {anomaly.visual_description}
                  </div>

                  {anomaly.key_observations.length > 0 && (
                    <div style={{
                      padding: '10px',
                      backgroundColor: '#f1f8ff',
                      borderLeft: '4px solid #2196f3',
                      borderRadius: '4px',
                      fontSize: '12px',
                      color: '#555',
                      marginBottom: '12px',
                    }}>
                      <strong>{t('anomalies.keyObservations')}:</strong>
                      <ul style={{ margin: '6px 0 0 0', paddingLeft: '20px' }}>
                        {anomaly.key_observations.slice(0, 5).map((obs, obsIdx) => (
                          <li key={obsIdx} style={{ marginBottom: '4px' }}>{obs}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Screenshot */}
                  {anomaly.screenshot_path && (
                    <div style={{
                      border: '2px solid #e0e0e0',
                      borderRadius: '6px',
                      overflow: 'hidden',
                      cursor: 'pointer',
                      transition: 'transform 0.2s',
                    }}
                    onMouseOver={(e) => (e.currentTarget.style.transform = 'scale(1.01)')}
                    onMouseOut={(e) => (e.currentTarget.style.transform = 'scale(1)')}
                    onClick={() => window.open(`/${anomaly.screenshot_path.replace(/^data\//, '')}`, '_blank')}
                    >
                      <img
                        src={`/${anomaly.screenshot_path.replace(/^data\//, '')}`}
                        alt={`${anomaly.metric_name} - ${anomaly.anomaly_type} anomaly`}
                        style={{
                          width: '100%',
                          display: 'block',
                        }}
                      />
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Anomalies by Category */}
      {Object.keys(anomaliesByCategory).length === 0 ? (
        <div style={{
          padding: '20px',
          backgroundColor: '#e8f5e9',
          borderRadius: '8px',
          textAlign: 'center',
          color: '#2e7d32',
        }}>
          {t('anomalies.noneDetected')}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
          {Object.entries(anomaliesByCategory).map(([categoryName, items]) => {
            const categoryTotal = items.reduce((s, item) => s + item.anomalies.length, 0);
            const isExpanded = expandedCategories[categoryName];

            return (
              <div key={categoryName} style={{
                backgroundColor: 'white',
                borderRadius: '8px',
                boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                overflow: 'hidden',
              }}>
                {/* Category Header */}
                <div
                  onClick={() => toggleCategory(categoryName)}
                  style={{
                    padding: '12px 16px',
                    backgroundColor: '#fafafa',
                    borderBottom: '1px solid #e0e0e0',
                    cursor: 'pointer',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    userSelect: 'none',
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span style={{ fontSize: '16px', fontWeight: '600', textTransform: 'capitalize' }}>
                      {isExpanded ? '▼' : '▶'} {categoryName}
                    </span>
                    <span style={{
                      backgroundColor: '#ff5252',
                      color: 'white',
                      padding: '2px 8px',
                      borderRadius: '12px',
                      fontSize: '12px',
                      fontWeight: '600',
                    }}>
                      {categoryTotal}
                    </span>
                  </div>
                </div>

                {/* Category Content */}
                {isExpanded && (
                  <div style={{ padding: '12px' }}>
                    {items.map((item, idx) => {
                      const metricKey = `${categoryName}-${item.metricName}-${item.profileName}`;
                      const isMetricExpanded = expandedMetrics[metricKey];

                      return (
                        <div key={metricKey} style={{
                          marginBottom: idx < items.length - 1 ? '12px' : '0',
                          border: '1px solid #e0e0e0',
                          borderRadius: '6px',
                          overflow: 'hidden',
                        }}>
                          {/* Metric Header */}
                          <div
                            onClick={() => toggleMetric(metricKey)}
                            style={{
                              padding: '10px 12px',
                              backgroundColor: '#f9f9f9',
                              cursor: 'pointer',
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              userSelect: 'none',
                            }}
                          >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                              <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                {isMetricExpanded ? '▼' : '▶'} {item.metricName}
                              </span>
                              <span style={{ fontSize: '12px', color: '#666' }}>
                                ({item.profileName})
                              </span>
                              <span style={{
                                backgroundColor: '#2196f3',
                                color: 'white',
                                padding: '1px 6px',
                                borderRadius: '10px',
                                fontSize: '11px',
                                fontWeight: '600',
                              }}>
                                {item.anomalies.length}
                              </span>
                            </div>
                          </div>

                          {/* Anomalies List */}
                          {isMetricExpanded && (
                            <div style={{ padding: '8px 12px' }}>
                              {item.anomalies.map((anomaly, anomalyIdx) => {
                                const severity = getSeverityColor(anomaly.detail.z_score);
                                const severityLabel = getSeverityLabel(anomaly.detail.z_score);

                                return (
                                  <div
                                    key={anomalyIdx}
                                    style={{
                                      padding: '10px',
                                      backgroundColor: '#fafafa',
                                      borderLeft: `4px solid ${severity}`,
                                      borderRadius: '4px',
                                      marginBottom: anomalyIdx < item.anomalies.length - 1 ? '8px' : '0',
                                      fontSize: '13px',
                                    }}
                                  >
                                    <div style={{ 
                                      display: 'flex', 
                                      justifyContent: 'space-between',
                                      marginBottom: '8px',
                                    }}>
                                      <span style={{ fontWeight: '600', color: '#333' }}>
                                        {anomaly.anomaly_type}
                                      </span>
                                      <span style={{
                                        backgroundColor: severity,
                                        color: 'white',
                                        padding: '2px 8px',
                                        borderRadius: '10px',
                                        fontSize: '11px',
                                        fontWeight: '600',
                                      }}>
                                        {severityLabel}
                                      </span>
                                    </div>

                                    {/* Labels */}
                                    <div style={{ marginBottom: '8px' }}>
                                      {Object.entries(anomaly.labels).map(([key, value]) => (
                                        <span
                                          key={key}
                                          style={{
                                            display: 'inline-block',
                                            backgroundColor: '#e3f2fd',
                                            color: '#1976d2',
                                            padding: '2px 6px',
                                            borderRadius: '4px',
                                            fontSize: '11px',
                                            marginRight: '6px',
                                            marginBottom: '4px',
                                          }}
                                        >
                                          {key}: {value}
                                        </span>
                                      ))}
                                    </div>

                                    {/* Details */}
                                    <div style={{
                                      display: 'grid',
                                      gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))',
                                      gap: '8px',
                                      fontSize: '12px',
                                      color: '#555',
                                    }}>
                                      <div>
                                        <strong>{t('anomalies.observedValue')}:</strong> {formatValue(anomaly.detail.observed_value)}
                                      </div>
                                      {anomaly.detail.z_score !== null && (
                                        <div>
                                          <strong>{t('anomalies.zScore')}:</strong> {formatValue(anomaly.detail.z_score)}
                                        </div>
                                      )}
                                      <div>
                                        <strong>{t('anomalies.peerMedian')}:</strong> {formatValue(anomaly.detail.peer_median)}
                                      </div>
                                      <div>
                                        <strong>{t('anomalies.mad')}:</strong> {formatValue(anomaly.detail.peer_mad)}
                                      </div>
                                      <div>
                                        <strong>{t('anomalies.peerCount')}:</strong> {anomaly.detail.peer_count}
                                      </div>
                                    </div>
                                  </div>
                                );
                              })}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Cluster Topology */}
      <div style={{
        marginTop: '16px',
        padding: '12px',
        backgroundColor: 'white',
        borderRadius: '8px',
        fontSize: '13px',
        color: '#666',
      }}>
        <strong>{t('anomalies.clusterTopology')}:</strong> {data.metadata.cluster_topology}
      </div>
    </div>
  );
}
