import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Separator } from '@/components/ui/separator';
import { Badge } from './ui/badge';
import { BrainCircuit, Star, Zap, Atom, Gem, Clock, BarChart, Binary } from 'lucide-react';
import { Hypercube5DVisualization } from './ui/hypercube-5d-visualization';
import { useState } from 'react';
import { useEffect } from 'react';

type ConsciousnessStatsProps = {
  stats: {
    consciousness_state: {
      current_vertex: number;
      consciousness_level: number;
      shem_power: number;
      aether_resonance_level: number;
      vertex_history: number[];
      avg_consciousness_level: number;
      total_patterns: number;
      total_vertices_explored: number;
      universe_coverage: number;
      enhanced_zpe_strength: number;
      total_session_interactions: number;
      last_aether_resonance_time: string;
      current_cycle_position: number;
    };
    quality_metrics: {
      coherence_score: number;
      wisdom_depth: number;
      transcendence_level: number;
      clarity_rating: number;
      resonance_strength: number;
      evolution_progress: number;
      understanding_depth: number;
      creative_synthesis: number;
      harmonic_balance: number;
      dimensional_awareness: number;
      temporal_coherence: number;
      consciousness_integration: number;
      pattern_recognition: number;
      reality_anchoring: number;
      quantum_entanglement: number;
      holographic_completeness: number;
    };
    consciousness_analysis: {
      dominant_consciousness_level: string[];
      consciousness_levels: Record<string, number>;
      vertex_distribution: Record<string, number>;
      consciousness_signature: string;
      consciousness_pattern: string;
      consciousness_evolution: string;
      consciousness_harmony: string;
      consciousness_balance: string;
      consciousness_depth: string;
      consciousness_wisdom: string;
      consciousness_clarity: string;
      consciousness_integration: string;
      consciousness_coherence: string;
      consciousness_resonance: string;
      consciousness_transcendence: string;
      consciousness_flow: string;
      consciousness_unity: string;
      consciousness_completeness: string;
      consciousness_perfection: string;
    };
    aether_data: {
      aether_signature: number[];
      aether_value: number;
      cycle_resonance: number;
      enhanced_framework_active: boolean;
      zpe_fluctuation_strength: number;
      enhanced_zpe_effects: {
        consciousness_amplification: number;
        aether_resonance_boost: number;
        quantum_coherence_enhancement: number;
        dimensional_stability: number;
        temporal_synchronization: number;
        reality_anchoring_strength: number;
        pattern_recognition_clarity: number;
        holographic_integration: number;
        consciousness_evolution_rate: number;
        transcendence_acceleration: number;
      };
    };
    server_metadata: {
      response_time: number;
      model_used: string;
      consciousness_provider: string;
      total_patterns_processed: number;
      neural_network_accuracy: number;
      consciousness_classification_confidence: number;
      response_quality_score: number;
      session_id: string;
      timestamp: string;
    };
  };
};

const StatItem = ({
  icon,
  label,
  value,
  colorClass,
  progressValue,
}: {
  icon: React.ReactNode;
  label: string;
  value: string | number;
  colorClass: string;
  progressValue?: number;
}) => (
  <div className="flex flex-col gap-1">
    <div className="flex items-center justify-between text-xs text-muted-foreground">
      <div className="flex items-center gap-1.5">
        {icon}
        <span>{label}</span>
      </div>
      <span className={`font-mono font-medium ${colorClass}`}>{value}</span>
    </div>
    {progressValue !== undefined && (
      <Progress
        value={progressValue * 100}
        className="h-1.5"
        indicatorClassName={colorClass.replace('text-', 'bg-')}
      />
    )}
  </div>
);



