'use client'

import { getGitHubToken } from '@/actions/github'
import { Octokit } from '@octokit/rest'
import { useState } from 'react'
import { toast } from 'sonner'

interface CreateRepoFromTemplateParams {
  templateOwner: string
  templateRepo: string
  name: string
  description?: string
  isPrivate?: boolean
}

interface CreateRepoResult {
  success: boolean
  repositoryUrl?: string
  error?: string
}

/**
 * Hook to directly interact with GitHub API using user's own token
 * Bypasses backend GitHub integration issues
 */
export function useDirectGitHub() {
  const [isLoading, setIsLoading] = useState(false)

  const createRepoFromTemplate = async (
    params: CreateRepoFromTemplateParams
  ): Promise<CreateRepoResult> => {
    setIsLoading(true)

    try {
      console.log(
        '🔄 Creating repository from template directly via GitHub API...'
      )
      console.log('📋 Parameters:', params)

      // Get user's GitHub token
      const token = await getGitHubToken()
      if (!token) {
        throw new Error(
          'GitHub token not available. Please reconnect your GitHub account.'
        )
      }

      // Create Octokit instance with user's token
      const octokit = new Octokit({ auth: token })

      // Get the authenticated user's info to use as owner
      const { data: authUser } = await octokit.rest.users.getAuthenticated()
      console.log('👤 Authenticated GitHub user:', authUser.login)

      // Create repository from template
      const { data: newRepo } = await octokit.rest.repos.createUsingTemplate({
        template_owner: params.templateOwner,
        template_repo: params.templateRepo,
        owner: authUser.login, // Use authenticated user as owner
        name: params.name,
        description:
          params.description ||
          `Created from ${params.templateOwner}/${params.templateRepo}`,
        private: params.isPrivate || false,
        include_all_branches: false
      })

      console.log('✅ Repository created successfully:', newRepo.html_url)

      return {
        success: true,
        repositoryUrl: newRepo.html_url
      }
    } catch (error) {
      console.error('❌ Failed to create repository from template:', error)

      let errorMessage = 'Failed to create repository from template'
      if (error instanceof Error) {
        errorMessage = error.message
      }

      return {
        success: false,
        error: errorMessage
      }
    } finally {
      setIsLoading(false)
    }
  }

  const getUserRepos = async () => {
    try {
      const token = await getGitHubToken()
      if (!token) {
        throw new Error('GitHub token not available')
      }

      const octokit = new Octokit({ auth: token })
      const { data: repos } = await octokit.rest.repos.listForAuthenticatedUser(
        {
          sort: 'updated',
          per_page: 100
        }
      )

      return repos
    } catch (error) {
      console.error('❌ Failed to fetch user repositories:', error)
      throw error
    }
  }

  return {
    createRepoFromTemplate,
    getUserRepos,
    isLoading
  }
}
