import { useState, useEffect, useCallback } from 'react'
import {
  COLLECTIONS,
  DATABASE_ID,
  Query,
  databases,
  isDemoMode,
} from '../lib/appwrite'
import {
  createCustomerWithPortalAccess,
  deleteCustomerWithPortalAccess,
  listCustomersForAdmin,
  updateCustomerWithPortalAccess,
} from '../lib/customerAdminApi'

const DEMO_MODE = isDemoMode

// Demo-Kunden für Testing
const DEMO_CUSTOMERS = [
  { $id: '1', code: 'C001', name: 'Kunde A', location: 'Berlin', email: 'kunde.a@example.com', phone: '030-123456' },
  { $id: '2', code: 'C002', name: 'Kunde B', location: 'München', email: 'kunde.b@example.com', phone: '089-654321' }
]

export function useCustomers() {
  const [customers, setCustomers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const fetchCustomers = useCallback(async () => {
    if (DEMO_MODE) {
      setCustomers(DEMO_CUSTOMERS)
      setLoading(false)
      return
    }

    try {
      try {
        const response = await listCustomersForAdmin()
        setCustomers(response.customers || [])
      } catch {
        const response = await databases.listDocuments(
          DATABASE_ID,
          COLLECTIONS.CUSTOMERS,
          [Query.orderAsc('name')]
        )
        setCustomers(response.documents || [])
      }
      setError(null)
    } catch (err) {
      console.error('Error fetching customers:', err)
      // Wenn Collection nicht existiert, setze leeres Array (kein Fehler)
      if (err.code === 404 || err.message?.includes('not found')) {
        setCustomers([])
        setError(null) // Kein Fehler, Collection existiert einfach noch nicht
      } else {
        setError(err.message)
        setCustomers([])
      }
    } finally {
      setLoading(false)
    }
  }, [])

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

  const createCustomer = async (data) => {
    if (DEMO_MODE) {
      const { password, ...rest } = data
      const newCustomer = {
        ...rest,
        portalPassword: password || rest.portalPassword || '',
        $id: Date.now().toString(),
      }
      setCustomers(prev => [...prev, newCustomer])
      return { success: true, data: newCustomer }
    }

    try {
      const { password, ...fields } = data
      const result = await createCustomerWithPortalAccess({ ...fields, password })
      const customer = {
        ...result.customer,
        portalPassword: result.customer?.portalPassword || password || '',
      }
      setCustomers(prev => [...prev, customer])
      return { success: true, data: customer }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const updateCustomer = async (id, data) => {
    if (DEMO_MODE) {
      const { password, ...rest } = data
      setCustomers(prev =>
        prev.map(c => {
          if (c.$id !== id) return c
          const next = { ...c, ...rest }
          if (password) next.portalPassword = password
          return next
        })
      )
      return { success: true }
    }

    try {
      const { password, ...fields } = data
      const payload = { ...fields }
      if (password) payload.password = password

      const result = await updateCustomerWithPortalAccess(id, payload)
      const customer = {
        ...result.customer,
        portalPassword:
          result.customer?.portalPassword ||
          password ||
          undefined,
      }
      setCustomers(prev =>
        prev.map(c => {
          if (c.$id !== id) return c
          return {
            ...customer,
            portalPassword: customer.portalPassword ?? c.portalPassword,
          }
        })
      )
      return { success: true, data: customer }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  const deleteCustomer = async (id) => {
    if (DEMO_MODE) {
      setCustomers(prev => prev.filter(c => c.$id !== id))
      return { success: true }
    }

    try {
      await deleteCustomerWithPortalAccess(id)
      setCustomers(prev => prev.filter(c => c.$id !== id))
      return { success: true }
    } catch (err) {
      return { success: false, error: err.message }
    }
  }

  return {
    customers,
    loading,
    error,
    refresh: fetchCustomers,
    createCustomer,
    updateCustomer,
    deleteCustomer
  }
}
