import { Box, Card, SimpleGrid, Skeleton, Stack, Typography } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'

import { useTimeFormatter } from 'dbaas/components/TimeComponent'
import { PageShell } from 'dbaas/layouts/v5/page'
import {
  useGetUserDebugAuthorizationDetail,
  UserDebugAuthorizationDetail,
  useGetUserDebugAuthorizationRecordsForAuth
} from 'dbaas/services'
import { UserDebugAuthorizationRecordItem } from 'dbaas/services/api/interface/userDebugAuthorizationRecordItem'
import useStores from 'dbaas/stores/useStores'
import useQuery from 'dbaas/utils/useQuery'

interface AuthorizationDetailRouteParams {
  id: string
}

const Loading = () => {
  return (
    <Box>
      <Skeleton height={8} mt={6} width="90%" radius="xl" />
      <Skeleton height={8} mt={6} width="70%" radius="xl" />
    </Box>
  )
}

interface Information<D> {
  title: string
  accessorKey: string
  accessorFn?: (data: D) => React.ReactNode
}

const AuthorizationDetail = () => {
  const { id } = useParams<AuthorizationDetailRouteParams>()
  const query = useQuery()
  const cluster_id = query.get('cluster_id')!
  const {
    store: { tenantData }
  } = useStores()
  const { data, isLoading } = useGetUserDebugAuthorizationDetail(tenantData.id, cluster_id, id)
  const formatter = useTimeFormatter()
  const informations: Information<UserDebugAuthorizationDetail>[] = [
    {
      title: 'Project Name',
      accessorKey: 'project_name'
    },
    {
      title: 'Cluster Name',
      accessorKey: 'cluster_name'
    },
    {
      title: 'Authorized Feature',
      accessorKey: 'auth_feature',
      accessorFn: () => 'TiDB Dashboard (Sensitive Data)'
    },
    {
      title: 'Time Limit',
      accessorKey: 'time_limit',
      accessorFn: (data) =>
        !!data?.created_at &&
        !!data?.expires_at && (
          <Box>
            <Typography variant="body-lg">From {formatter(data.created_at)}</Typography>
            <Typography variant="body-lg">To {formatter(data.expires_at)}</Typography>
          </Box>
        )
    },
    {
      title: 'Authorized by',
      accessorKey: 'authed_by',
      accessorFn: (data) => (
        <>
          {data?.authorized_by?.first_name} {data?.authorized_by?.last_name}
        </>
      )
    },
    {
      title: 'Status',
      accessorKey: 'status',
      accessorFn: (data) => (
        <>{data?.status ? data.status.replace(data.status[0], data.status[0].toUpperCase()) : 'Unknown'}</>
      )
    }
  ]

  return (
    <PageShell title="Authorization Detail" headerProps={{ withBack: true }}>
      <Stack>
        <Card>
          <SimpleGrid cols={6}>
            {informations.map((info) => (
              <Stack>
                <Typography variant="title-md">{info.title}</Typography>
                {isLoading ? (
                  <Loading />
                ) : (
                  <Typography variant="body-lg">
                    {info.accessorFn
                      ? info.accessorFn(data!)
                      : (data![info.accessorKey as keyof UserDebugAuthorizationDetail] as string)}
                  </Typography>
                )}
              </Stack>
            ))}
          </SimpleGrid>
        </Card>

        <Typography variant="title-md">Audit Logs</Typography>
        <AuditLogTable />
      </Stack>
    </PageShell>
  )
}

const PER_PAGE_SIZE = 10

const AuditLogTable = () => {
  const { id } = useParams<AuthorizationDetailRouteParams>()
  const query = useQuery()
  const cluster_id = query.get('cluster_id')!
  const {
    store: { tenantData }
  } = useStores()
  const formatter = useTimeFormatter()
  const [page, setPage] = useState(1)
  const { data, isLoading } = useGetUserDebugAuthorizationRecordsForAuth(tenantData.id, cluster_id, id, {
    page,
    per_page: PER_PAGE_SIZE
  })
  const total = Math.ceil((data?.total || 0) / PER_PAGE_SIZE)
  const columns = useMemo<MRT_ColumnDef<UserDebugAuthorizationRecordItem>[]>(
    () => [
      {
        id: 'time',
        header: 'Time',
        accessorFn: (row) => row.created_at && formatter(row.created_at)
      },
      {
        id: 'message',
        header: 'Message',
        accessorFn: (row) =>
          row.user?.first_name || row.user?.last_name
            ? `${row.user?.first_name} ${row.user?.last_name}: ${row.operation}`
            : `TiDB Cloud support: ${row.operation === 'query' ? 'visit TiDB Dashboard' : row.operation}`
      }
    ],
    [formatter]
  )

  return (
    <ProTable
      columns={columns}
      data={data?.items || []}
      loading={isLoading}
      manualPagination={true}
      pagination={
        total > 1
          ? {
              value: page,
              total,
              onChange: setPage
            }
          : undefined
      }
      emptyMessage="No Audit Log."
    />
  )
}

export default observer(AuthorizationDetail)
