'use client'

import { useState, useEffect, useCallback } from 'react'
import { CompanionData } from '@/lib/companion/types'
import { createDefaultPhases } from '@/lib/companion/constants'

interface UseCompanionDataOptions {
  pollingInterval?: number // ms, default 30000
  autoRefresh?: boolean
}

interface UseCompanionDataReturn {
  data: CompanionData | null
  loading: boolean
  error: string | null
  refresh: () => Promise<void>
  lastUpdated: Date | null
}

// Mock data for development - will be replaced with actual API calls
function getMockData(): CompanionData {
  return {
    context: {
      currentPhase: 'erarbeitung',
      phaseDisplayName: 'Erarbeitung',
    },
    stats: {
      classesCount: 4,
      studentsCount: 96,
      learningUnitsCreated: 23,
      gradesEntered: 156,
    },
    phases: createDefaultPhases(),
    progress: {
      percentage: 65,
      completed: 13,
      total: 20,
    },
    suggestions: [
      {
        id: '1',
        title: 'Klausuren korrigieren',
        description: 'Deutsch LK - 12 unkorrigierte Arbeiten warten',
        priority: 'urgent',
        icon: 'ClipboardCheck',
        actionTarget: '/ai/klausur-korrektur',
        estimatedTime: 120,
      },
      {
        id: '2',
        title: 'Elternsprechtag vorbereiten',
        description: 'Notenuebersicht fuer 8b erstellen',
        priority: 'high',
        icon: 'Users',
        actionTarget: '/education/grades',
        estimatedTime: 30,
      },
      {
        id: '3',
        title: 'Material hochladen',
        description: 'Arbeitsblatt fuer naechste Woche bereitstellen',
        priority: 'medium',
        icon: 'FileText',
        actionTarget: '/development/content',
        estimatedTime: 15,
      },
      {
        id: '4',
        title: 'Lernstandserhebung planen',
        description: 'Mathe 7a - Naechster Test in 2 Wochen',
        priority: 'low',
        icon: 'Calendar',
        actionTarget: '/education/planning',
        estimatedTime: 45,
      },
    ],
    upcomingEvents: [
      {
        id: 'e1',
        title: 'Mathe-Test 9b',
        date: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
        type: 'exam',
        inDays: 2,
      },
      {
        id: 'e2',
        title: 'Elternsprechtag',
        date: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
        type: 'parent_meeting',
        inDays: 5,
      },
      {
        id: 'e3',
        title: 'Notenschluss Q1',
        date: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
        type: 'deadline',
        inDays: 14,
      },
    ],
  }
}

export function useCompanionData(options: UseCompanionDataOptions = {}): UseCompanionDataReturn {
  const { pollingInterval = 30000, autoRefresh = true } = options

  const [data, setData] = useState<CompanionData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null)

  const fetchData = useCallback(async () => {
    try {
      // TODO: Replace with actual API call
      // const response = await fetch('/api/admin/companion')
      // if (!response.ok) throw new Error('Failed to fetch companion data')
      // const result = await response.json()
      // setData(result.data)

      // For now, use mock data with a small delay to simulate network
      await new Promise((resolve) => setTimeout(resolve, 300))
      setData(getMockData())
      setLastUpdated(new Date())
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }, [])

  const refresh = useCallback(async () => {
    setLoading(true)
    await fetchData()
  }, [fetchData])

  // Initial fetch
  useEffect(() => {
    fetchData()
  }, [fetchData])

  // Polling
  useEffect(() => {
    if (!autoRefresh || pollingInterval <= 0) return

    const interval = setInterval(fetchData, pollingInterval)
    return () => clearInterval(interval)
  }, [autoRefresh, pollingInterval, fetchData])

  return {
    data,
    loading,
    error,
    refresh,
    lastUpdated,
  }
}
