import { Box, Loader, Center, Modal } from '@tidbcloud/uikit'
// import { IconLifeBuoy02, IconHome02, IconBookOpen02, IconFilePlus02 } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'

// import config from 'config'
import { useAccessCheck } from 'dbaas/contexts/access-control'
import { FormsSupportPlan, useGetPublicSupportPlan, useGetTenantSupportPlan } from 'dbaas/services'
import { useListBindedSupportPlan } from 'dbaas/services/billing'
import { FormsBindedSupportPlan } from 'dbaas/services/billing/interface'
import useStores from 'dbaas/stores/useStores'
import { AccountProviders } from 'dbaas/utils/marketplace'
// import { replaceURLByCurrentDomain } from 'dbaas/utils/useInterceptDocLinks'

import { PlansComparison } from './Plans'
import { SupportAlerts } from './Plans/Alerts'
import { PlanLevels, PlanTier, useOpenPurchase, usePlanTiers } from './Plans/plans'
import { Purchase } from './Purchase'

const SupportPlans = ({
  plan,
  planTiers,
  plansMap,
  orgId
}: {
  plan: FormsBindedSupportPlan
  planTiers: PlanTier[]
  plansMap: Record<string, FormsSupportPlan>
  orgId: string
}) => {
  return (
    <Box>
      <SupportAlerts orgId={orgId} />
      <PlansComparison planTiers={planTiers} plansMap={plansMap} bindedPlan={plan} />
    </Box>
  )
}

export const SupportHome = observer(({ opened = false, onClose }: { opened?: boolean; onClose: () => void }) => {
  const {
    store: {
      tenantData,
      config: { isMSPCustomer }
    }
  } = useStores()
  const { data: plans = [] } = useGetPublicSupportPlan()

  const { data: bindedPlan = { level: PlanLevels.BASIC }, refetch, isFetched } = useGetTenantSupportPlan(tenantData.id)

  const { data: bindedPlanDetails } = useListBindedSupportPlan(tenantData.id, {
    query: {
      refetchInterval: false
    }
  })

  const plansMap = plans
    ?.filter((pl) => {
      // now, only show developer / enterprise plan price
      return pl.level === PlanLevels.DEVELOPER || pl.level === PlanLevels.ENTERPRISE
    })
    .reduce(
      (prev, next) => {
        prev[next.level || ''] = next
        return prev
      },
      { [PlanLevels.BASIC]: { level: PlanLevels.BASIC } }
    )
  const { purchaseParams, openPurchase, closePurchase } = useOpenPurchase()

  const alicloudDisabled =
    tenantData.third_party_account_provider === AccountProviders.alicloud &&
    bindedPlan.level === PlanLevels.ENTERPRISE &&
    !bindedPlan.public

  const planTiers = usePlanTiers(bindedPlan, plansMap, {
    isMSPCustomer,
    eligibleForFreeTrial: bindedPlanDetails?.is_eligible_for_free_trial,
    onPurchaseClick: openPurchase,
    disabled: alicloudDisabled,
    titleTips: alicloudDisabled
      ? {
          [PlanLevels.ENTERPRISE]:
            'Customers subscribed through the Alibaba Cloud Marketplace are automatically enrolled in the Enterprise support plan.'
        }
      : undefined
  })

  const actionEnabled = useAccessCheck('BillingPaymentCreation') && !isMSPCustomer && !alicloudDisabled

  const onComplete = () => {
    closePurchase()
    refetch()
  }

  return (
    <Modal
      title="Support"
      opened={opened}
      onClose={onClose}
      size={1200}
      trapFocus={false}
      withinPortal
      styles={{
        content: { height: 'calc(100dvh - var(--modal-y-offset) * 2)' },
        body: { height: 'calc(100% - 62px)', overflow: 'auto' }
      }}
    >
      {isFetched ? (
        <>
          <SupportPlans plan={bindedPlan} plansMap={plansMap} planTiers={planTiers} orgId={tenantData.id} />
          {actionEnabled && (
            <Purchase
              purchaseParams={purchaseParams}
              plansMap={plansMap}
              onComplete={onComplete}
              bindedPlan={bindedPlan}
              planTiers={planTiers}
              eligibleForFreeTrial={bindedPlanDetails?.is_eligible_for_free_trial}
              opened={purchaseParams.opened}
              onClose={closePurchase}
            />
          )}
        </>
      ) : (
        <Center>
          <Loader />
        </Center>
      )}
    </Modal>
  )
})

export default SupportHome
