import { Box, Button, Divider, Group, Stack, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { useMemo } from 'react'
import { useFormContext } from 'react-hook-form'
import { useHistory, useParams } from 'react-router-dom'

import { PropertyKV } from 'dbaas/components'
import { CloudProviderLabelConst } from 'dbaas/features/Project'
import { GetOrgInfoQueryResult } from 'dbaas/services/warehouse'

import { CreateWarehouseRequestBody } from './WarehouseCreate'

interface WarehouseSummaryProps {
  formId: string
  isPending?: boolean
  orgInfo?: GetOrgInfoQueryResult
}

const SumInfoItem = ({ label, value }: { label: string; value: React.ReactNode }) => {
  return (
    <PropertyKV label={label} labelProps={{ w: 144 }}>
      {value}
    </PropertyKV>
  )
}

export const WarehouseSummary = observer(({ formId, isPending, orgInfo }: WarehouseSummaryProps) => {
  const { watch } = useFormContext<CreateWarehouseRequestBody>()
  const { id: warehouseId } = useParams<{ id: string }>()
  const history = useHistory()

  const name = watch('name')
  const autoSuspend = watch('autoSuspend')
  const tags = watch('tags')
  const size = watch('size')
  const parsedSize = useMemo(() => {
    if (!size) return {}
    if (typeof size === 'string') {
      try {
        return JSON.parse(size)
      } catch (_e) {
        return {}
      }
    }
    if (typeof size === 'object') return size
    return {}
  }, [size])

  const parsedTags = useMemo(() => {
    if (!tags) return []
    if (typeof tags === 'string') {
      try {
        const p = JSON.parse(tags)
        if (Array.isArray(p)) return p
        if (p && typeof p === 'object') return Object.entries(p).map(([k, v]) => ({ key: k, value: String(v) }))
        return []
      } catch (_e) {
        return []
      }
    }
    if (Array.isArray(tags)) return tags
    if (tags && typeof tags === 'object') return Object.entries(tags).map(([k, v]) => ({ key: k, value: String(v) }))
    return []
  }, [tags])

  const getSuspendText = (autoSuspend) => {
    if (!autoSuspend) return '-'
    const mins = Number(autoSuspend) / 60
    if (mins && mins < 60) return `${mins} mins`
    if (mins === 60) return `1 hour`
    return 'never'
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <Box>
        <Typography variant="title-lg">Summary</Typography>
        <Typography variant="body-lg" c="carbon.7" mt={4}>
          Your new warehouse will be:
        </Typography>

        <Stack justify="flex-start" gap={16} py="xl">
          <SumInfoItem label="Name" value={!name ? '-' : name} />
          <SumInfoItem
            label="Provider"
            value={CloudProviderLabelConst[orgInfo?.data?.storageInfo?.provider ?? ''] ?? '-'}
          />
          <SumInfoItem label="Region" value={orgInfo?.data?.storageInfo?.regionTitle ?? '-'} />
          <SumInfoItem
            label="Tags"
            value={
              parsedTags.length > 0 ? (
                <Stack gap={4}>
                  {parsedTags.map((t, idx) => (
                    <Typography key={idx} variant="body-md">
                      {t?.key ?? ''}: {t?.value ?? ''}
                    </Typography>
                  ))}
                </Stack>
              ) : (
                '-'
              )
            }
          />
          <Divider />
          <SumInfoItem label="Size" value={parsedSize?.name ?? '-'} />
          <Divider />
          <SumInfoItem label="Auto Suspend" value={getSuspendText(autoSuspend)} />
          <Divider />
        </Stack>
      </Box>
      <Box sx={{ marginTop: 'auto' }}>
        <Group gap={8}>
          <Typography variant="headline-md">
            {parsedSize.creditCurrency}
            {parsedSize.creditCostPerHour}
          </Typography>{' '}
          /hour
        </Group>
        <Typography variant="body-lg">No upfront charges. Pay only for your actual usage.</Typography>

        <Group justify="space-between" pt="lg">
          <Button variant="default" onClick={() => history.push('/lakes')}>
            Cancel
          </Button>
          <Button type="submit" form={formId} disabled={isPending || !name} loading={isPending} sx={{ flexGrow: 1 }}>
            {warehouseId ? 'Update' : 'Create'}
          </Button>
        </Group>
      </Box>
    </Box>
  )
})
