'use client'

import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { gql } from 'graphql-tag'
import { apolloClient } from '@/lib/graphql/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useRouter } from 'next/navigation'
import { Server } from 'lucide-react'

const GET_SITES = gql`
  query GetSites {
    sites {
      id
      name
      region
      status
    }
  }
`

const CREATE_RESOURCE = gql`
  mutation CreateResource($input: CreateResourceInput!) {
    createResource(input: $input) {
      id
      name
      type
      status
      site {
        id
        name
      }
    }
  }
`

export function ResourceProvisioningForm() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    name: '',
    type: 'VM',
    siteId: '',
    metadata: {},
  })

  const { data: sites } = useQuery({
    queryKey: ['sites'],
    queryFn: async () => {
      const result = await apolloClient.query({ query: GET_SITES })
      return result.data.sites
    },
  })

  const createMutation = useMutation({
    mutationFn: async (variables: any) => {
      const result = await apolloClient.mutate({
        mutation: CREATE_RESOURCE,
        variables,
      })
      return result.data.createResource
    },
    onSuccess: (data) => {
      router.push(`/resources/${data.id}`)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    createMutation.mutate({
      input: {
        name: formData.name,
        type: formData.type,
        siteId: formData.siteId,
        metadata: formData.metadata,
      },
    })
  }

  return (
    <Card className="max-w-2xl mx-auto border-studio-medium bg-studio-dark">
      <CardHeader>
        <div className="flex items-center gap-3">
          <Server className="h-6 w-6 text-phoenix-fire" />
          <CardTitle className="text-2xl text-white">Provision New Resource</CardTitle>
        </div>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="name">Resource Name</Label>
            <Input
              id="name"
              placeholder="my-resource-01"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="type">Resource Type</Label>
            <Select
              value={formData.type}
              onValueChange={(value) => setFormData({ ...formData, type: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select resource type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="VM">Virtual Machine</SelectItem>
                <SelectItem value="CONTAINER">Container</SelectItem>
                <SelectItem value="STORAGE">Storage</SelectItem>
                <SelectItem value="NETWORK">Network</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="siteId">Site</Label>
            <Select
              value={formData.siteId}
              onValueChange={(value) => setFormData({ ...formData, siteId: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select site" />
              </SelectTrigger>
              <SelectContent>
                {sites?.map((site: any) => (
                  <SelectItem key={site.id} value={site.id}>
                    {site.name} ({site.region})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {createMutation.isError && (
            <div className="text-red-400 text-sm">
              {(createMutation.error as Error).message || 'Failed to create resource'}
            </div>
          )}

          <div className="flex gap-4">
            <Button
              type="submit"
              variant="phoenix"
              disabled={createMutation.isPending || !formData.name || !formData.siteId}
            >
              {createMutation.isPending ? 'Provisioning...' : 'Provision Resource'}
            </Button>
            <Button
              type="button"
              variant="ghost"
              onClick={() => router.back()}
            >
              Cancel
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}

