'use client'

import { useQuery } from '@tanstack/react-query'
import { Server, Play, Pause, Trash2 } from 'lucide-react'

import { Button } from '@/components/ui/Button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'

interface VM {
  id: string
  name: string
  status: string
  cpu: number
  memory: number
  disk: number
}

function specToNumber(v: string | number | undefined): number {
  if (v == null) return 0
  if (typeof v === 'number') return v
  const m = /^(\d+(?:\.\d+)?)/.exec(String(v).trim())
  return m ? parseFloat(m[1]) : 0
}

export function VMList() {
  const { data: vms, isLoading } = useQuery<VM[]>({
    queryKey: ['vms'],
    queryFn: async () => {
      const { createCrossplaneClient } = await import('@/lib/crossplane-client')
      const client = createCrossplaneClient()
      const vms = await client.getVMs()

      return vms.map((vm) => ({
        id: vm.metadata?.name || 'unknown',
        name: vm.metadata?.name || 'Unknown',
        status: vm.status?.state || 'unknown',
        cpu: vm.spec?.forProvider?.cpu || 0,
        memory: specToNumber(vm.spec?.forProvider?.memory),
        disk: specToNumber(vm.spec?.forProvider?.disk),
      }))
    },
  })

  if (isLoading) return <div>Loading VMs...</div>

  return (
    <div className="space-y-4">
      {vms?.map((vm) => (
        <Card key={vm.id}>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Server className="h-5 w-5" />
                <div>
                  <CardTitle>{vm.name}</CardTitle>
                  <p className="text-sm text-gray-500">Status: {vm.status}</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm">
                  <Play className="h-4 w-4" />
                </Button>
                <Button variant="outline" size="sm">
                  <Pause className="h-4 w-4" />
                </Button>
                <Button variant="outline" size="sm">
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-gray-500">CPU:</span> {vm.cpu} cores
              </div>
              <div>
                <span className="text-gray-500">Memory:</span> {vm.memory} GB
              </div>
              <div>
                <span className="text-gray-500">Disk:</span> {vm.disk} GB
              </div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

