import { useState, useCallback } from 'react'
import { databases, DATABASE_ID, COLLECTIONS, Query, PREVIEW_TEMPLATE_NAME, isDemoMode } from '../lib/appwrite'

function isTemplateProject(project) {
  const template = project.templateName || PREVIEW_TEMPLATE_NAME
  return template === PREVIEW_TEMPLATE_NAME || Boolean(project.repoFullName)
}

export function useWebsiteProjects() {
  const [projects, setProjects] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const fetchAllProjects = useCallback(async () => {
    if (isDemoMode) return []
    setLoading(true)
    setError(null)
    try {
      const response = await databases.listDocuments(
        DATABASE_ID, COLLECTIONS.WEBSITE_PROJECTS,
        [Query.orderDesc('$createdAt'), Query.limit(500)]
      )
      setProjects(response.documents)
      return response.documents
    } catch (err) {
      setError(err.message)
      return []
    } finally {
      setLoading(false)
    }
  }, [])

  const fetchByTicketId = useCallback(async (ticketId) => {
    if (!ticketId || isDemoMode) return []
    try {
      const response = await databases.listDocuments(
        DATABASE_ID, COLLECTIONS.WEBSITE_PROJECTS,
        [Query.equal('ticketId', ticketId), Query.limit(100)]
      )
      return response.documents
    } catch {
      return []
    }
  }, [])

  const getAvailableProjects = useCallback((allProjects, customerId) => {
    return (allProjects || []).filter(isTemplateProject).filter((p) => {
      if (!p.customerId) return true
      return customerId && p.customerId === customerId
    })
  }, [])

  const assignProject = async (projectId, { customerId, ticketId }) => {
    try {
      const response = await databases.updateDocument(
        DATABASE_ID, COLLECTIONS.WEBSITE_PROJECTS, projectId,
        { customerId, ticketId, updatedAt: new Date().toISOString() }
      )
      setProjects((prev) => prev.map((p) => (p.$id === projectId ? response : p)))
      return { success: true }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const assignProjects = async (projectIds, ctx) => {
    const results = await Promise.all(projectIds.map((id) => assignProject(id, ctx)))
    return results.find((r) => !r.success) || { success: true }
  }

  const unassignProject = async (projectId) => {
    try {
      await databases.updateDocument(
        DATABASE_ID, COLLECTIONS.WEBSITE_PROJECTS, projectId,
        { customerId: '', ticketId: '', updatedAt: new Date().toISOString() }
      )
      return { success: true }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  return { projects, loading, error, fetchAllProjects, fetchByTicketId, getAvailableProjects, assignProjects, unassignProject }
}
