import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { useAuth } from '../auth/AuthContext'
import { ApiError } from '../api/client'
import {
  Badge,
  Button,
  Card,
  CopyableId,
  ErrorText,
  Field,
  Input,
  PageTitle,
  SectionTitle,
} from '../components/ui'
import { formatUnixNano } from '../lib/formatDate'
import {
  formatMemberOrigin,
  formatMemberRoles,
  formatMemberStatus,
} from '../lib/memberRole'
import type { MemberMeData } from '../types/api'

const slotClass = 'ac-slot px-5 py-5'

function CopyOnlyRow({ label, value, actionLabel = '複製' }: { label: string; value: string; actionLabel?: string }) {
  const [copied, setCopied] = useState(false)

  const copy = async () => {
    if (!value) return
    await navigator.clipboard.writeText(value)
    setCopied(true)
    window.setTimeout(() => setCopied(false), 1800)
  }

  return (
    <div className={`${slotClass} flex items-center justify-between gap-4`}>
      <span className="text-sm font-bold text-ink-secondary">{label}</span>
      <button
        type="button"
        onClick={copy}
        disabled={!value}
        className="ac-btn-secondary shrink-0 px-4 py-2 text-sm"
      >
        {copied ? '已複製' : actionLabel}
      </button>
    </div>
  )
}

function ProfileMetaItem({ label, value }: { label: string; value: string }) {
  return (
    <div className={slotClass}>
      <div className="text-sm font-bold text-ink-secondary">{label}</div>
      <p className="mt-2 text-[15px] leading-relaxed text-ink">{value}</p>
    </div>
  )
}

export function ProfilePage() {
  const { refreshMember, member, tenantId, uid } = useAuth()
  const [profile, setProfile] = useState<MemberMeData | null>(null)
  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) => {
        setProfile(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 {
      const data = 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 },
      )
      setProfile(data)
      await refreshMember()
      setSaved(true)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '更新失敗')
    }
  }

  const account = profile ?? member
  const createdAt = formatUnixNano(account?.create_at)
  const updatedAt = formatUnixNano(account?.update_at)

  return (
    <div className="mx-auto w-full max-w-4xl">
      <PageTitle title="會員" subtitle="查看帳號資訊與更新個人設定" />

      <div className="grid gap-8 lg:grid-cols-2 lg:items-start">
        <Card className="p-6 md:p-8">
          <div className="flex flex-col gap-8">
            <SectionTitle>帳號資訊</SectionTitle>
            <div className="grid gap-5 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <CopyOnlyRow label="使用者 ID" value={account?.uid || uid} actionLabel="複製 ID" />
            </div>
            <CopyableId label="租戶 ID" value={account?.tenant_id || tenantId} />
            <ProfileMetaItem label="狀態" value={formatMemberStatus(account?.status)} />
            <div className="sm:col-span-2">
              <CopyableId label="電子郵件" value={account?.email ?? ''} />
            </div>
            <div className={`${slotClass} sm:col-span-2`}>
              <div className="text-sm font-bold text-ink-secondary">角色</div>
              <div className="mt-3 flex flex-wrap gap-2">
                {(account?.roles?.length ? account.roles : ['member']).map((role) => (
                  <Badge key={role} tone={role === 'admin' ? 'brand' : 'neutral'}>
                    {formatMemberRoles([role])}
                  </Badge>
                ))}
              </div>
            </div>
            <ProfileMetaItem label="註冊來源" value={formatMemberOrigin(account?.origin)} />
            {createdAt ? <ProfileMetaItem label="建立時間" value={createdAt} /> : null}
            {updatedAt ? <ProfileMetaItem label="更新時間" value={updatedAt} /> : null}
            </div>
          </div>
        </Card>

        <Card className="p-6 md:p-8">
          <div className="flex flex-col gap-8">
            <SectionTitle>個人設定</SectionTitle>
            <div className="space-y-6">
            <Field label="顯示名稱" hint="在頂欄與選單顯示的名稱">
              <Input
                value={form.display_name}
                onChange={(e) => setForm((f) => ({ ...f, display_name: e.target.value }))}
                placeholder="例如：巡樓小隊"
              />
            </Field>
            <div className="grid gap-5 sm:grid-cols-2">
              <Field label="語言" hint="例：zh-TW">
                <Input
                  value={form.language}
                  onChange={(e) => setForm((f) => ({ ...f, language: e.target.value }))}
                  placeholder="zh-TW"
                />
              </Field>
              <Field label="幣別" hint="例：TWD">
                <Input
                  value={form.currency}
                  onChange={(e) => setForm((f) => ({ ...f, currency: e.target.value }))}
                  placeholder="TWD"
                />
              </Field>
            </div>
            <Field label="電話">
              <Input
                value={form.phone}
                onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))}
                placeholder="選填"
              />
            </Field>
            </div>
            <div className="space-y-4 border-t border-line pt-6">
              <ErrorText message={error} />
              {saved ? <p className="text-sm text-success">已儲存</p> : null}
              <Button onClick={save}>儲存個人資料</Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  )
}