// src/hooks/useDeployment.tsx
'use client'

import { useState } from 'react'
import { useGQLClient } from '@/context'
import { toast } from 'sonner'

// Define the structure of deployment configuration
export interface DeploymentConfig {
  projectId?: string
  organizationSlug: string
  repository: string
  branch: string
  name: string
  environmentVariables?: Array<{
    key: string
    value: string
    environments: string[]
  }>
}

// Define the structure of deployment result
export interface DeploymentResult {
  id: string
  url?: string
  status: string
}

export function useDeployment() {
  const [isDeploying, setIsDeploying] = useState(false)
  const [deploymentResult, setDeploymentResult] = useState<DeploymentResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const gqlClient = useGQLClient()

  // Function to create a new project and deploy it
  const deployRepository = async (config: DeploymentConfig): Promise<DeploymentResult> => {
    setIsDeploying(true)
    setError(null)
    
    try {
      console.log('🚀 Starting repository deployment:', config)
      
      // Use the addProject mutation from your existing GraphQL client
      const projectResult = await gqlClient.addProject(
        config.organizationSlug,
        {
          name: config.name,
          repository: config.repository,
          prodBranch: config.branch,
          template: 'webapp', // Default template
          paymentAddress: "0x1ac42F4A25Ae0137d10a825a2e33e32de0F6B57E", // Should come from wallet
          txHash: "0x0000000000000000000000000000000000000000000000000000000000000000" // Placeholder
        },
        undefined, // lrn - will be handled in configure step
        undefined, // auctionParams - will be handled in configure step
        config.environmentVariables || []
      )
      
      if (!projectResult.addProject?.id) {
        throw new Error('Failed to create project')
      }
      
      toast.success('Project created successfully!')
      
      // Wait a moment for deployment to start
      await new Promise(resolve => setTimeout(resolve, 2000))

      // Get the newly created project to find its deployment
      const projectData = await gqlClient.getProject(projectResult.addProject.id)
      
      // Find the most recent deployment
      const deployment = projectData.project?.deployments?.[0]
      
      const deploymentResult: DeploymentResult = {
        id: deployment?.id || projectResult.addProject.id,
        url: deployment?.applicationDeploymentRecordData?.url,
        status: deployment?.status || 'Building'
      }
      
      setDeploymentResult(deploymentResult)
      toast.success('Deployment initiated successfully')
      return deploymentResult
      
    } catch (error) {
      console.error('Deployment failed:', error)
      const errorMessage = error instanceof Error ? error.message : 'Unknown error'
      setError(errorMessage)
      toast.error(`Failed to deploy repository: ${errorMessage}`)
      throw error
    } finally {
      setIsDeploying(false)
    }
  }

  // Function to check the status of a deployment
  const getDeploymentStatus = async (projectId: string) => {
    try {
      const result = await gqlClient.getProject(projectId)
      return result.project?.deployments?.[0]?.status
    } catch (error) {
      console.error('Failed to get deployment status:', error)
      throw error
    }
  }

  // Function to get all deployments for a project
  const getDeployments = async (projectId: string) => {
    try {
      return await gqlClient.getDeployments(projectId)
    } catch (error) {
      console.error('Failed to get deployments:', error)
      throw error
    }
  }

  const reset = () => {
    setDeploymentResult(null)
    setError(null)
    setIsDeploying(false)
  }

  return {
    deployRepository,
    getDeploymentStatus,
    getDeployments,
    isDeploying,
    deploymentResult,
    error,
    reset
  }
}