'use client'

import { useState } from 'react'
import { useMutation, useQuery } from '@apollo/client'
import { gql } from '@apollo/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { CREATE_RESOURCE } from '@/lib/graphql/mutations'
import { useToast } from '@/components/ui/use-toast'

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

interface ResourceTemplate {
  id: string
  name: string
  type: 'VM' | 'CONTAINER' | 'STORAGE' | 'NETWORK'
  description: string
  defaultConfig: {
    cpu?: number
    memory?: string
    storage?: string
    network?: string
  }
}

const RESOURCE_TEMPLATES: ResourceTemplate[] = [
  {
    id: 'vm-small',
    name: 'Small VM',
    type: 'VM',
    description: '2 vCPU, 4GB RAM, 20GB storage',
    defaultConfig: {
      cpu: 2,
      memory: '4Gi',
      storage: '20Gi',
    },
  },
  {
    id: 'vm-medium',
    name: 'Medium VM',
    type: 'VM',
    description: '4 vCPU, 8GB RAM, 50GB storage',
    defaultConfig: {
      cpu: 4,
      memory: '8Gi',
      storage: '50Gi',
    },
  },
  {
    id: 'vm-large',
    name: 'Large VM',
    type: 'VM',
    description: '8 vCPU, 16GB RAM, 100GB storage',
    defaultConfig: {
      cpu: 8,
      memory: '16Gi',
      storage: '100Gi',
    },
  },
  {
    id: 'container-basic',
    name: 'Basic Container',
    type: 'CONTAINER',
    description: '1 vCPU, 2GB RAM',
    defaultConfig: {
      cpu: 1,
      memory: '2Gi',
    },
  },
  {
    id: 'storage-basic',
    name: 'Basic Storage',
    type: 'STORAGE',
    description: '100GB block storage',
    defaultConfig: {
      storage: '100Gi',
    },
  },
]

interface ProvisioningWizardProps {
  onComplete?: (resourceId: string) => void
  onCancel?: () => void
}

