import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Eye, Loader2, RotateCcw, SearchIcon } from 'lucide-react'
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 { type AuditLog, listAuditLogs } from './api'
import { AdminPage } from './components/admin-page'
import { ListPagination } from './components/list-pagination'
import { formatDateTime } from './utils'

const LOGIN_RESULT_ALL = 'all'

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

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

function DetailItem({
  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>
  )
}

export function AdminAuditLogsPage() {
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [actorInput, setActorInput] = useState('')
  const [actionInput, setActionInput] = useState('')
  const [actorUsername, setActorUsername] = useState('')
  const [action, setAction] = useState('')
  const [loginResult, setLoginResult] = useState(LOGIN_RESULT_ALL)
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null)

  const logsQuery = useQuery({
    queryKey: [
      'admin-audit-logs',
      page,
      pageSize,
      actorUsername,
      action,
      loginResult,
    ],
    queryFn: () =>
      listAuditLogs({
        page,
        pageSize,
        actorUsername,
        action,
        loginResult:
          loginResult === LOGIN_RESULT_ALL ? undefined : loginResult,
      }),
  })

  function handleSearch() {
    setPage(1)
    setActorUsername(actorInput.trim())
    setAction(actionInput.trim())
  }

  function handleReset() {
    setPage(1)
    setActorInput('')
    setActionInput('')
    setActorUsername('')
    setAction('')
    setLoginResult(LOGIN_RESULT_ALL)
  }

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

  return (
    <AdminPage
      title='操作日志'
      description='统一记录后台登录、用户管理、角色调整等关键动作，便于追踪责任链路。'
    >
      <div className='flex flex-col gap-4'>
        <div className='flex flex-wrap items-center gap-2'>
          <Input
            value={actorInput}
            onChange={(event) => setActorInput(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') handleSearch()
            }}
            placeholder='搜索操作人'
            className='h-9 w-52'
          />
          <Input
            value={actionInput}
            onChange={(event) => setActionInput(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') handleSearch()
            }}
            placeholder='搜索动作，例如 auth.login'
            className='h-9 w-72'
          />
          <Select
            value={loginResult}
            onValueChange={(value) => {
              setPage(1)
              setLoginResult(value)
            }}
          >
            <SelectTrigger className='h-9 w-36'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={LOGIN_RESULT_ALL}>全部登录</SelectItem>
              <SelectItem value='success'>登录成功</SelectItem>
              <SelectItem value='failed'>登录失败</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>资源 ID</TableHead>
                <TableHead>IP 地址</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 className='font-medium'>
                      {log.actorUsername || '-'}
                    </TableCell>
                    <TableCell>
                      <Badge variant='outline'>{log.action}</Badge>
                    </TableCell>
                    <TableCell>{log.resourceType || '-'}</TableCell>
                    <TableCell className='max-w-48 truncate'>
                      {log.resourceId || '-'}
                    </TableCell>
                    <TableCell>{log.ipAddress || '-'}</TableCell>
                    <TableCell className='max-w-80 truncate font-mono text-xs'>
                      {log.metadata ? JSON.stringify(log.metadata) : '-'}
                    </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-xl'>
          <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'>
                  <DetailItem label='日志 ID' value={selectedLog.id} />
                  <DetailItem
                    label='操作时间'
                    value={formatDateTime(selectedLog.createdAt)}
                  />
                  <DetailItem
                    label='操作人'
                    value={selectedLog.actorUsername}
                  />
                  <DetailItem label='操作人 ID' value={selectedLog.actorId} />
                  <DetailItem label='动作' value={selectedLog.action} />
                  <DetailItem label='IP 地址' value={selectedLog.ipAddress} />
                  <DetailItem
                    label='资源类型'
                    value={selectedLog.resourceType}
                  />
                  <DetailItem label='资源 ID' value={selectedLog.resourceId} />
                </div>

                <div className='grid gap-2'>
                  <div className='text-xs text-muted-foreground'>元数据</div>
                  <pre className='max-h-[46vh] overflow-auto rounded-md border bg-muted/30 p-3 font-mono text-xs whitespace-pre-wrap break-words'>
                    {formatJson(selectedLog.metadata)}
                  </pre>
                </div>
              </div>
            </ScrollArea>
          )}
        </SheetContent>
      </Sheet>
    </AdminPage>
  )
}
