import { useState, useCallback } from 'react'
import { databases, DATABASE_ID, COLLECTIONS, Query, isDemoMode } from '../lib/appwrite'
import {
  createRoadmapPlan,
  deleteRoadmapPlan,
  completeRoadmap,
  fetchRoadmapByTicketId,
} from '../lib/roadmaps'

export function useRoadmaps() {
  const [roadmaps, setRoadmaps] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

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

  const fetchById = useCallback(async (roadmapId) => {
    if (!roadmapId || isDemoMode) return null
    try {
      return await databases.getDocument(DATABASE_ID, COLLECTIONS.ROADMAPS, roadmapId)
    } catch {
      return null
    }
  }, [])

  const fetchByTicketId = useCallback(async (ticketId) => {
    if (isDemoMode) return null
    try {
      return await fetchRoadmapByTicketId(ticketId)
    } catch {
      return null
    }
  }, [])

  const createRoadmap = async (project, data, user) => {
    if (isDemoMode) return { success: false, error: 'Demo-Modus' }
    try {
      const result = await createRoadmapPlan(project, data, user)
      setRoadmaps((prev) => [result.roadmap, ...prev])
      return { success: true, data: result }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const updateRoadmap = async (roadmapId, data) => {
    if (isDemoMode) return { success: false, error: 'Demo-Modus' }
    try {
      const doc = await databases.updateDocument(DATABASE_ID, COLLECTIONS.ROADMAPS, roadmapId, {
        ...data,
        updatedAt: new Date().toISOString(),
      })
      setRoadmaps((prev) => prev.map((r) => (r.$id === roadmapId ? doc : r)))
      return { success: true, data: doc }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const deleteRoadmap = async (roadmap, user) => {
    if (isDemoMode) return { success: false, error: 'Demo-Modus' }
    try {
      await deleteRoadmapPlan(roadmap, user)
      setRoadmaps((prev) => prev.filter((r) => r.$id !== roadmap.$id))
      return { success: true }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const completePlan = async (roadmap, user) => {
    if (isDemoMode) return { success: false, error: 'Demo-Modus' }
    try {
      const updated = await completeRoadmap(roadmap, user)
      setRoadmaps((prev) => prev.map((r) => (r.$id === updated.$id ? updated : r)))
      return { success: true, data: updated }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  return { roadmaps, loading, error, fetchAll, fetchById, fetchByTicketId, createRoadmap, updateRoadmap, deleteRoadmap, completePlan }
}
