'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { FileText, Pencil, Plus, Search, Trash2 } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendCoupon, yuan } from '@/lib/backend'

const statusLabel: Record<BackendCoupon['status'], string> = {
  active: '启用',
  paused: '暂停',
  expired: '过期',
}

const discountTypeLabel: Record<BackendCoupon['discountType'], string> = {
  amount: '固定金额',
  percent: '百分比',
}

function formatDiscount(coupon: BackendCoupon) {
  if (coupon.discountType === 'percent') {
    const cap = coupon.maxDiscountAmount ? `，封顶 ¥${yuan(coupon.maxDiscountAmount).toLocaleString()}` : ''
    return `${coupon.discountValue}%${cap}`
  }
  return `减 ¥${yuan(coupon.discountValue).toLocaleString()}`
}

function formatDate(value?: string | null) {
  if (!value) return '长期'
  return new Date(value).toLocaleString('zh-CN')
}

export default function AdminCouponsPage() {
  const [items, setItems] = useState<BackendCoupon[]>([])
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [discountType, setDiscountType] = useState('')
  const [loading, setLoading] = useState(true)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')

  async function reload(nextSearch = search, nextStatus = status, nextDiscountType = discountType) {
    setLoading(true)
    try {
      const result = await backend.adminCoupons({ search: nextSearch.trim(), status: nextStatus, discountType: nextDiscountType })
      setItems(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '优惠码加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void reload('', '', '')
    }, 0)
    return () => window.clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  async function updateStatus(item: BackendCoupon, nextStatus: BackendCoupon['status']) {
    try {
      await backend.updateAdminCoupon(item.id, { ...item, status: nextStatus })
      setSaved(nextStatus === 'active' ? '优惠码已启用' : '优惠码已暂停')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '优惠码状态更新失败')
    }
  }

  async function deleteCoupon(item: BackendCoupon) {
    if (!window.confirm('确定删除这个优惠码吗？已使用过的优惠码会自动改为暂停。')) return
    try {
      const result = await backend.deleteAdminCoupon(item.id)
      setSaved(result.paused ? '优惠码已有使用记录，已改为暂停' : '优惠码已删除')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '优惠码删除失败')
    }
  }

  return (
    <AdminShell title="优惠码" description="维护优惠码、适用范围、用户限制、预算、叠加规则和使用记录。">
      {(saved || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || saved}
        </div>
      )}

      <form className="mb-3 flex flex-col gap-3 border border-line bg-white px-4 py-3 lg:flex-row lg:items-center" onSubmit={(event) => { event.preventDefault(); void reload() }}>
        <div className="relative flex-1">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索优惠码或名称" className="h-10 w-full rounded-[4px] border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
        </div>
        <select value={status} onChange={(event) => { setStatus(event.target.value); void reload(search, event.target.value, discountType) }} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
          <option value="">全部状态</option>
          <option value="active">启用</option>
          <option value="paused">暂停</option>
          <option value="expired">过期</option>
        </select>
        <select value={discountType} onChange={(event) => { setDiscountType(event.target.value); void reload(search, status, event.target.value) }} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
          <option value="">全部类型</option>
          <option value="amount">固定金额</option>
          <option value="percent">百分比</option>
        </select>
        <button className="h-10 rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white">查询</button>
        <Link href="/admin/coupons/new" className="inline-flex h-10 items-center justify-center gap-2 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark">
          <Plus className="h-4 w-4" />
          新增优惠码
        </Link>
      </form>

      <section className="border border-line bg-white">
        <div className="grid grid-cols-[130px_minmax(220px,1fr)_150px_150px_150px_230px] border-b border-line px-4 py-3 text-xs font-extrabold text-soft">
          <span>优惠码</span><span>规则</span><span>用量</span><span>预算</span><span>有效期</span><span>操作</span>
        </div>
        {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载优惠码...</div>}
        {!loading && items.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无优惠码</div>}
        {!loading && items.map((item) => (
          <div key={item.id} className="grid grid-cols-[130px_minmax(220px,1fr)_150px_150px_150px_230px] items-center border-b border-line px-4 py-4 text-sm hover:bg-bg">
            <div>
              <div className="font-extrabold text-ink">{item.code}</div>
              <div className={`mt-1 text-xs font-bold ${item.status === 'active' ? 'text-green' : item.status === 'paused' ? 'text-[#b45309]' : 'text-red-600'}`}>{statusLabel[item.status]}</div>
            </div>
            <div className="min-w-0">
              <div className="truncate font-bold text-ink">{item.name}</div>
              <div className="mt-1 text-xs font-bold text-muted">{discountTypeLabel[item.discountType]} · {formatDiscount(item)} · 门槛 ¥{yuan(item.minOrderAmount).toLocaleString()}</div>
              <div className="mt-1 truncate text-xs text-soft">{item.description || '无说明'}</div>
            </div>
            <div className="font-bold text-muted">
              <div>{item.usedQuantity}/{item.totalQuantity}</div>
              <div className="mt-1 text-xs">剩余 {item.remainingQuantity}</div>
            </div>
            <div className="font-bold text-muted">
              <div>{item.budgetAmount ? `¥${yuan(item.usedDiscountAmount || 0).toLocaleString()} / ¥${yuan(item.budgetAmount).toLocaleString()}` : '不限'}</div>
            </div>
            <div className="text-xs font-bold text-muted">
              <div>{formatDate(item.startsAt)}</div>
              <div className="mt-1">至 {formatDate(item.endsAt)}</div>
            </div>
            <div className="flex flex-wrap gap-2">
              <Link href={`/admin/coupons/${item.id}/edit`} className="inline-flex items-center gap-1 text-xs font-extrabold text-brand">
                <Pencil className="h-3.5 w-3.5" />
                编辑
              </Link>
              <Link href={`/admin/coupons/${item.id}/redemptions`} className="inline-flex items-center gap-1 text-xs font-extrabold text-ink">
                <FileText className="h-3.5 w-3.5" />
                记录
              </Link>
              {item.status === 'active'
                ? <button type="button" onClick={() => void updateStatus(item, 'paused')} className="text-xs font-extrabold text-ink">暂停</button>
                : <button type="button" onClick={() => void updateStatus(item, 'active')} className="text-xs font-extrabold text-ink">启用</button>}
              <button type="button" onClick={() => void deleteCoupon(item)} className="inline-flex items-center gap-1 text-xs font-extrabold text-red-600">
                <Trash2 className="h-3.5 w-3.5" />
                删除
              </button>
            </div>
          </div>
        ))}
      </section>
    </AdminShell>
  )
}
