import { api } from '@/lib/api'
import { usePaged } from '@/lib/usePaged'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { Pager } from '@/components/Pager'

export default function Feedback() {
  const { page, setPage, data, totalPages, reload } = usePaged<any>(api.feedback)

  async function toggle(f: any) {
    await api.setFeedbackHandled(f.id, !f.handled)
    reload()
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold">意见反馈</h1>
        <p className="text-sm text-muted-foreground mt-1">来自小程序「我的 → 意见反馈」的用户留言。</p>
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>时间</TableHead>
                <TableHead>用户</TableHead>
                <TableHead>内容</TableHead>
                <TableHead>联系方式</TableHead>
                <TableHead>状态</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data?.list?.map((f) => (
                <TableRow key={f.id}>
                  <TableCell className="whitespace-nowrap text-muted-foreground">
                    {String(f.created_at).slice(0, 16).replace('T', ' ')}
                  </TableCell>
                  <TableCell>{f.nickname || '—'}</TableCell>
                  <TableCell className="max-w-md whitespace-pre-wrap">{f.content}</TableCell>
                  <TableCell>{f.contact || '—'}</TableCell>
                  <TableCell>
                    {f.handled ? <Badge variant="success">已处理</Badge> : <Badge variant="muted">待处理</Badge>}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="outline" size="sm" onClick={() => toggle(f)}>
                      {f.handled ? '标为待处理' : '标为已处理'}
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
              {!data?.list?.length && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                    还没有反馈
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
          <Pager page={page} totalPages={totalPages} total={data?.total ?? 0} onChange={setPage} />
        </CardContent>
      </Card>
    </div>
  )
}