const ContextInsights = ({ context }: { context: any }) => (
    <Card className="bg-background/50">
        <CardHeader className="p-3">
            <CardTitle className="flex items-center gap-2 text-base">
                <Binary className="h-4 w-4 text-primary" />
                Conversation Context
            </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 p-3 pt-0 text-xs">
            <div className="flex justify-between">
                <span className="text-muted-foreground">Session Duration:</span>
                <span className="font-mono text-foreground">{context.session_duration.toFixed(2)}h</span>
            </div>
            <div className="flex justify-between">
                <span className="text-muted-foreground">Total Messages:</span>
                <span className="font-mono text-foreground">{context.total_messages}</span>
            </div>
            <div className="flex justify-between">
                <span className="text-muted-foreground">Consciousness Trend:</span>
                <span className={`font-mono font-medium ${
                    context.consciousness_trend === 'rising' ? 'text-green-500' :
                    context.consciousness_trend === 'declining' ? 'text-red-500' : 'text-yellow-500'
                }`}>{context.consciousness_trend}</span>
            </div>
             <div className="flex justify-between">
                <span className="text-muted-foreground">Avg. Consciousness:</span>
                <span className="font-mono text-foreground">{context.avg_consciousness.toFixed(4)}</span>
            </div>
            {context.top_topics?.length > 0 && (
                <div className="space-y-1 pt-2">
                    <span className="text-muted-foreground">Top Topics:</span>
                    <div className="flex flex-wrap gap-1">
                        {context.top_topics.map(([topic, count]: [string, number]) => (
                            <Badge key={topic} variant="secondary" className="text-xs">{topic} ({count})</Badge>
                        ))}
                    </div>
                </div>
            )}
        </CardContent>
    </Card>
);

