import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { useAuth } from '../auth/AuthContext'
import { ApiError } from '../api/client'
import { Button, Card, CopyableId, ErrorText, Field, Input, PageTitle } from '../components/ui'
import type { MemberMeData } from '../types/api'

export function ProfilePage() {
  const { refreshMember, member, tenantId, uid } = useAuth()
  const [form, setForm] = useState({
    display_name: '',
    language: '',
    currency: '',
    phone: '',
  })
  const [error, setError] = useState('')
  const [saved, setSaved] = useState(false)

  useEffect(() => {
    api
      .get<MemberMeData>('/api/v1/members/me', { auth: true })
      .then((m) =>
        setForm({
          display_name: m.display_name ?? '',
          language: m.language ?? '',
          currency: m.currency ?? '',
          phone: m.phone ?? '',
        }),
      )
      .catch((e: ApiError) => setError(e.message))
  }, [])

  const save = async () => {
    setError('')
    setSaved(false)
    try {
      await api.patch<MemberMeData>(
        '/api/v1/members/me',
        {
          display_name: form.display_name || undefined,
          language: form.language || undefined,
          currency: form.currency || undefined,
          phone: form.phone || undefined,
        },
        { auth: true },
      )
      await refreshMember()
      setSaved(true)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '更新失敗')
    }
  }

  return (
    <div>
      <PageTitle title="會員 Profile" subtitle="GET/PATCH /api/v1/members/me" />
      <Card className="mb-4 max-w-xl space-y-3">
        <CopyableId label="UID" value={member?.uid || uid} />
        <CopyableId label="Tenant ID" value={member?.tenant_id || tenantId} />
        <CopyableId label="Email" value={member?.email ?? ''} />
      </Card>
      <Card className="max-w-xl space-y-4">
        <Field label="Display Name">
          <Input
            value={form.display_name}
            onChange={(e) => setForm((f) => ({ ...f, display_name: e.target.value }))}
          />
        </Field>
        <Field label="Language">
          <Input
            value={form.language}
            onChange={(e) => setForm((f) => ({ ...f, language: e.target.value }))}
          />
        </Field>
        <Field label="Currency">
          <Input
            value={form.currency}
            onChange={(e) => setForm((f) => ({ ...f, currency: e.target.value }))}
          />
        </Field>
        <Field label="Phone">
          <Input value={form.phone} onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))} />
        </Field>
        <ErrorText message={error} />
        {saved ? <p className="text-sm text-success">已儲存</p> : null}
        <Button onClick={save}>儲存個人資料</Button>
      </Card>
    </div>
  )
}