import { Typography, Flex, Select, Alert, Badge, Card, Stack } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { IconAlertTriangle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useMemo, useState } from 'react'

import { getCloudProviderLabel } from 'dbaas/features/Project/profile'
import { useRequestSupport } from 'dbaas/screens/HelpCenter/RequestSupport/helper'
import {
  useRegionServiceListOpsAuditLogSettings,
  useRegionServiceListRegions
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import {
  TidbServiceListTidbsServicePlan,
  V1beta1RegionCloudProvider,
  V1beta2OpsAuditLogSetting
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'

const DEFAULT_PAGE_SIZE = 10
const SILENT_BYOC_QUERY_REQUEST = { isShowToast: false, isHandleErr: false }

export const BYOCOpsAuditLog = observer(({ regionSettingsView = false }: { regionSettingsView?: boolean }) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: DEFAULT_PAGE_SIZE })
  const [params, setParams] = useState<{
    regionId?: string
    status?: string
  }>({
    regionId: '',
    status: undefined
  })
  const { open: openSupport } = useRequestSupport()

  const { data: regionData } = useRegionServiceListRegions(
    {
      orgId,
      projectId,
      servicePlan: TidbServiceListTidbsServicePlan.BYOC,
      pageSize: 100
    },
    {
      query: {
        enabled: !!orgId && !!projectId,
        refetchInterval: 60 * 1000
      },
      request: SILENT_BYOC_QUERY_REQUEST
    }
  )
  const { data: opsAuditLogSettings } = useRegionServiceListOpsAuditLogSettings(
    {
      orgId,
      projectId,
      servicePlan: 'BYOC',
      pageSize: pagination.pageSize,
      skip: pagination.pageIndex * pagination.pageSize,
      regionId: params.regionId,
      status: params.status ? [params.status === 'true'] : undefined
    },
    {
      query: {
        enabled: !!orgId && !!projectId,
        refetchInterval: 60 * 1000
      },
      request: SILENT_BYOC_QUERY_REQUEST
    }
  )
  const columns: MRT_ColumnDef<V1beta2OpsAuditLogSetting>[] = [
    {
      header: 'Region ID',
      size: 100,
      accessorFn(originalRow) {
        return originalRow.region?.displayName || ''
      }
    },
    {
      header: 'Cloud',
      size: 100,
      accessorFn(originalRow) {
        return getCloudProviderLabel(originalRow.region?.cloudProvider || '')
      }
    },
    {
      header: 'Status',
      size: 100,
      accessorKey: 'enabled',
      accessorFn(originalRow) {
        return (
          <Badge color={originalRow.enabled ? 'green' : 'gray'} variant="dot" size="lg" sx={{ pointerEvents: 'none' }}>
            {originalRow.enabled ? 'Enabled' : 'Disabled'}
          </Badge>
        )
      }
    },
    {
      header: 'S3 address',
      accessorFn(originalRow) {
        return originalRow.logLocation?.bucketUri || '-'
      }
    }
  ]

  const regionOptions = useMemo(() => {
    if (!regionData?.regions) {
      return []
    }

    const groupedRegions = regionData.regions.reduce(
      (acc, region) => {
        const provider = region.cloudProvider || region.regionId?.split('-')?.[0]
        if (!provider || !V1beta1RegionCloudProvider[provider]) {
          return acc
        }

        acc[provider] = [
          ...(acc[provider] || []),
          {
            value: region.regionId || '',
            label: region.displayName || ''
          }
        ]

        return acc
      },
      {} as Record<V1beta1RegionCloudProvider, { value: string; label: string }[]>
    )

    return Object.entries(groupedRegions).map(([provider, items]) => ({
      group: getCloudProviderLabel(provider),
      items
    }))
  }, [regionData])

  const table = (
    <ProTable
      columns={columns}
      data={opsAuditLogSettings?.opsAuditLogSettings ?? []}
      mantinePaperProps={{ mt: regionSettingsView ? 0 : 16 }}
      manualPagination={true}
      enablePagination={true}
      state={{ pagination }}
      onPaginationChange={setPagination}
      rowCount={opsAuditLogSettings?.totalSize ?? 0}
      pagination={{
        showRowsPerPage: true,
        showTotal: true
      }}
      data-testid="byoc-region-settings-table"
    />
  )

  if (regionSettingsView) {
    return (
      <Stack pb="xl" data-testid="byoc-region-settings-page">
        <Card withBorder shadow="none" p="xl">
          <Stack gap="xs" mb="lg">
            <Typography variant="title-lg">OPS Audit Logs Settings</Typography>
            <Typography variant="body-lg" c="carbon.7">
              This provides a view-only list of OPS Audit Log storage locations for each BYOC region. Contact the TiDB
              Cloud{' '}
              <Typography variant="body-lg" c="carbon.7" component="span">
                <a onClick={() => openSupport()}>support team</a>
              </Typography>{' '}
              to modify any setting.
            </Typography>
          </Stack>
          {table}
        </Card>
      </Stack>
    )
  }

  return (
    <>
      <Alert icon={<IconAlertTriangle size={14} />} color="yellow">
        This page lists the S3 bucket location of OPS Audit Logs for each BYOC region, and it is read-only for security
        and compliance. To modify any settings, please contact your TiDB Cloud{' '}
        <Typography variant="body-lg" c="carbon.7" component="span">
          <a onClick={() => openSupport()}>support team</a>
        </Typography>
        .
      </Alert>
      <Flex mt={24} gap={8}>
        <Select
          value={params.regionId}
          data={regionOptions}
          placeholder="Region ID"
          clearable={true}
          onChange={(value) => setParams({ ...params, regionId: value || '' })}
        />
        <Select
          value={params.status}
          data={[
            { label: 'Enabled', value: 'true' },
            { label: 'Disabled', value: 'false' }
          ]}
          placeholder="Status"
          clearable={true}
          onChange={(value) => setParams({ ...params, status: value || '' })}
        />
      </Flex>
      {table}
    </>
  )
})

export default BYOCOpsAuditLog
