'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useSession } from 'next-auth/react';
import { createCrossplaneClient } from '@/lib/crossplane-client';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Play, Square, Trash2, Plus } from 'lucide-react';

export default function VMList() {
  const { data: session } = useSession();
  const crossplane = createCrossplaneClient(session?.accessToken as string);
  const queryClient = useQueryClient();

  const { data: vms = [], isLoading } = useQuery({
    queryKey: ['vms'],
    queryFn: () => crossplane.getVMs(),
    refetchInterval: 30000, // Refresh every 30 seconds
  });

  const deleteMutation = useMutation({
    mutationFn: (name: string) => crossplane.deleteVM(name),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vms'] });
    },
  });

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

  return (
    <div>
      <div className="mb-4 flex justify-between items-center">
        <h2 className="text-xl font-semibold">Virtual Machines</h2>
        <button className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded hover:bg-primary-700">
          <Plus className="h-4 w-4" />
          Create VM
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {vms.map((vm: any) => (
          <Card key={vm.metadata.name}>
            <CardHeader>
              <CardTitle className="text-lg">{vm.metadata.name}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Status:</span>
                  <span
                    className={
                      vm.status?.state === 'running'
                        ? 'text-green-600'
                        : 'text-gray-600'
                    }
                  >
                    {vm.status?.state || 'Unknown'}
                  </span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">VM ID:</span>
                  <span>{vm.status?.vmId || 'N/A'}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">IP Address:</span>
                  <span>{vm.status?.ipAddress || 'N/A'}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">CPU:</span>
                  <span>{vm.spec.forProvider.cpu} cores</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Memory:</span>
                  <span>{vm.spec.forProvider.memory}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Site:</span>
                  <span>{vm.spec.forProvider.site}</span>
                </div>
                <div className="flex gap-2 mt-4">
                  <button
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700 text-sm"
                    title="Start VM"
                  >
                    <Play className="h-4 w-4" />
                  </button>
                  <button
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 text-sm"
                    title="Stop VM"
                  >
                    <Square className="h-4 w-4" />
                  </button>
                  <button
                    className="flex items-center justify-center gap-2 px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700 text-sm"
                    title="Delete VM"
                    onClick={() => {
                      if (
                        confirm(
                          `Are you sure you want to delete ${vm.metadata.name}?`
                        )
                      ) {
                        deleteMutation.mutate(vm.metadata.name);
                      }
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {vms.length === 0 && (
        <Card>
          <CardContent className="py-8 text-center text-muted-foreground">
            No virtual machines found. Create your first VM to get started.
          </CardContent>
        </Card>
      )}
    </div>
  );
}

