import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { Badge, Button, Card, ErrorText, Field, Input, PageTitle, TableAction } from '../components/ui'
import { parseStyle8DProfile } from '../lib/styleProfile'
import { OnboardingGuideTarget } from '../components/OnboardingGuide'

import { useOnboarding } from '../onboarding/OnboardingContext'
import type { ListPersonasData, PersonaData } from '../types/api'

export function PersonasPage() {
  const navigate = useNavigate()
  const { refresh: refreshOnboarding } = useOnboarding()
  const [personas, setPersonas] = useState<PersonaData[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [newName, setNewName] = useState('')
  const [error, setError] = useState('')

  const load = useCallback(async () => {
    setError('')
    const data = await api.get<ListPersonasData>('/api/v1/personas', { auth: true })
    setPersonas(data.list ?? [])
  }, [])

  useEffect(() => {
    load()
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入失敗'))
      .finally(() => setLoading(false))
  }, [load])

  const remove = async (item: PersonaData) => {
    const label = item.display_name?.trim() || '未命名人設'
    if (!window.confirm(`確定要刪除「${label}」？刪除後無法復原。`)) return
    setDeletingId(item.id)
    setError('')
    try {
      await api.delete(`/api/v1/personas/${encodeURIComponent(item.id)}`, { auth: true })
      setPersonas((prev) => prev.filter((p) => p.id !== item.id))
      await refreshOnboarding()
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '刪除失敗')
    } finally {
      setDeletingId(null)
    }
  }

  const create = async () => {
    setCreating(true)
    setError('')
    try {
      const created = await api.post<PersonaData>(
        '/api/v1/personas',
        { display_name: newName.trim() || undefined },
        { auth: true },
      )
      setNewName('')
      await refreshOnboarding()
      navigate(`/personas/${created.id}`)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗')
    } finally {
      setCreating(false)
    }
  }

  return (
    <div>
      <PageTitle
        title="人設庫"
        subtitle="回覆與發文的語氣策略（8D 風格）。找 TA 寫留言時選用；品牌與產品定位請到品牌庫。"
      />

      <OnboardingGuideTarget step="persona" className="mb-4">
        <Card className="grid gap-4 sm:grid-cols-[1fr_auto] sm:items-end">
          <Field label="新增人設名稱（選填）">
            <Input
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="例如：醫療衛教、個人品牌"
              onKeyDown={(e) => {
                if (e.key === 'Enter') void create()
              }}
            />
          </Field>
          <Button onClick={create} disabled={creating}>
            {creating ? '建立中…' : '建立人設'}
          </Button>
        </Card>
      </OnboardingGuideTarget>

      {loading ? (
        <Card>
          <p className="text-sm text-muted">載入中…</p>
        </Card>
      ) : personas.length ? (
        <div className="grid gap-3">
          {personas.map((item) => (
            <div key={item.id} className="ac-app-card p-5">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <Link to={`/personas/${item.id}`} className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <h2 className="text-base font-bold text-ink transition hover:text-brand">
                      {item.display_name || '未命名人設'}
                    </h2>
                    <div className="flex flex-wrap items-center gap-2">
                      {parseStyle8DProfile(item.style_profile) ? (
                        <Badge tone="success">8D 已建立</Badge>
                      ) : null}
                      {item.style_benchmark ? (
                        <span className="text-xs text-muted">
                          對標 @{item.style_benchmark.replace(/^@/, '')}
                        </span>
                      ) : null}
                    </div>
                  </div>
                  {item.brief ? (
                    <p className="mt-2 line-clamp-2 text-sm text-ink-secondary">{item.brief}</p>
                  ) : (
                    <p className="mt-2 text-sm text-muted">尚未填寫語氣定位與 8D 策略</p>
                  )}
                </Link>
                <TableAction
                  variant="danger"
                  disabled={deletingId === item.id}
                  onClick={() => void remove(item)}
                >
                  {deletingId === item.id ? '刪除中…' : '刪除'}
                </TableAction>
              </div>

            </div>
          ))}
        </div>
      ) : (
        <Card>
          <p className="text-sm text-ink-secondary">
            尚無人設。在上方建立第一份人設，再設定回覆語氣與 8D 對標分析。產品與受眾請到品牌庫設定。
          </p>
        </Card>
      )}

      <ErrorText message={error} />
    </div>
  )
}