import {
  Alert,
  Button,
  Card,
  Code,
  Group,
  Modal,
  Select,
  SimpleGrid,
  Stack,
  Switch,
  Textarea,
  TextInput,
  Typography
} from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { IconFileSearch02 } from '@tidbcloud/uikit/icons'
import { useCallback, useEffect, useMemo, useState } from 'react'

import {
  cloudConfigControllerImportVersions,
  cloudConfigControllerListAvailableClusterVersions,
  cloudConfigControllerListAvailableComponentVersions,
  cloudConfigControllerListComponentImageUpdateRecords,
  cloudConfigControllerListComponents,
  cloudConfigControllerListDefaultVersionRules,
  cloudConfigControllerUpdateVersion
} from 'apiClient/services/devops'
import {
  CloudConfigControllerListComponentImageUpdateRecordsClusterType,
  CloudconfigAvailableClusterVersion,
  CloudconfigComponentInfo,
  CloudconfigDefaultVersionRule,
  OperationInstance
} from 'apiClient/services/devops/interface'
import { toLocal } from 'pages/Devops/Maintenance/Detail'
import { getErrorMessage } from 'utils/error'

import ReleaseTable from './ReleaseTable'

type VersionView = 'premium' | 'dedicated'

type PremiumDefaultVersionRule = CloudconfigDefaultVersionRule & {
  base_image?: string
  cluster_type: CloudConfigControllerListComponentImageUpdateRecordsClusterType
  image_tag?: string
  key: string
}

type DefaultVersionFormType = {
  default_version: string
}

type SyncVersionsFormType = {
  gitops_branch: string
  max_version: string
  min_version: string
  reason: string
}

type ConfirmAction =
  | {
      payload: DefaultVersionFormType
      type: 'default'
    }
  | {
      payload: SyncVersionsFormType
      type: 'sync'
    }

type OperationResult = {
  message: string
  operationPath?: string
  status: 'error' | 'success'
  title: string
}

type TablePaginationState = {
  pageIndex: number
  pageSize: number
}

type TablePaginationUpdater =
  | TablePaginationState
  | ((prev: TablePaginationState) => TablePaginationState)

const VERSION_VIEW_OPTIONS: Array<{ label: string; value: VersionView }> = [
  { label: 'Premium', value: 'premium' },
  { label: 'Dedicated', value: 'dedicated' }
]

const DEDICATED_CLUSTER_TYPE = 'DEDICATED_TIDB'
const DEFAULT_RULE_PAGE_SIZE = 10
const PREMIUM_PAGE_SIZE = 30
const PREMIUM_RECORD_PAGE_SIZE = 10
const { LOGICAL_CLUSTER, SHARED_POOL, TICDC_NG } =
  CloudConfigControllerListComponentImageUpdateRecordsClusterType
const PREMIUM_CLUSTER_TYPES = [SHARED_POOL, LOGICAL_CLUSTER, TICDC_NG]
const DEFAULT_SYNC_FORM_VALUES: SyncVersionsFormType = {
  gitops_branch: '3layer-prod',
  max_version: 'v99.99.99',
  min_version: '',
  reason: ''
}

const getImageTag = (
  detail: CloudconfigComponentInfo[] | undefined,
  version: string | undefined
) => {
  if (!version) {
    return undefined
  }

  return detail?.find((item) => item.version === version)?.image_tag
}

const getBaseImage = (
  detail: CloudconfigComponentInfo[] | undefined,
  version: string | undefined
) => {
  if (!version) {
    return undefined
  }

  return detail?.find((item) => item.version === version)?.base_image
}

const getFixedPagination = (
  updaterOrValue: TablePaginationUpdater,
  currentPagination: TablePaginationState,
  pageSize: number
) => {
  const nextPagination =
    typeof updaterOrValue === 'function'
      ? updaterOrValue(currentPagination)
      : updaterOrValue

  return {
    pageIndex: nextPagination.pageIndex,
    pageSize
  }
}

const getTextValue = (value?: string) => {
  if (!value) {
    return <span style={{ color: 'var(--mantine-color-carbon-5)' }}>-</span>
  }

  return (
    <span
      title={value}
      style={{
        maxWidth: 360,
        display: 'inline-block',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap'
      }}
    >
      {value}
    </span>
  )
}

