'use client'

import { useState, useEffect, useCallback } from 'react'
import { apiFetch } from '@/lib/api'

export type EmployeeRole = 'OWNER' | 'MANAGER' | 'AGENT'
export type InvitationStatus = 'accepted' | 'pending' | 'revoked'

export interface TeamMember {
  id: string
  firstName: string
  lastName: string
  email: string
  phone: string | null
  role: EmployeeRole
  isActive: boolean
  createdAt: string
  updatedAt: string
  lastActiveAt: string | null
  invitationStatus: InvitationStatus
}

export interface TeamStats {
  total: number
  active: number
  pending: number
  inactive: number
}

export interface InvitePayload {
  firstName: string
  lastName: string
  email: string
  role: 'MANAGER' | 'AGENT'
}

export function useTeam() {
  const [members, setMembers] = useState<TeamMember[]>([])
  const [stats, setStats] = useState<TeamStats>({ total: 0, active: 0, pending: 0, inactive: 0 })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const refetch = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [membersData, statsData] = await Promise.all([
        apiFetch<TeamMember[]>('/team'),
        apiFetch<TeamStats>('/team/stats'),
      ])
      setMembers(membersData)
      setStats(statsData)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [])

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

  const invite = useCallback(async (payload: InvitePayload) => {
    const result = await apiFetch<{ employee: TeamMember; invitationId: string }>(
      '/team/invite',
      { method: 'POST', body: JSON.stringify(payload) }
    )
    setMembers((prev) => [...prev, result.employee])
    setStats((prev) => ({
      ...prev,
      total: prev.total + 1,
      pending: prev.pending + 1,
    }))
    return result
  }, [])

  const updateRole = useCallback(async (memberId: string, role: 'MANAGER' | 'AGENT') => {
    const updated = await apiFetch<TeamMember>(`/team/${memberId}/role`, {
      method: 'PATCH',
      body: JSON.stringify({ role }),
    })
    setMembers((prev) =>
      prev.map((m) => (m.id === memberId ? { ...m, role: updated.role } : m))
    )
    return updated
  }, [])

  const deactivate = useCallback(async (memberId: string) => {
    const updated = await apiFetch<TeamMember>(`/team/${memberId}/deactivate`, {
      method: 'POST',
    })
    setMembers((prev) =>
      prev.map((m) => (m.id === memberId ? { ...m, isActive: false } : m))
    )
    setStats((prev) => ({ ...prev, active: prev.active - 1, inactive: prev.inactive + 1 }))
    return updated
  }, [])

  const reactivate = useCallback(async (memberId: string) => {
    const updated = await apiFetch<TeamMember>(`/team/${memberId}/reactivate`, {
      method: 'POST',
    })
    setMembers((prev) =>
      prev.map((m) => (m.id === memberId ? { ...m, isActive: true } : m))
    )
    setStats((prev) => ({ ...prev, active: prev.active + 1, inactive: prev.inactive - 1 }))
    return updated
  }, [])

  const remove = useCallback(async (memberId: string) => {
    await apiFetch<{ success: boolean }>(`/team/${memberId}`, {
      method: 'DELETE',
    })
    const target = members.find((m) => m.id === memberId)
    setMembers((prev) => prev.filter((m) => m.id !== memberId))
    setStats((prev) => ({
      ...prev,
      total: prev.total - 1,
      active: target?.isActive ? prev.active - 1 : prev.active,
      pending: target?.invitationStatus === 'pending' ? prev.pending - 1 : prev.pending,
      inactive: !target?.isActive && target?.invitationStatus === 'accepted'
        ? prev.inactive - 1
        : prev.inactive,
    }))
  }, [members])

  return {
    members,
    stats,
    loading,
    error,
    refetch,
    invite,
    updateRole,
    deactivate,
    reactivate,
    remove,
  }
}
