'use client'

import { useQuery } from '@apollo/client'
import MetricsCard from './MetricsCard'
import { MetricsChart } from './MetricsChart'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { GET_REGIONS } from '@/lib/graphql/queries/resources'
import { GET_RESOURCES } from '@/lib/graphql/queries'
import { GET_METRICS } from '@/lib/graphql/queries/metrics'
import { useMemo, useEffect, useState } from 'react'
import { useResourceUpdate, useMetricsUpdate, useHealthChange } from '@/lib/graphql/hooks/useSubscriptions'

export default function Dashboard() {
  // Fetch regions
  const { data: regionsData, loading: regionsLoading } = useQuery(GET_REGIONS, {
    fetchPolicy: 'cache-and-network',
  })

  // Fetch all resources
  const { data: resourcesData, loading: resourcesLoading } = useQuery(GET_RESOURCES, {
    fetchPolicy: 'cache-and-network',
  })

  // Calculate metrics from data
  const regions = regionsData?.regions || []
  const resources = resourcesData?.resources || []
  
  // Calculate active services (running resources)
  const activeServices = resources.filter((r: any) => r.status === 'RUNNING').length
  const totalResources = resources.length

  // Calculate network health (simplified - would use actual health metrics)
  const healthyResources = resources.filter((r: any) => r.health === 'HEALTHY' || !r.health).length
  const networkHealth = totalResources > 0 ? Math.round((healthyResources / totalResources) * 100) : 0

  // Get a sample resource for metrics (first running resource)
  const sampleResource = resources.find((r: any) => r.status === 'RUNNING')
  const timeRange = useMemo(() => {
    const end = new Date()
    const start = new Date(end.getTime() - 60 * 60 * 1000) // Last hour
    return { start, end }
  }, [])

  // Fetch metrics for sample resource
  const { data: metricsData, loading: metricsLoading } = useQuery(GET_METRICS, {
    variables: {
      resourceId: sampleResource?.id || '',
      metricType: 'CPU_USAGE',
      timeRange: {
        start: timeRange.start.toISOString(),
        end: timeRange.end.toISOString(),
      },
    },
    skip: !sampleResource?.id,
    fetchPolicy: 'cache-and-network',
  })

  // Fetch cost metrics
  const { data: costMetricsData } = useQuery(GET_METRICS, {
    variables: {
      resourceId: sampleResource?.id || '',
      metricType: 'COST',
      timeRange: {
        start: timeRange.start.toISOString(),
        end: timeRange.end.toISOString(),
      },
    },
    skip: !sampleResource?.id,
    fetchPolicy: 'cache-and-network',
  })

  // Real-time subscriptions for live updates
  const { resource: updatedResource } = useResourceUpdate(sampleResource?.id || '')
  const { metric: updatedMetric } = useMetricsUpdate(sampleResource?.id || '', 'CPU_USAGE')
  const { health: updatedHealth } = useHealthChange(sampleResource?.id || '')

  // Update local state when subscription data arrives
  useEffect(() => {
    if (updatedResource) {
      // Trigger refetch or update local cache
      // Apollo Client will handle this automatically with cache updates
    }
  }, [updatedResource])

  useEffect(() => {
    if (updatedMetric) {
      // Add new metric point to the chart data
      // This would typically update the Apollo cache or local state
    }
  }, [updatedMetric])

  useEffect(() => {
    if (updatedHealth) {
      // Update health status in real-time
    }
  }, [updatedHealth])

  // Transform metrics data for charts
  const cpuMetricsData = useMemo(() => {
    if (!metricsData?.metrics?.values) return []
    return metricsData.metrics.values.map((v: any) => ({
      timestamp: v.timestamp,
      value: v.value,
    }))
  }, [metricsData])

  const costMetricsData = useMemo(() => {
    if (!costMetricsData?.metrics?.values) return []
    return costMetricsData.metrics.values.map((v: any) => ({
      timestamp: v.timestamp,
      value: v.value,
    }))
  }, [costMetricsData])

  // Calculate cost efficiency (simplified)
  const costEfficiency = useMemo(() => {
    if (!costMetricsData?.metrics?.values || costMetricsData.metrics.values.length === 0) return 87
    const values = costMetricsData.metrics.values.map((v: any) => v.value)
    const avgCost = values.reduce((a: number, b: number) => a + b, 0) / values.length
    // Simplified calculation - in production would compare against baseline
    return Math.max(70, Math.min(100, 100 - (avgCost / 1000) * 10))
  }, [costMetricsData])

  if (regionsLoading || resourcesLoading) {
    return (
      <div className="space-y-6 p-6">
        <h1 className="text-3xl font-bold text-white">Dashboard</h1>
        <div className="text-white">Loading...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6 p-6">
      <h1 className="text-3xl font-bold text-white">Dashboard</h1>
      
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        <MetricsCard
          title="Total Regions"
          value={regions.length.toString()}
          health={regions.length > 0 ? 95 : 0}
          trend="up"
          description="Active global regions"
        />
        <MetricsCard
          title="Active Services"
          value={activeServices.toLocaleString()}
          health={totalResources > 0 ? Math.round((activeServices / totalResources) * 100) : 0}
          trend={activeServices > 0 ? "up" : "stable"}
          description="Running services"
        />
        <MetricsCard
          title="Network Health"
          value={`${networkHealth}%`}
          health={networkHealth}
          trend={networkHealth >= 90 ? "up" : networkHealth >= 70 ? "stable" : "down"}
          description="Overall network status"
        />
        <MetricsCard
          title="Cost Efficiency"
          value={`${costEfficiency}%`}
          health={costEfficiency}
          trend="up"
          description="Cost optimization score"
        />
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <Card className="border-studio-medium bg-studio-dark">
          <CardHeader>
            <CardTitle className="text-white">Performance Metrics</CardTitle>
          </CardHeader>
          <CardContent>
            {metricsLoading ? (
              <div className="text-white">Loading metrics...</div>
            ) : cpuMetricsData.length > 0 ? (
              <MetricsChart
                data={cpuMetricsData}
                title="CPU Usage"
                metricType="CPU_USAGE"
              />
            ) : (
              <div className="text-white">No metrics available</div>
            )}
          </CardContent>
        </Card>
        
        <Card className="border-studio-medium bg-studio-dark">
          <CardHeader>
            <CardTitle className="text-white">Cost Analysis</CardTitle>
          </CardHeader>
          <CardContent>
            {costMetricsData.length > 0 ? (
              <MetricsChart
                data={costMetricsData}
                title="Cost Over Time"
                metricType="COST"
              />
            ) : (
              <div className="text-white">No cost data available</div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

