import { useMemo, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Eye, FileSearch, Loader2, RotateCcw, SearchIcon } from 'lucide-react'
import { toast } from 'sonner'
import { getApiErrorMessage } from '@/lib/api'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { AdminPage } from '@/features/admin/components/admin-page'
import { ListPagination } from '@/features/admin/components/list-pagination'
import { formatDateTime } from '@/features/admin/utils'
import { type ApiCallLog } from '@/features/third-party/api'
import {
  listOrderLogHistory,
  queryOrderLog,
  type OrderLogQueryResult,
  type OrderLogType,
} from './api'

const FILTER_ALL = 'all'

const logTypeLabels: Record<OrderLogType, string> = {
  normal: '普通日志',
  zhs: 'zhs 明细',
  yjy: '易教育记录',
  stream: 'Stream 日志',
}

function formatJson(value: unknown) {
  if (value === undefined || value === null || value === '') return '-'
  if (typeof value === 'string') return value
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

function statusVariant(status: ApiCallLog['status']) {
  return status === 'success' ? 'default' : 'destructive'
}

function getHistoryType(act: string): OrderLogType | null {
  if (act === 'cha_logwk') return 'normal'
  if (act === 'cha_log') return 'zhs'
  if (act === 'get_yjy_study_log') return 'yjy'
  if (act === 'streamLogs') return 'stream'
  return null
}

function getHistoryOrderId(log: ApiCallLog) {
  const value = log.requestPayload?.id
  return value === undefined || value === null ? '-' : String(value)
}

export function OrderLogsPage() {
  const queryClient = useQueryClient()
  const [orderIdInput, setOrderIdInput] = useState('')
  const [type, setType] = useState<OrderLogType>('normal')
  const [result, setResult] = useState<OrderLogQueryResult | null>(null)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [historyOrderInput, setHistoryOrderInput] = useState('')
  const [historyOrderId, setHistoryOrderId] = useState('')
  const [historyType, setHistoryType] = useState(FILTER_ALL)
  const [historyStatus, setHistoryStatus] = useState(FILTER_ALL)
  const [selectedLog, setSelectedLog] = useState<ApiCallLog | null>(null)

  const historyQuery = useQuery({
    queryKey: [
      'order-log-history',
      page,
      pageSize,
      historyOrderId,
      historyType,
      historyStatus,
    ],
    queryFn: () =>
      listOrderLogHistory({
        page,
        pageSize,
        orderId: historyOrderId || undefined,
        type: historyType === FILTER_ALL ? undefined : historyType,
        status: historyStatus === FILTER_ALL ? undefined : historyStatus,
      }),
  })

  const queryMutation = useMutation({
    mutationFn: queryOrderLog,
    onSuccess: (data) => {
      setResult(data)
      toast.success('日志查询完成')
      void queryClient.invalidateQueries({ queryKey: ['order-log-history'] })
    },
    onError: (error) => toast.error(getApiErrorMessage(error, '日志查询失败')),
  })

  function handleQuery() {
    const nextOrderId = orderIdInput.trim()
    if (!nextOrderId) {
      toast.error('请填写第三方订单 ID')
      return
    }
    queryMutation.mutate({ orderId: nextOrderId, type })
  }

  function handleHistorySearch() {
    setPage(1)
    setHistoryOrderId(historyOrderInput.trim())
  }

  function handleHistoryReset() {
    setPage(1)
    setHistoryOrderInput('')
    setHistoryOrderId('')
    setHistoryType(FILTER_ALL)
    setHistoryStatus(FILTER_ALL)
  }

  const history = historyQuery.data?.list ?? []
  const entries = result?.entries ?? []
  const resultSummary = useMemo(() => {
    if (!result) return null
    return [
      { label: '日志类型', value: logTypeLabels[result.type] },
      { label: '第三方动作', value: result.act },
      { label: '订单 ID', value: result.orderId },
      { label: '查询时间', value: formatDateTime(result.queriedAt) },
    ]
  }, [result])

  return (
    <AdminPage
      title='日志查询'
      description='查询第三方订单学习日志、Stream 日志，并沉淀日志查询历史。'
    >
      <div className='grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]'>
        <section className='space-y-4'>
          <div className='rounded-md border p-4'>
            <div className='flex flex-wrap items-end gap-3'>
              <div className='grid gap-2'>
                <Label>第三方订单 ID</Label>
                <Input
                  value={orderIdInput}
                  className='h-9 w-72'
                  placeholder='请输入第三方订单 ID'
                  onChange={(event) => setOrderIdInput(event.target.value)}
                  onKeyDown={(event) => {
                    if (event.key === 'Enter') handleQuery()
                  }}
                />
              </div>
              <div className='grid gap-2'>
                <Label>日志类型</Label>
                <Select
                  value={type}
                  onValueChange={(value) => setType(value as OrderLogType)}
                >
                  <SelectTrigger className='h-9 w-40'>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(logTypeLabels).map(([value, label]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button disabled={queryMutation.isPending} onClick={handleQuery}>
                {queryMutation.isPending ? (
                  <Loader2 className='animate-spin' />
                ) : (
                  <FileSearch />
                )}
                查询日志
              </Button>
            </div>
          </div>

          <div className='rounded-md border'>
            <div className='border-b px-4 py-3'>
              <h3 className='font-medium'>查询结果</h3>
              <p className='text-sm text-muted-foreground'>
                第三方原始响应会保留结构化展示，便于排查异常学习记录。
              </p>
            </div>
            {result ? (
              <div className='space-y-4 p-4'>
                <div className='grid gap-3 sm:grid-cols-2 lg:grid-cols-4'>
                  {resultSummary?.map((item) => (
                    <InfoItem
                      key={item.label}
                      label={item.label}
                      value={item.value}
                    />
                  ))}
                </div>
                <div className='grid gap-4 lg:grid-cols-2'>
                  <PayloadBlock title='日志条目' value={entries} />
                  <PayloadBlock title='原始响应' value={result.response} />
                </div>
              </div>
            ) : (
              <div className='flex h-64 items-center justify-center text-sm text-muted-foreground'>
                输入第三方订单 ID 后查询日志
              </div>
            )}
          </div>
        </section>

        <section className='space-y-4'>
          <div className='rounded-md border'>
            <div className='border-b px-4 py-3'>
              <h3 className='font-medium'>查询历史</h3>
              <p className='text-sm text-muted-foreground'>
                来自第三方接口调用日志，可按订单 ID、类型和状态筛选。
              </p>
            </div>
            <div className='space-y-3 p-4'>
              <div className='flex flex-wrap items-center gap-2'>
                <Input
                  value={historyOrderInput}
                  placeholder='筛选订单 ID'
                  className='h-9 w-40'
                  onChange={(event) =>
                    setHistoryOrderInput(event.target.value)
                  }
                  onKeyDown={(event) => {
                    if (event.key === 'Enter') handleHistorySearch()
                  }}
                />
                <Select
                  value={historyType}
                  onValueChange={(value) => {
                    setPage(1)
                    setHistoryType(value)
                  }}
                >
                  <SelectTrigger className='h-9 w-36'>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={FILTER_ALL}>全部类型</SelectItem>
                    {Object.entries(logTypeLabels).map(([value, label]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Select
                  value={historyStatus}
                  onValueChange={(value) => {
                    setPage(1)
                    setHistoryStatus(value)
                  }}
                >
                  <SelectTrigger className='h-9 w-32'>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={FILTER_ALL}>全部状态</SelectItem>
                    <SelectItem value='success'>成功</SelectItem>
                    <SelectItem value='failure'>失败</SelectItem>
                  </SelectContent>
                </Select>
                <Button variant='outline' onClick={handleHistorySearch}>
                  <SearchIcon />
                  查询
                </Button>
                <Button variant='ghost' onClick={handleHistoryReset}>
                  <RotateCcw />
                  重置
                </Button>
              </div>

              <div className='overflow-auto rounded-md border'>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>类型</TableHead>
                      <TableHead>订单 ID</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>时间</TableHead>
                      <TableHead className='w-20 text-right'>操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {historyQuery.isLoading ? (
                      <TableRow>
                        <TableCell colSpan={5} className='h-24 text-center'>
                          <Loader2 className='mx-auto animate-spin' />
                        </TableCell>
                      </TableRow>
                    ) : history.length ? (
                      history.map((log) => {
                        const logType = getHistoryType(log.act)
                        return (
                          <TableRow key={log.id}>
                            <TableCell>
                              {logType ? logTypeLabels[logType] : log.act}
                            </TableCell>
                            <TableCell className='max-w-28 truncate'>
                              {getHistoryOrderId(log)}
                            </TableCell>
                            <TableCell>
                              <Badge variant={statusVariant(log.status)}>
                                {log.status === 'success' ? '成功' : '失败'}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              {formatDateTime(log.createdAt)}
                            </TableCell>
                            <TableCell className='text-right'>
                              <Button
                                size='sm'
                                variant='ghost'
                                onClick={() => setSelectedLog(log)}
                              >
                                <Eye />
                              </Button>
                            </TableCell>
                          </TableRow>
                        )
                      })
                    ) : (
                      <TableRow>
                        <TableCell colSpan={5} className='h-24 text-center'>
                          暂无查询历史
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>

              <ListPagination
                page={historyQuery.data?.page ?? page}
                pageSize={historyQuery.data?.pageSize ?? pageSize}
                total={historyQuery.data?.total ?? 0}
                onPageChange={setPage}
                onPageSizeChange={(nextPageSize) => {
                  setPage(1)
                  setPageSize(nextPageSize)
                }}
              />
            </div>
          </div>
        </section>
      </div>

      <Sheet
        open={!!selectedLog}
        onOpenChange={(open) => {
          if (!open) setSelectedLog(null)
        }}
      >
        <SheetContent className='flex w-full flex-col gap-0 sm:max-w-2xl'>
          <SheetHeader className='border-b text-start'>
            <SheetTitle>日志历史详情</SheetTitle>
            <SheetDescription>
              查看本次第三方日志请求、响应和错误信息。
            </SheetDescription>
          </SheetHeader>
          {selectedLog && (
            <ScrollArea className='flex-1'>
              <div className='space-y-5 px-4 py-4'>
                <div className='grid gap-3 sm:grid-cols-2'>
                  <InfoItem label='日志 ID' value={selectedLog.id} />
                  <InfoItem label='第三方动作' value={selectedLog.act} />
                  <InfoItem label='请求方式' value={selectedLog.method} />
                  <InfoItem
                    label='状态'
                    value={selectedLog.status === 'success' ? '成功' : '失败'}
                  />
                  <InfoItem
                    label='HTTP 状态'
                    value={
                      selectedLog.httpStatus === null
                        ? '-'
                        : String(selectedLog.httpStatus)
                    }
                  />
                  <InfoItem
                    label='耗时'
                    value={
                      selectedLog.durationMs === null
                        ? '-'
                        : `${selectedLog.durationMs}ms`
                    }
                  />
                  <InfoItem
                    label='订单 ID'
                    value={getHistoryOrderId(selectedLog)}
                  />
                  <InfoItem
                    label='创建时间'
                    value={formatDateTime(selectedLog.createdAt)}
                  />
                </div>
                <InfoItem label='错误信息' value={selectedLog.errorMessage} />
                <PayloadBlock
                  title='请求摘要'
                  value={selectedLog.requestPayload}
                />
                <PayloadBlock
                  title='响应摘要'
                  value={selectedLog.responsePayload}
                />
              </div>
            </ScrollArea>
          )}
        </SheetContent>
      </Sheet>
    </AdminPage>
  )
}

function InfoItem({
  label,
  value,
}: {
  label: string
  value?: string | null
}) {
  return (
    <div className='grid gap-1'>
      <div className='text-xs text-muted-foreground'>{label}</div>
      <div className='min-h-8 rounded-md border bg-muted/30 px-3 py-2 text-sm break-all'>
        {value || '-'}
      </div>
    </div>
  )
}

function PayloadBlock({ title, value }: { title: string; value: unknown }) {
  return (
    <div className='grid gap-1'>
      <div className='text-xs text-muted-foreground'>{title}</div>
      <pre className='max-h-[420px] overflow-auto rounded-md border bg-muted/30 p-3 font-mono text-xs whitespace-pre-wrap break-all'>
        {formatJson(value)}
      </pre>
    </div>
  )
}
