import { useCallback, useEffect, useState } from 'react'
import { api } from '../api/client'
import {
  COPY_PERSONA_CHANGED_EVENT,
  getActiveCopyPersonaId,
  rememberCopyPersonaId,
} from '../lib/copyFlow'
import type { PersonaData } from '../types/api'

export function useActiveCopyPersona() {
  const [personaId, setPersonaIdState] = useState(getActiveCopyPersonaId)
  const [personas, setPersonas] = useState<PersonaData[]>([])
  const [persona, setPersona] = useState<PersonaData | null>(null)
  const [loading, setLoading] = useState(true)

  const setPersonaId = useCallback((id: string) => {
    const next = id.trim()
    setPersonaIdState(next)
    if (next) rememberCopyPersonaId(next)
  }, [])

  useEffect(() => {
    const onChanged = (event: Event) => {
      const detail = (event as CustomEvent<{ id?: string }>).detail
      if (detail?.id) setPersonaIdState(detail.id)
    }
    window.addEventListener(COPY_PERSONA_CHANGED_EVENT, onChanged)
    return () => window.removeEventListener(COPY_PERSONA_CHANGED_EVENT, onChanged)
  }, [])

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    api
      .get<{ list: PersonaData[] }>('/api/v1/personas', { auth: true })
      .then((data) => {
        if (cancelled) return
        const list = data.list ?? []
        setPersonas(list)
        const remembered = getActiveCopyPersonaId()
        const resolved =
          list.find((item) => item.id === remembered)?.id ||
          list.find((item) => item.id === personaId)?.id ||
          list[0]?.id ||
          ''
        if (resolved && resolved !== personaId) {
          setPersonaIdState(resolved)
          rememberCopyPersonaId(resolved)
        }
      })
      .catch(() => {
        if (!cancelled) setPersonas([])
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [personaId])

  useEffect(() => {
    if (!personaId) {
      setPersona(null)
      return
    }
    let cancelled = false
    api
      .get<PersonaData>(`/api/v1/personas/${encodeURIComponent(personaId)}`, { auth: true })
      .then((data) => {
        if (!cancelled) setPersona(data)
      })
      .catch(() => {
        if (!cancelled) setPersona(null)
      })
    return () => {
      cancelled = true
    }
  }, [personaId])

  return { personaId, persona, personas, setPersonaId, loading }
}