import { useCallback, useEffect, useState } from 'react'
import {
  COLLECTIONS,
  DATABASE_ID,
  Query,
  databases,
  isDemoMode,
} from '../lib/appwrite'
import {
  createEmployeeWithLogin,
  deleteEmployeeWithLogin,
  listEmployeesForAdmin,
  updateEmployeeWithLogin,
} from '../lib/employeeAdminApi'

const DEMO_MODE = isDemoMode
const DEMO_EMPLOYEES = [
  {
    $id: '1',
    userId: 'user1',
    displayName: 'Kenso Grimm',
    email: 'kenso@example.com',
    shortcode: 'KNSO',
    isAdmin: true,
  },
  {
    $id: '2',
    userId: 'user2',
    displayName: 'Christian Lehmann',
    email: 'christian@example.com',
    shortcode: 'CHLE',
    isAdmin: false,
  },
]

export function useEmployees() {
  const [employees, setEmployees] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const fetchEmployees = useCallback(async () => {
    setLoading(true)
    try {
      if (DEMO_MODE) {
        setEmployees(DEMO_EMPLOYEES)
      } else {
        try {
          const result = await listEmployeesForAdmin()
          setEmployees(result.employees || [])
        } catch {
          const result = await databases.listDocuments(
            DATABASE_ID,
            COLLECTIONS.EMPLOYEES,
            [Query.orderAsc('displayName')]
          )
          setEmployees(result.documents || [])
        }
      }
      setError(null)
    } catch (err) {
      setEmployees([])
      setError(err.message || 'Mitarbeiter konnten nicht geladen werden')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchEmployees()
  }, [fetchEmployees])

  const createEmployee = async (data) => {
    try {
      if (DEMO_MODE) {
        const employee = {
          ...data,
          userId: crypto.randomUUID(),
          $id: Date.now().toString(),
        }
        setEmployees((current) => [...current, employee])
        return { success: true, data: employee }
      }
      const result = await createEmployeeWithLogin(data)
      setEmployees((current) => [...current, result.employee])
      return { success: true, data: result.employee }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const updateEmployee = async (id, data) => {
    try {
      if (DEMO_MODE) {
        setEmployees((current) =>
          current.map((employee) => employee.$id === id ? { ...employee, ...data } : employee)
        )
        return { success: true }
      }
      const result = await updateEmployeeWithLogin(id, data)
      setEmployees((current) =>
        current.map((employee) => employee.$id === id ? result.employee : employee)
      )
      return { success: true, data: result.employee }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const deleteEmployee = async (id) => {
    try {
      if (!DEMO_MODE) await deleteEmployeeWithLogin(id)
      setEmployees((current) => current.filter((employee) => employee.$id !== id))
      return { success: true }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  return {
    employees,
    loading,
    error,
    refresh: fetchEmployees,
    createEmployee,
    updateEmployee,
    deleteEmployee,
  }
}
