'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
// import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useToast } from '@/hooks/use-toast'

interface DeploymentWizardProps {
  product: {
    id: string
    name: string
    versions?: Array<{
      id: string
      version: string
      isLatest: boolean
    }>
  }
  onClose: () => void
}

const DEPLOYMENT_TYPES = [
  { value: 'TERRAFORM', label: 'Terraform' },
  { value: 'HELM', label: 'Helm' },
  { value: 'ANSIBLE', label: 'Ansible' },
  { value: 'KUBERNETES', label: 'Kubernetes' },
]

export function DeploymentWizard({ product, onClose }: DeploymentWizardProps) {
  const router = useRouter()
  const { toast } = useToast()
  const [step, setStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const [formData, setFormData] = useState({
    name: `${product.name}-${Date.now()}`,
    productVersionId: product.versions?.find((v) => v.isLatest)?.id || product.versions?.[0]?.id,
    region: '',
    deploymentType: 'TERRAFORM' as string,
    parameters: {} as Record<string, any>,
  })

  const handleSubmit = async () => {
    setLoading(true)
    try {
      const response = await fetch('/api/graphql', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          query: `
            mutation CreateDeployment($input: CreateDeploymentInput!) {
              createDeployment(input: $input) {
                id
                name
                status
              }
            }
          `,
          variables: {
            input: {
              name: formData.name,
              productId: product.id,
              productVersionId: formData.productVersionId,
              region: formData.region || undefined,
              deploymentType: formData.deploymentType,
              parameters: formData.parameters,
            },
          },
        }),
      })

      const data = await response.json()

      if (data.errors) {
        throw new Error(data.errors[0].message)
      }

      toast({
        title: 'Deployment Created',
        description: 'Your deployment has been initiated successfully.',
      })

      onClose()
      router.push(`/marketplace/deployments/${data.data.createDeployment.id}`)
    } catch (error) {
      toast({
        title: 'Deployment Failed',
        description: error instanceof Error ? error.message : 'Failed to create deployment',
        variant: 'destructive',
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Deploy {product.name}</DialogTitle>
          <DialogDescription>
            Configure your deployment settings
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Step 1: Basic Configuration */}
          {step === 1 && (
            <div className="space-y-4">
              <div>
                <Label htmlFor="name">Deployment Name</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="my-deployment"
                />
              </div>

              {product.versions && product.versions.length > 1 && (
                <div>
                  <Label htmlFor="version">Version</Label>
                  <Select
                    value={formData.productVersionId}
                    onValueChange={(value) =>
                      setFormData({ ...formData, productVersionId: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {product.versions.map((version) => (
                        <SelectItem key={version.id} value={version.id}>
                          v{version.version}
                          {version.isLatest && ' (Latest)'}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              <div>
                <Label htmlFor="region">Region (Optional)</Label>
                <Input
                  id="region"
                  value={formData.region}
                  onChange={(e) => setFormData({ ...formData, region: e.target.value })}
                  placeholder="us-east-1"
                />
              </div>

              <div>
                <Label htmlFor="deploymentType">Deployment Type</Label>
                <Select
                  value={formData.deploymentType}
                  onValueChange={(value) =>
                    setFormData({ ...formData, deploymentType: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {DEPLOYMENT_TYPES.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}

          {/* Step 2: Parameters */}
          {step === 2 && (
            <div className="space-y-4">
              <p className="text-sm text-muted-foreground">
                Configure deployment parameters. These will be passed to the template.
              </p>
              <div>
                <Label htmlFor="parameters">Parameters (JSON)</Label>
                <textarea
                  id="parameters"
                  value={JSON.stringify(formData.parameters, null, 2)}
                  onChange={(e) => {
                    try {
                      const parsed = JSON.parse(e.target.value)
                      setFormData({ ...formData, parameters: parsed })
                    } catch {
                      // Invalid JSON, keep as is
                    }
                  }}
                  placeholder='{"key": "value"}'
                  className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                  rows={10}
                />
              </div>
            </div>
          )}

          {/* Navigation */}
          <div className="flex justify-between">
            <div>
              {step > 1 && (
                <Button variant="outline" onClick={() => setStep(step - 1)}>
                  Previous
                </Button>
              )}
            </div>
            <div className="flex gap-2">
              {step < 2 ? (
                <Button onClick={() => setStep(step + 1)}>Next</Button>
              ) : (
                <Button onClick={handleSubmit} disabled={loading}>
                  {loading ? 'Deploying...' : 'Deploy'}
                </Button>
              )}
              <Button variant="outline" onClick={onClose}>
                Cancel
              </Button>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}

