import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api/client'
import {
  REPLY_PERSONA_CHANGED_EVENT,
  getReplyPersonaId,
  rememberReplyPersonaId,
} from '../lib/brandContext'
import { parseStyle8DProfile } from '../lib/styleProfile'
import { Field, Select } from './ui'
import type { ListPersonasData, PersonaData } from '../types/api'

type Props = {
  value: string
  onChange: (id: string) => void
}

export function ReplyPersonaPicker({ value, onChange }: Props) {
  const [personas, setPersonas] = useState<PersonaData[]>([])

  useEffect(() => {
    void api
      .get<ListPersonasData>('/api/v1/personas', { auth: true })
      .then((data) => setPersonas(data.list ?? []))
      .catch(() => setPersonas([]))
  }, [])

  useEffect(() => {
    if (value) return
    const stored = getReplyPersonaId()
    const fallback =
      (stored && personas.some((p) => p.id === stored) ? stored : '') ||
      personas.find((p) => parseStyle8DProfile(p.style_profile))?.id ||
      personas[0]?.id ||
      ''
    if (fallback) {
      rememberReplyPersonaId(fallback)
      onChange(fallback)
    }
  }, [value, personas, onChange])

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

  if (!personas.length) {
    return (
      <p className="text-sm text-ink-secondary">
        寫留言需要人設語氣。
        <Link to="/personas" className="ml-1 font-semibold text-brand hover:underline">
          建立人設
        </Link>
      </p>
    )
  }

  return (
    <Field label="回覆人設（語氣）">
      <Select
        value={value}
        onChange={(e) => {
          const next = e.target.value
          rememberReplyPersonaId(next)
          onChange(next)
        }}
      >
        {!value ? <option value="">請選擇人設</option> : null}
        {personas.map((item) => (
          <option key={item.id} value={item.id}>
            {item.display_name?.trim() || '未命名人設'}
            {parseStyle8DProfile(item.style_profile) ? ' · 8D' : ''}
          </option>
        ))}
      </Select>
    </Field>
  )
}