'use client'

import { useQuery } from '@tanstack/react-query'
import { gql } from 'graphql-tag'
import { apolloClient } from '@/lib/graphql/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { MetricsChart } from '@/components/dashboards/MetricsChart'
import { Server, MapPin, Clock } from 'lucide-react'

const GET_RESOURCE = gql`
  query GetResource($id: ID!) {
    resource(id: $id) {
      id
      name
      type
      status
      site {
        id
        name
        region
      }
      metadata
      createdAt
      updatedAt
    }
  }
`

const GET_METRICS = gql`
  query GetMetrics($resourceId: ID!, $metricType: MetricType!, $timeRange: TimeRange!) {
    metrics(resourceId: $resourceId, metricType: $metricType, timeRange: $timeRange) {
      resource {
        id
        name
      }
      metricType
      values {
        timestamp
        value
      }
      timeRange {
        start
        end
      }
    }
  }
`

export function ResourceDetailView({ resourceId }: { resourceId: string }) {
  const { data: resource, isLoading: resourceLoading } = useQuery({
    queryKey: ['resource', resourceId],
    queryFn: async () => {
      const result = await apolloClient.query({
        query: GET_RESOURCE,
        variables: { id: resourceId },
      })
      return result.data.resource
    },
  })

  const timeRange = {
    start: new Date(Date.now() - 3600000).toISOString(),
    end: new Date().toISOString(),
  }

  const { data: cpuMetrics } = useQuery({
    queryKey: ['metrics', resourceId, 'CPU_USAGE', timeRange],
    queryFn: async () => {
      const result = await apolloClient.query({
        query: GET_METRICS,
        variables: {
          resourceId,
          metricType: 'CPU_USAGE',
          timeRange,
        },
      })
      return result.data.metrics
    },
    enabled: !!resourceId,
  })

  if (resourceLoading) return <div>Loading resource...</div>
  if (!resource) return <div>Resource not found</div>

  return (
    <div className="space-y-6">
      <Card className="border-studio-medium bg-studio-dark">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Server className="h-6 w-6 text-phoenix-fire" />
              <div>
                <CardTitle className="text-2xl text-white">{resource.name}</CardTitle>
                <div className="flex items-center gap-2 mt-2">
                  <Badge>{resource.type}</Badge>
                  <Badge
                    variant={
                      resource.status === 'RUNNING'
                        ? 'default'
                        : resource.status === 'ERROR'
                        ? 'destructive'
                        : 'secondary'
                    }
                  >
                    {resource.status}
                  </Badge>
                </div>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-3 gap-4">
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4 text-gray-400" />
              <span className="text-sm text-gray-400">Site:</span>
              <span className="text-sm text-white">{resource.site?.name}</span>
            </div>
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4 text-gray-400" />
              <span className="text-sm text-gray-400">Region:</span>
              <span className="text-sm text-white">{resource.site?.region}</span>
            </div>
            <div className="flex items-center gap-2">
              <Clock className="h-4 w-4 text-gray-400" />
              <span className="text-sm text-gray-400">Created:</span>
              <span className="text-sm text-white">
                {new Date(resource.createdAt).toLocaleDateString()}
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {cpuMetrics && (
        <Card className="border-studio-medium bg-studio-dark">
          <CardHeader>
            <CardTitle className="text-white">CPU Usage</CardTitle>
          </CardHeader>
          <CardContent>
            <MetricsChart
              data={cpuMetrics.values.map((v: any) => ({
                timestamp: v.timestamp,
                value: v.value,
              }))}
              metricType="CPU_USAGE"
            />
          </CardContent>
        </Card>
      )}
    </div>
  )
}