const getCodeValue = (value?: string) => {
  if (!value) {
    return getTextValue(value)
  }

  return (
    <Code
      title={value}
      style={{
        display: 'inline-block',
        maxWidth: 240,
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        verticalAlign: 'middle',
        whiteSpace: 'nowrap'
      }}
    >
      {value}
    </Code>
  )
}

const getWrappedCodeValue = (value?: string) => {
  if (!value) {
    return getTextValue(value)
  }

  return (
    <Code
      title={value}
      style={{
        display: 'inline-block',
        lineHeight: 1.5,
        maxWidth: '100%',
        overflowWrap: 'anywhere',
        verticalAlign: 'middle',
        whiteSpace: 'normal',
        wordBreak: 'break-word'
      }}
    >
      {value}
    </Code>
  )
}

const getStrongTextValue = (value: string) => (
  <span style={{ fontWeight: 600 }}>{value}</span>
)

const getOperationParamValue = (record: OperationInstance, keys: string[]) => {
  for (const key of keys) {
    const value = record.params?.[key] || record.outputs?.[key]

    if (value) {
      return value
    }
  }

  return undefined
}

function VersionReleaseList() {
  const [viewMode, setViewMode] = useState<VersionView>('premium')
  const [modalDefault, setModalDefault] = useState(false)
  const [modalSync, setModalSync] = useState(false)
  const [confirmAction, setConfirmAction] = useState<ConfirmAction | null>(null)
  const [operationSaving, setOperationSaving] = useState(false)
  const [operationResult, setOperationResult] =
    useState<OperationResult | null>(null)
  const [defaultVersion, setDefaultVersion] = useState('')
  const [syncForm, setSyncForm] = useState<SyncVersionsFormType>({
    ...DEFAULT_SYNC_FORM_VALUES
  })
  const [versions, setVersions] = useState<string[]>([])
  const [dedicatedDefaultRules, setDedicatedDefaultRules] = useState<
    CloudconfigDefaultVersionRule[]
  >([])
  const [dedicatedLoading, setDedicatedLoading] = useState(false)
  const [premiumDefaultRules, setPremiumDefaultRules] = useState<
    PremiumDefaultVersionRule[]
  >([])
  const [premiumLoading, setPremiumLoading] = useState(false)
  const [showBaseImage, setShowBaseImage] = useState(false)
  const [dedicatedDefaultRulePagination, setDedicatedDefaultRulePagination] =
    useState<TablePaginationState>({
      pageIndex: 0,
      pageSize: DEFAULT_RULE_PAGE_SIZE
    })
  const [premiumPagination, setPremiumPagination] =
    useState<TablePaginationState>({
      pageIndex: 0,
      pageSize: PREMIUM_PAGE_SIZE
    })
  const [recordModalOpened, setRecordModalOpened] = useState(false)
  const [recordModalComponent, setRecordModalComponent] = useState('')
  const [recordModalClusterType, setRecordModalClusterType] =
    useState<CloudConfigControllerListComponentImageUpdateRecordsClusterType>(
      SHARED_POOL
    )
  const [recordRows, setRecordRows] = useState<OperationInstance[]>([])
  const [recordTotal, setRecordTotal] = useState(0)
  const [recordLoading, setRecordLoading] = useState(false)
  const [recordError, setRecordError] = useState<unknown>(null)
  const [recordPagination, setRecordPagination] =
    useState<TablePaginationState>({
      pageIndex: 0,
      pageSize: PREMIUM_RECORD_PAGE_SIZE
    })

  const fetchDedicated = useCallback(async () => {
    try {
      setDedicatedLoading(true)
      const [versionsResp, defaultRulesList] = await Promise.all([
        cloudConfigControllerListAvailableClusterVersions(
          DEDICATED_CLUSTER_TYPE
        ),
        cloudConfigControllerListDefaultVersionRules({
          cluster_type: DEDICATED_CLUSTER_TYPE
        })
      ])

      setVersions(
        (versionsResp.data.items || []).map(
          (version: CloudconfigAvailableClusterVersion) => version.version!
        )
      )
      setDedicatedDefaultRules(defaultRulesList.data.rules || [])
    } catch (e) {
      console.error(e)
    } finally {
      setDedicatedLoading(false)
    }
  }, [])

  const fetchPremium = useCallback(async () => {
    try {
      setPremiumLoading(true)
      const componentRulesByClusterType = await Promise.all(
        PREMIUM_CLUSTER_TYPES.map(async (clusterType) => {
          const [componentsResp, defaultRulesList] = await Promise.all([
            cloudConfigControllerListComponents({
              cluster_type: clusterType
            }),
            cloudConfigControllerListDefaultVersionRules({
              cluster_type: clusterType
            })
          ])
          const components = (componentsResp.data.components || []).filter(
            (component) =>
              clusterType !== LOGICAL_CLUSTER ||
              (component !== 'tidb' && component !== 'tiproxy')
          )
          const defaultRules = defaultRulesList.data.rules || []
          const ruleByComponent = new Map<
            string,
            CloudconfigDefaultVersionRule
          >()
          const defaultRule = defaultRules.find((rule) => !rule.component)

          defaultRules.forEach((rule) => {
            if (rule.component && !ruleByComponent.has(rule.component)) {
              ruleByComponent.set(rule.component, rule)
            }
          })

          return components.map((component) => ({
            clusterType,
            component,
            rule: ruleByComponent.get(component) || defaultRule
          }))
        })
      )
      const componentRules = componentRulesByClusterType.flat()
      const componentVersionResults = await Promise.allSettled(
        componentRules
          .filter(({ rule }) => !!rule?.version)
          .map(async ({ clusterType, component, rule }) => {
            const versionsResp =
              await cloudConfigControllerListAvailableComponentVersions(
                component,
                {
                  cluster_type: clusterType
                }
              )

            return {
              clusterType,
              component,
              detail: versionsResp.data.detail,
              rule
            }
          })
      )
      const imageTagByComponent = new Map<string, string | undefined>()
      const baseImageByComponent = new Map<string, string | undefined>()

      componentVersionResults.forEach((result) => {
        if (result.status !== 'fulfilled') {
          return
        }

        const key = `${result.value.clusterType}:${result.value.component}`
        imageTagByComponent.set(
          key,
          getImageTag(result.value.detail, result.value.rule?.version)
        )
        baseImageByComponent.set(
          key,
          getBaseImage(result.value.detail, result.value.rule?.version)
        )
      })

      setPremiumDefaultRules(
        componentRules.map(({ clusterType, component, rule }) => {
          const key = `${clusterType}:${component}`

          return {
            ...rule,
            base_image: baseImageByComponent.get(key),
            cluster_type: clusterType,
            component,
            image_tag: imageTagByComponent.get(key),
            key
          }
        })
      )
    } catch (e) {
      console.error(e)
    } finally {
      setPremiumLoading(false)
    }
  }, [])

  useEffect(() => {
    if (viewMode === 'premium') {
      fetchPremium()
      return
    }

    fetchDedicated()
  }, [fetchDedicated, fetchPremium, viewMode])

  useEffect(() => {
    setDedicatedDefaultRulePagination({
      pageIndex: 0,
      pageSize: DEFAULT_RULE_PAGE_SIZE
    })
  }, [dedicatedDefaultRules.length])

  useEffect(() => {
    setPremiumPagination({
      pageIndex: 0,
      pageSize: PREMIUM_PAGE_SIZE
    })
  }, [premiumDefaultRules.length])

  const handleConfirmAction = async () => {
    if (!confirmAction) {
      return
    }

    setOperationSaving(true)

    try {
      if (confirmAction.type === 'default') {
        const instance = (
          await cloudConfigControllerUpdateVersion(
            DEDICATED_CLUSTER_TYPE,
            confirmAction.payload.default_version,
            { is_default: true }
          )
        ).data.instance_id

        setOperationResult({
          message:
            'Successfully submit the request to update the default version.',
          operationPath: instance ? `/operations/${instance}` : undefined,
          status: 'success',
          title: 'Default version request submitted'
        })
        fetchDedicated()
        setModalDefault(false)
      } else {
        const instance = (
          await cloudConfigControllerImportVersions({
            gitops_branch: confirmAction.payload.gitops_branch,
            min_version: confirmAction.payload.min_version,
            max_version: confirmAction.payload.max_version,
            tier_branch: confirmAction.payload.reason,
            reason: confirmAction.payload.reason
          })
        ).data.instance_id

        setOperationResult({
          message:
            'Successfully submit the request to sync versions from gitops.',
          operationPath: instance ? `/operations/${instance}` : undefined,
          status: 'success',
          title: 'Sync request submitted'
        })
        setModalSync(false)
      }

      setConfirmAction(null)
    } catch (error) {
      setOperationResult({
        message: getErrorMessage(error),
        status: 'error',
        title: 'Request failed'
      })
      setConfirmAction(null)
    } finally {
      setOperationSaving(false)
    }
  }

  const fetchPremiumRecords = useCallback(
    async (
      component: string,
      clusterType: CloudConfigControllerListComponentImageUpdateRecordsClusterType,
      paginationState: TablePaginationState
    ) => {
      setRecordLoading(true)
      setRecordError(null)

      try {
        const response =
          await cloudConfigControllerListComponentImageUpdateRecords(
            component,
            {
              cluster_type: clusterType,
              page: paginationState.pageIndex + 1,
              per_page: paginationState.pageSize
            }
          )

        setRecordRows(response.data.items || [])
        setRecordTotal(response.data.total || 0)
      } catch (error) {
        setRecordRows([])
        setRecordTotal(0)
        setRecordError(error)
      } finally {
        setRecordLoading(false)
      }
    },
    []
  )

  const handleOpenPremiumRecords = useCallback(
    (record: PremiumDefaultVersionRule) => {
      const { cluster_type: clusterType, component } = record

      if (!component) {
        return
      }

      const nextPagination = {
        pageIndex: 0,
        pageSize: PREMIUM_RECORD_PAGE_SIZE
      }

      setRecordModalComponent(component)
      setRecordModalClusterType(clusterType)
      setRecordPagination(nextPagination)
      setRecordModalOpened(true)
      void fetchPremiumRecords(component, clusterType, nextPagination)
    },
    [fetchPremiumRecords]
  )

  const handleRecordPaginationChange = useCallback(
    (updaterOrValue: TablePaginationUpdater) => {
      if (!recordModalComponent) {
        return
      }

      setRecordPagination((currentPagination) => {
        const nextPagination = getFixedPagination(
          updaterOrValue,
          currentPagination,
          PREMIUM_RECORD_PAGE_SIZE
        )

        if (nextPagination.pageIndex !== currentPagination.pageIndex) {
          void fetchPremiumRecords(
            recordModalComponent,
            recordModalClusterType,
            nextPagination
          )
        }

        return nextPagination
      })
    },
    [fetchPremiumRecords, recordModalClusterType, recordModalComponent]
  )

  const dedicatedDefaultRuleColumns = useMemo<
    MRT_ColumnDef<CloudconfigDefaultVersionRule>[]
  >(
    () => [
      {
        header: 'Component',
        accessorKey: 'component',
        Cell: ({ row }) => getTextValue(row.original.component)
      },
      {
        header: 'Cloud Region',
        accessorKey: 'region',
        Cell: ({ row }) => {
          if (!row.original.region) {
            return row.original.cloud_provider
              ? getStrongTextValue(`Any ${row.original.cloud_provider} Region`)
              : getStrongTextValue('Any Cloud Region')
          }

          return getTextValue(
            [row.original.cloud_provider, row.original.region]
              .filter(Boolean)
              .join('/')
          )
        }
      },
      {
        header: 'Cluster Version',
        accessorKey: 'cluster_version',
        Cell: ({ row }) =>
          row.original.cluster_version
            ? getTextValue(row.original.cluster_version)
            : getStrongTextValue('Any Cluster Version')
      },
      {
        header: 'Default Component Version',
        accessorKey: 'version',
        Cell: ({ row }) => getCodeValue(row.original.version)
      }
    ],
    []
  )
  const premiumDefaultRuleColumns = useMemo<
    MRT_ColumnDef<PremiumDefaultVersionRule>[]
  >(() => {
    const columns: MRT_ColumnDef<PremiumDefaultVersionRule>[] = [
      {
        header: 'Component',
        accessorKey: 'component',
        Cell: ({ row }) => getTextValue(row.original.component)
      },
      {
        header: 'Default Component Version',
        accessorKey: 'version',
        Cell: ({ row }) => getCodeValue(row.original.version)
      },
      {
        header: 'Image tag',
        accessorKey: 'image_tag',
        Cell: ({ row }) => getCodeValue(row.original.image_tag)
      }
    ]

    if (showBaseImage) {
      columns.push({
        header: 'Base Image',
        accessorKey: 'base_image',
        size: 360,
        Cell: ({ row }) => getWrappedCodeValue(row.original.base_image)
      })
    }

    columns.push({
      header: 'Action',
      id: 'action',
      size: 180,
      Cell: ({ row }) => (
        <Button
          size="sm"
          variant="default"
          leftSection={<IconFileSearch02 size={16} />}
          disabled={!row.original.component}
          onClick={() => handleOpenPremiumRecords(row.original)}
        >
          Update History
        </Button>
      )
    })

    return columns
  }, [handleOpenPremiumRecords, showBaseImage])
  const premiumDefaultRuleColumnOrder = useMemo(
    () =>
      showBaseImage
        ? ['component', 'version', 'image_tag', 'base_image', 'action']
        : ['component', 'version', 'image_tag', 'action'],
    [showBaseImage]
  )
  const recordColumns = useMemo<MRT_ColumnDef<OperationInstance>[]>(
    () => [
      {
        header: 'ID',
        accessorKey: 'id',
        size: 100,
        Cell: ({ row }) =>
          row.original.id ? (
            <Button
              size="sm"
              variant="subtle"
              onClick={() =>
                window.open(`/operations/${row.original.id}`, '_blank')
              }
            >
              {row.original.id}
            </Button>
          ) : (
            getTextValue()
          )
      },
      {
        header: 'Component',
        id: 'component',
        size: 140,
        Cell: ({ row }) =>
          getTextValue(
            getOperationParamValue(row.original, [
              'component',
              'component_name'
            ]) || recordModalComponent
          )
      },
      {
        header: 'Base Image',
        id: 'base_image',
        size: 260,
        Cell: ({ row }) =>
          getCodeValue(
            getOperationParamValue(row.original, ['base_image', 'image_base'])
          )
      },
      {
        header: 'Version',
        id: 'version',
        size: 140,
        Cell: ({ row }) =>
          getCodeValue(
            getOperationParamValue(row.original, [
              'version',
              'component_version'
            ])
          )
      },
      {
        header: 'Tag',
        id: 'tag',
        size: 260,
        Cell: ({ row }) =>
          getCodeValue(
            getOperationParamValue(row.original, [
              'tag',
              'image_tag',
              'to_image_tag'
            ])
          )
      },
      {
        header: 'Phase',
        accessorKey: 'phase',
        size: 140,
        Cell: ({ row }) => getTextValue(row.original.phase)
      },
      {
        header: 'Applicant',
        accessorKey: 'applicant',
        size: 220,
        Cell: ({ row }) => getTextValue(row.original.applicant)
      },
      {
        header: 'Created At',
        accessorKey: 'created_at',
        size: 180,
        Cell: ({ row }) => getTextValue(toLocal(row.original.created_at))
      }
    ],
    [recordModalComponent]
  )

  const shouldPaginatePremium = premiumDefaultRules.length > PREMIUM_PAGE_SIZE
  const shouldPaginateDedicatedRules =
    dedicatedDefaultRules.length > DEFAULT_RULE_PAGE_SIZE

  return (
    <Stack gap="md">
      <Group gap={4}>
        {VERSION_VIEW_OPTIONS.map((option) => {
          const active = viewMode === option.value

          return (
            <Button
              key={option.value}
              variant="subtle"
              size="sm"
              onClick={() => setViewMode(option.value)}
              style={{
                borderBottom: active
                  ? '2px solid var(--mantine-color-peacock-6, #0b6fcb)'
                  : '2px solid transparent',
                borderRadius: 0,
                color: active
                  ? 'var(--mantine-color-carbon-9, #1f2d3d)'
                  : 'var(--mantine-color-carbon-6, #5f6b7a)',
                fontWeight: active ? 600 : 400,
                paddingLeft: 12,
                paddingRight: 12
              }}
            >
              {option.label}
            </Button>
          )
        })}
      </Group>

      <Card withBorder shadow="xs" padding="md" radius="sm">
        <Stack gap="md">
          <Group align="flex-start" justify="space-between">
            <Stack gap={4}>
              <Typography variant="title-md">Default Version Rules</Typography>
              {viewMode === 'premium' && (
                <Typography variant="body-sm" c="carbon.6">
                  Premium uses shared pool, logical cluster, and TiCDC NG
                  default component version rules.
                </Typography>
              )}
            </Stack>
            {viewMode === 'premium' && (
              <Switch
                checked={showBaseImage}
                label="Show base image"
                onChange={(event) =>
                  setShowBaseImage(event.currentTarget.checked)
                }
              />
            )}
          </Group>
          {viewMode === 'premium' ? (
            <ProTable<PremiumDefaultVersionRule>
              columns={premiumDefaultRuleColumns}
              data={premiumDefaultRules}
              enableColumnActions={false}
              enableColumnFilters={false}
              enableDensityToggle={false}
              enableFullScreenToggle={false}
              enableHiding={false}
              enablePagination={shouldPaginatePremium}
              enableSorting={false}
              enableTopToolbar={false}
              getRowId={(row) => row.key}
              loading={premiumLoading}
              onPaginationChange={(updaterOrValue) => {
                setPremiumPagination((currentPagination) =>
                  getFixedPagination(
                    updaterOrValue,
                    currentPagination,
                    PREMIUM_PAGE_SIZE
                  )
                )
              }}
              pagination={{ showRowsPerPage: false }}
              rowCount={
                shouldPaginatePremium ? premiumDefaultRules.length : undefined
              }
              state={{
                columnOrder: premiumDefaultRuleColumnOrder,
                pagination: premiumPagination
              }}
            />
          ) : (
            <ProTable<CloudconfigDefaultVersionRule>
              columns={dedicatedDefaultRuleColumns}
              data={dedicatedDefaultRules}
              enableColumnActions={false}
              enableColumnFilters={false}
              enableDensityToggle={false}
              enableFullScreenToggle={false}
              enableHiding={false}
              enablePagination={shouldPaginateDedicatedRules}
              enableSorting={false}
              enableTopToolbar={false}
              getRowId={(record, rowIndex) =>
                [
                  record.component,
                  record.cloud_provider,
                  record.region,
                  record.cluster_version,
                  record.version,
                  rowIndex
                ].join('|')
              }
              loading={dedicatedLoading}
              onPaginationChange={(updaterOrValue) => {
                setDedicatedDefaultRulePagination((currentPagination) =>
                  getFixedPagination(
                    updaterOrValue,
                    currentPagination,
                    DEFAULT_RULE_PAGE_SIZE
                  )
                )
              }}
              pagination={{ showRowsPerPage: false }}
              rowCount={
                shouldPaginateDedicatedRules
                  ? dedicatedDefaultRules.length
                  : undefined
              }
              state={{ pagination: dedicatedDefaultRulePagination }}
            />
          )}
        </Stack>
      </Card>

      {viewMode === 'dedicated' && (
        <Card withBorder shadow="xs" padding="md" radius="sm">
          <Stack gap="md">
            <Group justify="space-between">
              <Typography variant="title-md">
                Cluster Version Release
              </Typography>
              <Group gap="sm">
                <Button
                  onClick={() => {
                    setDefaultVersion('')
                    setModalDefault(true)
                  }}
                >
                  Set Default Version
                </Button>
                <Button
                  onClick={() => {
                    setSyncForm({ ...DEFAULT_SYNC_FORM_VALUES })
                    setModalSync(true)
                  }}
                >
                  Sync from Gitops
                </Button>
              </Group>
            </Group>
            <ReleaseTable />
          </Stack>
        </Card>
      )}

      <Modal
        opened={recordModalOpened}
        onClose={() => setRecordModalOpened(false)}
        title={`Version Update Records: ${recordModalComponent}`}
        centered
        size="80vw"
      >
        <Stack gap="md">
          {!!recordError && (
            <Alert color="red" variant="light" title="Load records failed">
              {getErrorMessage(recordError)}
            </Alert>
          )}
          <ProTable<OperationInstance>
            columns={recordColumns}
            data={recordRows}
            enableColumnActions={false}
            enableColumnFilters={false}
            enableDensityToggle={false}
            enableFullScreenToggle={false}
            enableHiding={false}
            enablePagination={recordTotal > PREMIUM_RECORD_PAGE_SIZE}
            enableSorting={false}
            enableTopToolbar={false}
            getRowId={(row, rowIndex) => String(row.id || rowIndex)}
            loading={recordLoading}
            manualPagination
            onPaginationChange={(updaterOrValue) => {
              handleRecordPaginationChange(
                updaterOrValue as TablePaginationUpdater
              )
            }}
            pagination={{ showRowsPerPage: false }}
            rowCount={recordTotal}
            state={{ pagination: recordPagination }}
          />
        </Stack>
      </Modal>

      <Modal
        opened={modalDefault}
        onClose={() => setModalDefault(false)}
        title="Set default version"
        centered
      >
        <Stack gap="md">
          <Select
            label="Default Version"
            data={versions.map((version) => ({
              label: version,
              value: version
            }))}
            onChange={(value) => setDefaultVersion(value || '')}
            placeholder="Select default version"
            searchable
            value={defaultVersion}
          />
          <Group justify="flex-end">
            <Button variant="outline" onClick={() => setModalDefault(false)}>
              Cancel
            </Button>
            <Button
              disabled={!defaultVersion}
              onClick={() =>
                setConfirmAction({
                  payload: { default_version: defaultVersion },
                  type: 'default'
                })
              }
            >
              Commit
            </Button>
          </Group>
        </Stack>
      </Modal>

      <Modal
        opened={modalSync}
        onClose={() => setModalSync(false)}
        title="Sync versions from Gitops"
        centered
        size="lg"
      >
        <Stack gap="md">
          <Alert color="blue" variant="light">
            Before performing, please ensure:
            <br />
            1. Modify the configs in the "tidb-configuration" repo
            <br />
            2. Update on the SKU page if necessary
          </Alert>
          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="sm">
            <TextInput
              label="gitops Branch"
              onChange={(event) => {
                const { value } = event.currentTarget

                setSyncForm((current) => ({
                  ...current,
                  gitops_branch: value
                }))
              }}
              value={syncForm.gitops_branch}
            />
            <TextInput
              label="Max Version"
              onChange={(event) => {
                const { value } = event.currentTarget

                setSyncForm((current) => ({
                  ...current,
                  max_version: value
                }))
              }}
              value={syncForm.max_version}
            />
            <TextInput
              label="Min Version"
              onChange={(event) => {
                const { value } = event.currentTarget

                setSyncForm((current) => ({
                  ...current,
                  min_version: value
                }))
              }}
              value={syncForm.min_version}
            />
          </SimpleGrid>
          <Textarea
            autosize
            label="Reason"
            minRows={3}
            onChange={(event) => {
              const { value } = event.currentTarget

              setSyncForm((current) => ({
                ...current,
                reason: value
              }))
            }}
            value={syncForm.reason}
          />
          <Group justify="flex-end">
            <Button variant="outline" onClick={() => setModalSync(false)}>
              Cancel
            </Button>
            <Button
              onClick={() =>
                setConfirmAction({ payload: syncForm, type: 'sync' })
              }
            >
              Sync
            </Button>
          </Group>
        </Stack>
      </Modal>

      <Modal
        opened={!!confirmAction}
        onClose={() => setConfirmAction(null)}
        title="Info"
        centered
      >
        <Stack gap="md">
          <Typography variant="body-md">
            {confirmAction?.type === 'default'
              ? 'Are you sure to update the default version?'
              : 'Are you sure to sync versions from Gitops?'}
          </Typography>
          <Group justify="flex-end">
            <Button
              disabled={operationSaving}
              variant="outline"
              onClick={() => setConfirmAction(null)}
            >
              Cancel
            </Button>
            <Button loading={operationSaving} onClick={handleConfirmAction}>
              Confirm
            </Button>
          </Group>
        </Stack>
      </Modal>

      <Modal
        opened={!!operationResult}
        onClose={() => setOperationResult(null)}
        title={operationResult?.title}
        centered
      >
        <Stack gap="md">
          {operationResult && (
            <Alert
              color={operationResult.status === 'success' ? 'green' : 'red'}
              variant="light"
            >
              {operationResult.message}
              {operationResult.operationPath && (
                <>
                  <br />
                  <br />
                  To check the progress of this operation, please refer to the
                  Detail page.
                </>
              )}
            </Alert>
          )}
          <Group justify="flex-end">
            <Button variant="outline" onClick={() => setOperationResult(null)}>
              Close
            </Button>
            {operationResult?.operationPath && (
              <Button
                onClick={() => {
                  window.open(operationResult.operationPath, '_blank')
                  setOperationResult(null)
                }}
              >
                Open Detail
              </Button>
            )}
          </Group>
        </Stack>
      </Modal>
    </Stack>
  )
}

export default VersionReleaseList
