import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  CheckCircle2,
  Eye,
  Loader2,
  PlugZap,
  RefreshCcw,
  RotateCcw,
  SearchIcon,
  XCircle,
} 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 { 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 {
  getThirdPartyConfigStatus,
  listApiCallLogs,
  syncThirdPartyOrderList,
  testThirdPartyConnection,
  type ApiCallLog,
  type ThirdPartyConfigStatus,
} from './api'

const STATUS_ALL = 'all'

function formatJson(value: unknown) {
  if (!value) {
    return '-'
  }

  return JSON.stringify(value, null, 2)
}

function ConfigItem({
  label,
  ok,
  value,
}: {
  label: string
  ok?: boolean
  value: string
}) {
  return (
    <div className='flex min-w-48 items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2'>
      <div>
        <div className='text-xs text-muted-foreground'>{label}</div>
        <div className='text-sm font-medium break-all'>{value}</div>
      </div>
      {typeof ok === 'boolean' ? (
        ok ? (
          <CheckCircle2 className='size-4 text-emerald-600' />
        ) : (
          <XCircle className='size-4 text-destructive' />
        )
      ) : null}
    </div>
  )
}

function ConfigStatusBar({
  status,
}: {
  status?: ThirdPartyConfigStatus
}) {
  return (
    <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-5'>
      <ConfigItem
        label='服务商'
        value={status?.provider || 'biedawo'}
      />
      <ConfigItem
        label='接口地址'
        ok={Boolean(status?.baseUrl)}
        value={status?.baseUrl || '未配置'}
      />
      <ConfigItem
        label='UID'
        ok={Boolean(status?.uidConfigured)}
        value={status?.uidConfigured ? '已配置' : '未配置'}
      />
      <ConfigItem
        label='KEY'
        ok={Boolean(status?.keyConfigured)}
        value={status?.keyConfigured ? '已配置' : '未配置'}
      />
      <ConfigItem
        label='调试日志'
        ok={Boolean(status?.debugLogEnabled)}
        value={status?.debugLogEnabled ? '已开启' : '未开启'}
      />
    </div>
  )
}

function StatusBadge({ status }: { status: ApiCallLog['status'] }) {
  return (
    <Badge variant={status === 'success' ? 'default' : 'destructive'}>
      {status === 'success' ? '成功' : '失败'}
    </Badge>
  )
}

export function ThirdPartySettingsPage() {
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [keywordInput, setKeywordInput] = useState('')
  const [actInput, setActInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [act, setAct] = useState('')
  const [status, setStatus] = useState(STATUS_ALL)
  const [selectedLog, setSelectedLog] = useState<ApiCallLog | null>(null)

  const configQuery = useQuery({
    queryKey: ['third-party-config-status'],
    queryFn: getThirdPartyConfigStatus,
  })
  const logsQuery = useQuery({
    queryKey: ['third-party-api-call-logs', page, pageSize, keyword, act, status],
    queryFn: () =>
      listApiCallLogs({
        page,
        pageSize,
        keyword,
        act,
        status: status === STATUS_ALL ? undefined : status,
      }),
  })
  const testConnectionMutation = useMutation({
    mutationFn: testThirdPartyConnection,
    onSuccess: () => {
      toast.success('第三方接口连接成功')
      void queryClient.invalidateQueries({
        queryKey: ['third-party-api-call-logs'],
      })
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '第三方接口连接失败')),
  })
  const syncThirdPartyOrdersMutation = useMutation({
    mutationFn: () => syncThirdPartyOrderList(),
    onSuccess: (result) => {
      toast.success(
        `第三方订单拉取完成：共 ${result.total} 条，导入订单 ${result.imported} 条，更新本地 ${result.localUpdated} 条`
      )
      void queryClient.invalidateQueries({
        queryKey: ['third-party-api-call-logs'],
      })
      void queryClient.invalidateQueries({ queryKey: ['orders'] })
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '拉取第三方订单列表失败')),
  })

  function handleSearch() {
    setPage(1)
    setKeyword(keywordInput.trim())
    setAct(actInput.trim())
  }

  function handleReset() {
    setPage(1)
    setKeywordInput('')
    setActInput('')
    setKeyword('')
    setAct('')
    setStatus(STATUS_ALL)
  }

  const logs = logsQuery.data?.list ?? []

  return (
    <AdminPage
      title='第三方接口'
      description='检查服务端接口配置、测试连接，并查看第三方调用的脱敏请求与响应。'
      actions={
        <div className='flex flex-wrap items-center gap-2'>
          <Button
            variant='outline'
            onClick={() => syncThirdPartyOrdersMutation.mutate()}
            disabled={syncThirdPartyOrdersMutation.isPending}
          >
            {syncThirdPartyOrdersMutation.isPending ? (
              <Loader2 className='animate-spin' />
            ) : (
              <RefreshCcw />
            )}
            拉取第三方订单
          </Button>
          <Button
            onClick={() => testConnectionMutation.mutate()}
            disabled={testConnectionMutation.isPending}
          >
            {testConnectionMutation.isPending ? (
              <Loader2 className='animate-spin' />
            ) : (
              <PlugZap />
            )}
            测试连接
          </Button>
        </div>
      }
    >
      <div className='flex flex-col gap-4'>
        <ConfigStatusBar status={configQuery.data} />

        <div className='flex flex-wrap items-center gap-2'>
          <Input
            value={keywordInput}
            onChange={(event) => setKeywordInput(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') handleSearch()
            }}
            placeholder='搜索接口、错误或地址'
            className='h-9 w-64'
          />
          <Input
            value={actInput}
            onChange={(event) => setActInput(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') handleSearch()
            }}
            placeholder='act，例如 getcate'
            className='h-9 w-48'
          />
          <Select
            value={status}
            onValueChange={(value) => {
              setPage(1)
              setStatus(value)
            }}
          >
            <SelectTrigger className='h-9 w-32'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={STATUS_ALL}>全部状态</SelectItem>
              <SelectItem value='success'>成功</SelectItem>
              <SelectItem value='failure'>失败</SelectItem>
            </SelectContent>
          </Select>
          <Button variant='outline' onClick={handleSearch}>
            <SearchIcon />
            查询
          </Button>
          <Button variant='ghost' onClick={handleReset}>
            <RotateCcw />
            重置
          </Button>
        </div>

        <div className='overflow-hidden rounded-md border'>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>接口</TableHead>
                <TableHead>服务商</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>HTTP</TableHead>
                <TableHead>耗时</TableHead>
                <TableHead>错误信息</TableHead>
                <TableHead>时间</TableHead>
                <TableHead className='w-24 text-right'>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {logsQuery.isLoading ? (
                <TableRow>
                  <TableCell colSpan={8} className='h-24 text-center'>
                    <Loader2 className='mx-auto animate-spin' />
                  </TableCell>
                </TableRow>
              ) : logs.length ? (
                logs.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell>
                      <Badge variant='outline'>{log.act}</Badge>
                    </TableCell>
                    <TableCell>{log.provider}</TableCell>
                    <TableCell>
                      <StatusBadge status={log.status} />
                    </TableCell>
                    <TableCell>{log.httpStatus ?? '-'}</TableCell>
                    <TableCell>
                      {typeof log.durationMs === 'number'
                        ? `${log.durationMs} ms`
                        : '-'}
                    </TableCell>
                    <TableCell className='max-w-72 truncate'>
                      {log.errorMessage || '-'}
                    </TableCell>
                    <TableCell>{formatDateTime(log.createdAt)}</TableCell>
                    <TableCell className='text-right'>
                      <Button
                        type='button'
                        size='sm'
                        variant='ghost'
                        onClick={() => setSelectedLog(log)}
                      >
                        <Eye />
                        查看
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={8} className='h-24 text-center'>
                    暂无接口调用日志
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        <ListPagination
          page={logsQuery.data?.page ?? page}
          pageSize={logsQuery.data?.pageSize ?? pageSize}
          total={logsQuery.data?.total ?? 0}
          onPageChange={setPage}
          onPageSizeChange={(nextPageSize) => {
            setPage(1)
            setPageSize(nextPageSize)
          }}
        />
      </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'>
                  <ConfigItem label='日志 ID' value={selectedLog.id} />
                  <ConfigItem label='服务商' value={selectedLog.provider} />
                  <ConfigItem label='接口 act' value={selectedLog.act} />
                  <ConfigItem label='请求方法' value={selectedLog.method} />
                  <ConfigItem
                    label='HTTP 状态'
                    value={String(selectedLog.httpStatus ?? '-')}
                  />
                  <ConfigItem
                    label='耗时'
                    value={
                      typeof selectedLog.durationMs === 'number'
                        ? `${selectedLog.durationMs} ms`
                        : '-'
                    }
                  />
                  <ConfigItem
                    label='调用状态'
                    value={selectedLog.status === 'success' ? '成功' : '失败'}
                  />
                  <ConfigItem
                    label='调用时间'
                    value={formatDateTime(selectedLog.createdAt)}
                  />
                </div>
                <div className='grid gap-1'>
                  <div className='text-xs text-muted-foreground'>接口地址</div>
                  <div className='rounded-md border bg-muted/30 px-3 py-2 text-sm break-all'>
                    {selectedLog.url}
                  </div>
                </div>
                <div className='grid gap-1'>
                  <div className='text-xs text-muted-foreground'>错误信息</div>
                  <div className='rounded-md border bg-muted/30 px-3 py-2 text-sm break-all'>
                    {selectedLog.errorMessage || '-'}
                  </div>
                </div>
                <div className='grid gap-2'>
                  <div className='text-xs text-muted-foreground'>请求参数</div>
                  <pre className='max-h-72 overflow-auto rounded-md border bg-muted/30 p-3 font-mono text-xs whitespace-pre-wrap break-words'>
                    {formatJson(selectedLog.requestPayload)}
                  </pre>
                </div>
                <div className='grid gap-2'>
                  <div className='text-xs text-muted-foreground'>响应内容</div>
                  <pre className='max-h-72 overflow-auto rounded-md border bg-muted/30 p-3 font-mono text-xs whitespace-pre-wrap break-words'>
                    {formatJson(selectedLog.responsePayload)}
                  </pre>
                </div>
              </div>
            </ScrollArea>
          )}
        </SheetContent>
      </Sheet>
    </AdminPage>
  )
}