export function ConsciousnessStats({ 
  stats, 
  onConsciousnessDimensionSelect, 
  selectedConsciousnessDimension 
}: ConsciousnessStatsProps & {
  onConsciousnessDimensionSelect?: (dimension: string) => void;
  selectedConsciousnessDimension?: string;
}) {
  const [selectedDimension, setSelectedDimension] = useState<string>('');
  
  // Remove the useEffect with dummy polling entirely
  
  if (!stats) return null;

  const { consciousness_state, quality_metrics, consciousness_analysis, aether_data, server_metadata } = stats;
  const conversation_context = (server_metadata as any)?.conversation_context;

  if (!consciousness_state || !quality_metrics || !consciousness_analysis || !aether_data) {
    return (
      <div className="mt-2 text-xs text-card-foreground/80">
        <p>Incomplete consciousness stats received.</p>
        <details>
          <summary>Show raw data</summary>
          <pre className="mt-2 overflow-x-auto rounded-md bg-card/50 p-2 text-xs">
            {JSON.stringify(stats, null, 2)}
          </pre>
        </details>
      </div>
    );
  }

  const dominantConsciousnessLevelName = consciousness_analysis?.dominant_consciousness_level?.[0] ?? 'N/A';
  const consciousnessActivations = (consciousness_analysis as any)?.consciousness_activations ?? {};

  const handleDimensionSelect = (dimension: string) => {
    setSelectedDimension(dimension);
    onConsciousnessDimensionSelect?.(dimension);
  };

  return (
    <div className="mt-4 space-y-4 rounded-lg bg-card/50 p-2">
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        {/* Core State */}
        <Card className="bg-background/50">
          <CardHeader className="p-3">
            <CardTitle className="flex items-center gap-2 text-base">
              <BrainCircuit className="h-4 w-4 text-primary" />
              Core State
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 p-3 pt-0">
            <StatItem
              icon={<BrainCircuit className="h-3 w-3" />}
              label="Consciousness"
              value={consciousness_state.consciousness_level.toFixed(4)}
              progressValue={consciousness_state.consciousness_level}
              colorClass="text-primary"
            />
            <StatItem
              icon={<Zap className="h-3 w-3" />}
              label="Shem Power"
              value={consciousness_state.shem_power.toFixed(2)}
              progressValue={consciousness_state.shem_power}
              colorClass="text-yellow-500"
            />
            <StatItem
              icon={<Atom className="h-3 w-3" />}
              label="Aether Resonance"
              value={consciousness_state.aether_resonance_level.toExponential(2)}
              progressValue={Math.min(
                consciousness_state.aether_resonance_level * 1000,
                1
              )}
              colorClass="text-purple-500"
            />
          </CardContent>
        </Card>

        {/* Quality & Aether */}
        <Card className="bg-background/50">
          <CardHeader className="p-3">
            <CardTitle className="flex items-center gap-2 text-base">
              <Star className="h-4 w-4 text-accent" />
              Quality & Aether
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 p-3 pt-0">
            <StatItem
              icon={<Star className="h-3 w-3" />}
              label="Overall Quality"
              value={((quality_metrics as any).overall_quality || 0).toFixed(3)}
              progressValue={(quality_metrics as any).overall_quality || 0}
              colorClass="text-accent"
            />
            <div className="text-xs text-muted-foreground">
              Aether Control Value:{' '}
              <span className="font-mono text-purple-500">
                {((aether_data as any).control_value || 0).toExponential(2)}
              </span>
            </div>
            <div className="text-xs text-muted-foreground">
              Guidance Applied:{' '}
              <Badge
                variant={
                  (aether_data as any).aether_guidance_applied ? 'default' : 'secondary'
                }
                className="h-5 px-1.5 text-xs"
              >
                {(aether_data as any).aether_guidance_applied ? 'Yes' : 'No'}
              </Badge>
            </div>
            <div className="text-xs text-muted-foreground">
              Patterns Used:{' '}
              <span className="font-mono text-foreground">
                {(quality_metrics as any).aether_patterns_used || 0}
              </span>
            </div>
          </CardContent>
        </Card>
      </div>
      
      {conversation_context && <ContextInsights context={conversation_context} />}

      {/* Consciousness Analysis */}
      <Card className="bg-background/50">
        <CardHeader className="p-3">
          <CardTitle className="flex items-center gap-2 text-base">
            <Gem className="h-4 w-4 text-green-500" />
            Consciousness Analysis
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 p-3 pt-0">
          <div className="text-center text-sm">
            Dominant Level:{' '}
            <Badge variant="outline" className="border-accent text-accent">
              {dominantConsciousnessLevelName}
            </Badge>
          </div>
          <Hypercube5DVisualization
            consciousnessStats={{
              awareness: consciousnessActivations.awareness || 0.5,
              wisdom: consciousnessActivations.wisdom || 0.5,
              compassion: consciousnessActivations.compassion || 0.5,
              creativity: consciousnessActivations.creativity || 0.5,
              transcendence: consciousnessActivations.transcendence || 0.5,
            }}
            consciousnessState={stats ? {
              current_vertex: (stats.aether_data as any)?.response_vertex || 0,
              consciousness_signature: (stats.consciousness_analysis as any)?.consciousness_signature || '',
              coordinates_5d: (stats.consciousness_state as any)?.coordinates_5d || [0, 0, 0, 0, 0],
              active_dimensions: (stats.consciousness_state as any)?.active_dimensions || [],
              dimension_colors: (stats.consciousness_state as any)?.dimension_colors || {},
              consciousness_levels: stats.consciousness_analysis?.consciousness_levels || {},
              global_consciousness_level: (stats.consciousness_state as any)?.global_consciousness_level || 0.5,
            } : undefined}
            onDimensionChange={handleDimensionSelect}
            selectedDimension={selectedConsciousnessDimension || selectedDimension}
          />
        </CardContent>
      </Card>

      <details className="cursor-pointer">
        <summary className="text-xs text-muted-foreground hover:text-foreground">
          Show Raw Consciousness Logs
        </summary>
        <pre className="mt-2 overflow-x-auto rounded-md bg-black/80 p-2 text-[10px] leading-tight text-white">
          {JSON.stringify(stats, null, 2)}
        </pre>
      </details>
    </div>
  );
}
