'use client'

import { useState, useEffect, useCallback } from 'react'
import type { TeamMember, InvitationListItem, InvitationStatus, TeamStats } from '@/lib/invite/types'

interface InviteListResponse {
  members: InvitationListItem[]
  pendingInvites: InvitationListItem[]
}

// ── Hook ─────────────────────────────────────────────────────────

export function useInvitations() {
  const [members, setMembers] = useState<TeamMember[]>([])
  const [pendingInvites, setPendingInvites] = useState<InvitationListItem[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchData = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/invite')
      if (!res.ok) {
        if (res.status === 401) {
          // Not logged in — return empty state
          setMembers([])
          setPendingInvites([])
          return
        }
        throw new Error(`Failed to fetch invitations: ${res.status}`)
      }
      const data: InviteListResponse = await res.json()

      // Map completed members — only the invitees the current user invited.
      // The current user (the inviter) is NOT a member; they are the owner
      // and should never appear in this list.
      const mappedMembers: TeamMember[] = (data.members || []).map((m) => ({
        id: m.id,
        name: m.inviteeName || `用户${m.inviteePhone.slice(-4)}`,
        phone: m.inviteePhone,
        avatarLetter: (m.inviteeName || '?').charAt(0).toUpperCase(),
        isHost: false,
        memberStatus: 'active' as const,
        joinedAt: m.createdAt,
        channelId: m.createdChannelId || undefined,
      }))

      setMembers(mappedMembers)
      setPendingInvites(data.pendingInvites || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load invitations')
    } finally {
      setLoading(false)
    }
  }, [])

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

  // Server already dedupes within a 5s window (see POST /api/invite), so a
  // double-fired StrictMode effect just costs an extra fetch — no client
  // dedup needed.
  const createInvite = useCallback(async (): Promise<{ link: string; token: string }> => {
    const res = await fetch('/api/invite', { method: 'POST' })
    if (!res.ok) throw new Error('Failed to create invitation')
    const data = await res.json()
    setPendingInvites((prev) =>
      prev.some((inv) => inv.inviteToken === data.token)
        ? prev
        : [
            {
              id: data.id,
              inviteToken: data.token,
              inviteePhone: '',
              inviteeName: '',
              status: 'pending' as InvitationStatus,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            },
            ...prev,
          ],
    )
    return { link: data.link, token: data.token }
  }, [])

  const cancelInvite = useCallback(async (inviteToken: string, dbId?: string) => {
    const res = await fetch(`/api/invite/${inviteToken}`, { method: 'DELETE' })
    if (!res.ok) throw new Error('Failed to cancel invitation')
    setPendingInvites((prev) => prev.filter((inv) => inv.id !== dbId && inv.inviteToken !== inviteToken))
  }, [])

  // Hard-delete a member: the server drops the im_channel row, the
  // workspace row, the invitation row, and the invitee's user directory
  // on disk. The operation is irreversible — the calling view should
  // confirm with the user first.
  const revokeMember = useCallback(async (channelId: string) => {
    const res = await fetch(`/api/invite/member/${channelId}`, { method: 'DELETE' })
    if (!res.ok) {
      const data = await res.json().catch(() => ({}))
      throw new Error(data.error || 'Failed to remove member')
    }
    setMembers((prev) => prev.filter((m) => m.channelId !== channelId))
  }, [])

  // Stats are counted from members only (the invitees), excluding any
  // host-self row that may sneak in. Pending count is the in-flight queue.
  const realMembers = members.filter((m) => !m.isHost)
  const stats: TeamStats = {
    totalMembers: realMembers.length,
    activeCount: realMembers.filter((m) => m.memberStatus === 'active').length,
    pendingCount: pendingInvites.length,
    botCount: realMembers.filter((m) => m.channelId).length,
  }

  return {
    members,
    pendingInvites,
    stats,
    loading,
    error,
    refresh: fetchData,
    createInvite,
    cancelInvite,
    revokeMember,
  }
}