function SiteSelect({ value, onValueChange }: { value: string; onValueChange: (value: string) => void }) {
  const { data, loading, error } = useQuery(GET_SITES)

  if (loading) {
    return (
      <Select disabled>
        <SelectTrigger className="mt-2">
          <SelectValue placeholder="Loading sites..." />
        </SelectTrigger>
      </Select>
    )
  }

  if (error) {
    return (
      <div className="mt-2 text-sm text-red-500">
        Error loading sites: {error.message}
      </div>
    )
  }

  return (
    <Select value={value} onValueChange={onValueChange}>
      <SelectTrigger className="mt-2">
        <SelectValue placeholder="Select a site" />
      </SelectTrigger>
      <SelectContent>
        {data?.sites?.map((site: any) => (
          <SelectItem key={site.id} value={site.id}>
            {site.name} ({site.region})
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}

export function ProvisioningWizard({ onComplete, onCancel }: ProvisioningWizardProps) {
  const [step, setStep] = useState(1)
  const [selectedTemplate, setSelectedTemplate] = useState<ResourceTemplate | null>(null)
  const [resourceName, setResourceName] = useState('')
  const [siteId, setSiteId] = useState('')
  const [config, setConfig] = useState<Record<string, any>>({})
  const { toast } = useToast()

  const [createResource, { loading }] = useMutation(CREATE_RESOURCE, {
    onCompleted: (data) => {
      toast({
        title: 'Resource Created',
        description: `Resource ${data.createResource.name} has been created successfully.`,
      })
      onComplete?.(data.createResource.id)
    },
    onError: (error) => {
      toast({
        title: 'Error',
        description: error.message,
        variant: 'destructive',
      })
    },
  })

  const handleTemplateSelect = (template: ResourceTemplate) => {
    setSelectedTemplate(template)
    setConfig(template.defaultConfig)
    setStep(2)
  }

  const handleNext = () => {
    if (step === 2 && resourceName && siteId) {
      setStep(3)
    }
  }

  const handleBack = () => {
    if (step > 1) {
      setStep(step - 1)
    }
  }

  const handleProvision = async () => {
    if (!selectedTemplate || !resourceName || !siteId) {
      toast({
        title: 'Validation Error',
        description: 'Please fill in all required fields.',
        variant: 'destructive',
      })
      return
    }

    await createResource({
      variables: {
        input: {
          name: resourceName,
          type: selectedTemplate.type,
          siteId,
          metadata: {
            template: selectedTemplate.id,
            config,
          },
        },
      },
    })
  }

  return (
    <div className="w-full max-w-4xl mx-auto p-6">
      <Card>
        <CardHeader>
          <CardTitle>Provision Resource</CardTitle>
        </CardHeader>
        <CardContent>
          <Tabs value={step.toString()} className="w-full">
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="1" disabled={step < 1}>
                Select Template
              </TabsTrigger>
              <TabsTrigger value="2" disabled={step < 2}>
                Configure
              </TabsTrigger>
              <TabsTrigger value="3" disabled={step < 3}>
                Review
              </TabsTrigger>
            </TabsList>

            <TabsContent value="1" className="mt-6">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {RESOURCE_TEMPLATES.map((template) => (
                  <Card
                    key={template.id}
                    className={`cursor-pointer transition-all hover:border-phoenix-fire ${
                      selectedTemplate?.id === template.id
                        ? 'border-phoenix-fire border-2'
                        : ''
                    }`}
                    onClick={() => handleTemplateSelect(template)}
                  >
                    <CardHeader>
                      <CardTitle className="text-lg">{template.name}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-sm text-gray-400 mb-4">{template.description}</p>
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-gray-500">{template.type}</span>
                        <Button variant="outline" size="sm">
                          Select
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </TabsContent>

            <TabsContent value="2" className="mt-6">
              <div className="space-y-6">
                <div>
                  <Label htmlFor="resourceName">Resource Name</Label>
                  <Input
                    id="resourceName"
                    value={resourceName}
                    onChange={(e) => setResourceName(e.target.value)}
                    placeholder="my-resource"
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label htmlFor="siteId">Site</Label>
                  <SiteSelect value={siteId} onValueChange={setSiteId} />
                </div>

                {selectedTemplate && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold">Configuration</h3>
                    
                    {config.cpu !== undefined && (
                      <div>
                        <Label htmlFor="cpu">vCPU</Label>
                        <Input
                          id="cpu"
                          type="number"
                          value={config.cpu}
                          onChange={(e) =>
                            setConfig({ ...config, cpu: parseInt(e.target.value) })
                          }
                          className="mt-2"
                          min={1}
                        />
                      </div>
                    )}

                    {config.memory && (
                      <div>
                        <Label htmlFor="memory">Memory</Label>
                        <Input
                          id="memory"
                          value={config.memory}
                          onChange={(e) =>
                            setConfig({ ...config, memory: e.target.value })
                          }
                          className="mt-2"
                          placeholder="4Gi"
                        />
                      </div>
                    )}

                    {config.storage && (
                      <div>
                        <Label htmlFor="storage">Storage</Label>
                        <Input
                          id="storage"
                          value={config.storage}
                          onChange={(e) =>
                            setConfig({ ...config, storage: e.target.value })
                          }
                          className="mt-2"
                          placeholder="20Gi"
                        />
                      </div>
                    )}
                  </div>
                )}
              </div>
            </TabsContent>

            <TabsContent value="3" className="mt-6">
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">Review Configuration</h3>
                
                <div className="bg-studio-dark p-4 rounded-lg space-y-2">
                  <div className="flex justify-between">
                    <span className="text-gray-400">Template:</span>
                    <span>{selectedTemplate?.name}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-400">Resource Name:</span>
                    <span>{resourceName}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-400">Type:</span>
                    <span>{selectedTemplate?.type}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-400">Site:</span>
                    <span>{siteId}</span>
                  </div>
                  {config.cpu && (
                    <div className="flex justify-between">
                      <span className="text-gray-400">vCPU:</span>
                      <span>{config.cpu}</span>
                    </div>
                  )}
                  {config.memory && (
                    <div className="flex justify-between">
                      <span className="text-gray-400">Memory:</span>
                      <span>{config.memory}</span>
                    </div>
                  )}
                  {config.storage && (
                    <div className="flex justify-between">
                      <span className="text-gray-400">Storage:</span>
                      <span>{config.storage}</span>
                    </div>
                  )}
                </div>

                <div className="bg-status-warning/10 border border-status-warning/20 p-4 rounded-lg">
                  <p className="text-sm text-status-warning">
                    <strong>Note:</strong> Resource provisioning may take a few minutes.
                    You can track the status in the resources list.
                  </p>
                </div>
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex justify-between mt-6">
            <div>
              {step > 1 && (
                <Button variant="outline" onClick={handleBack}>
                  Back
                </Button>
              )}
            </div>
            <div className="flex gap-2">
              {onCancel && (
                <Button variant="ghost" onClick={onCancel}>
                  Cancel
                </Button>
              )}
              {step < 3 && (
                <Button
                  variant="phoenix"
                  onClick={handleNext}
                  disabled={!selectedTemplate || (step === 2 && (!resourceName || !siteId))}
                >
                  Next
                </Button>
              )}
              {step === 3 && (
                <Button
                  variant="phoenix"
                  onClick={handleProvision}
                  disabled={loading}
                >
                  {loading ? 'Provisioning...' : 'Provision Resource'}
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

