import { ActionIcon, Anchor, Box, Group, HoverCard, Skeleton, Stack, Typography } from '@tidbcloud/uikit'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'

import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import { toLocalBackupTime } from 'dbaas/screens/Cluster/Backup/utils'
import {
  useTidbServiceGetBackupSetting,
  useTidbServiceListBackupPolicies
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'
import { getUTCString } from 'dbaas/utils/format'
import { MixpanelEvents } from 'dbaas/utils/tracking'

import { getBackupSettingOverview } from './Settings.utils'

interface BackupSettingSummaryProps {
  tidbId: string
  servicePlan: Commonv1beta1ServicePlan
  canChangeSettings: boolean
  onChangeSettings: () => void
}

const modeLabels = {
  STANDARD_BUNDLE: 'Bundled',
  FLEXIBLE_RETENTION: 'Custom'
} as const

export function BackupSettingSummary({
  tidbId,
  servicePlan,
  canChangeSettings,
  onChangeSettings
}: BackupSettingSummaryProps) {
  const isEssentialV2 = servicePlan === 'Essential_V2'
  const { orgId, projectId } = useOrgProjectClusterIds()
  const {
    store: { tenantData }
  } = useStores()
  const { data: backupSetting, isLoading: isLoadingSetting } = useTidbServiceGetBackupSetting(
    tidbId,
    { orgId, projectId },
    {
      query: {
        enabled: !!tidbId && !!orgId && !!projectId,
        refetchOnWindowFocus: false
      }
    }
  )
  const { data: backupPoliciesData, isLoading: isLoadingPolicies } = useTidbServiceListBackupPolicies(
    tidbId,
    { orgId, projectId },
    {
      query: {
        enabled: !isEssentialV2 && !!tidbId && !!orgId && !!projectId && !!backupSetting,
        refetchOnWindowFocus: false
      }
    }
  )
  const policy = backupPoliciesData?.backupPolicies?.find(
    (item) => item.name === (backupSetting?.backupPolicy ?? 'TIER1')
  )
  const effectiveSetting =
    isEssentialV2 && backupSetting ? { ...backupSetting, mode: 'FLEXIBLE_RETENTION' as const } : backupSetting
  const overview = getBackupSettingOverview(effectiveSetting, policy)
  const dailyBackupTime = toLocalBackupTime(overview.dailyBackupTimeUtc, tenantData.timezone)
  const timezone = getUTCString(tenantData.timezone)
  const rules = [
    { label: 'PITR', retentionDays: overview.pitrRetentionDays },
    ...(overview.hourlyRetentionDays ? [{ label: 'Hourly Backup', retentionDays: overview.hourlyRetentionDays }] : []),
    {
      label: 'Daily Backup',
      retentionDays: overview.dailyRetentionDays,
      schedule: `at ${dailyBackupTime} ${timezone}`
    }
  ]

  return (
    <Box data-testid="premium-backup-settings-summary">
      {isLoadingSetting || isLoadingPolicies || !backupSetting ? (
        <Skeleton h={20} w={220} />
      ) : (
        <Group gap={6} wrap="nowrap">
          <Typography variant="body-md" c="carbon.7">
            Auto Backup Mode:
          </Typography>
          <Typography variant="label-md">{modeLabels[overview.mode]}</Typography>
          <HoverCard
            position="bottom-end"
            width={320}
            shadow="md"
            withArrow
            withinPortal
            openDelay={150}
            closeDelay={100}
          >
            <HoverCard.Target>
              <ActionIcon
                variant="subtle"
                size="sm"
                aria-label="View auto backup rules"
                data-testid="premium-backup-settings-summary-details"
                data-mp-event={MixpanelEvents.PremiumBackup.View.ButtonClicked}
              >
                <IconInfoCircle size={16} />
              </ActionIcon>
            </HoverCard.Target>
            <HoverCard.Dropdown data-testid="premium-backup-settings-summary-popover">
              <Stack gap={16}>
                {rules.map((rule) => (
                  <Stack key={rule.label} gap={4}>
                    <Typography variant="label-lg">{rule.label}</Typography>
                    {rule.schedule && <Typography variant="body-md">({rule.schedule})</Typography>}
                    <Typography variant="body-md">
                      Retention{' '}
                      <Typography span fw={600}>
                        {rule.retentionDays}
                      </Typography>{' '}
                      {rule.retentionDays === 1 ? 'day' : 'days'}
                    </Typography>
                  </Stack>
                ))}
                <Anchor
                  component="button"
                  type="button"
                  ta="left"
                  disabled={!canChangeSettings}
                  onClick={onChangeSettings}
                  data-testid="premium-backup-settings-summary-change"
                  data-mp-event={MixpanelEvents.PremiumBackup.Update.ButtonClicked}
                >
                  Change Backup Settings
                </Anchor>
              </Stack>
            </HoverCard.Dropdown>
          </HoverCard>
        </Group>
      )}
    </Box>
  )
}
