import { Button, Group, HoverCard } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'
import { useHistory, useLocation } from 'react-router-dom'

import { AccessGuard } from 'dbaas/contexts/access-control'
import { useAddCreditCard } from 'dbaas/screens/NextGen/my-tidb-creation/shared/use-add-credit-card'
import { MixpanelEvents } from 'dbaas/utils/tracking'

import { ClaimFormValue } from './types'

interface ClaimActionsProps {
  formId: string
  claimId: string
  freeQuotaExhausted?: boolean
  isPending?: boolean
  isLoading?: boolean
}

export const ClaimActions = observer(
  ({ formId, claimId, freeQuotaExhausted = false, isPending, isLoading }: ClaimActionsProps) => {
    const history = useHistory()
    const location = useLocation()
    const { watch } = useFormContext<ClaimFormValue>()
    const orgId = watch('orgId')
    const projectId = watch('projectId')

    const { creditCardNeeded } = useAddCreditCard({
      enabled: freeQuotaExhausted,
      orgId,
      refetchOnWindowFocus: true
    })

    return (
      <>
        <Group mt="xl">
          {!projectId && (
            <HoverCard withArrow withinPortal>
              <HoverCard.Target>
                <span>
                  <Button disabled>Claim</Button>
                </span>
              </HoverCard.Target>
              <HoverCard.Dropdown maw={320}>
                Please ask your admin to grant you permission to claim a Starter instance.
              </HoverCard.Dropdown>
            </HoverCard>
          )}

          {!!projectId && (
            <AccessGuard
              id="TidbxCreateInProject"
              scopeProps={{ orgId: orgId || undefined, projectId }}
              fallback={
                <HoverCard withArrow withinPortal>
                  <HoverCard.Target>
                    <span>
                      <Button disabled>Claim</Button>
                    </span>
                  </HoverCard.Target>
                  <HoverCard.Dropdown maw={320}>
                    Please ask your admin to grant you permission to claim a Starter instance.
                  </HoverCard.Dropdown>
                </HoverCard>
              }
            >
              {!creditCardNeeded && (
                <Button
                  type="submit"
                  form={formId}
                  disabled={isLoading}
                  loading={isPending}
                  data-mp-event={MixpanelEvents.ZeroClaim.Create.SubmitClicked}
                  data-mp-claim-id={claimId}
                  data-mp-source="Zero Claim"
                >
                  Claim
                </Button>
              )}
              {creditCardNeeded && (
                <AccessGuard
                  id="BillingPaymentCreation"
                  scopeProps={{ orgId: orgId || undefined }}
                  fallback={
                    <HoverCard withArrow withinPortal>
                      <HoverCard.Target>
                        <span>
                          <Button disabled>Add Credit Card</Button>
                        </span>
                      </HoverCard.Target>
                      <HoverCard.Dropdown maw={320}>
                        Please contact your Organization Owner or Billing Manager to add a credit card.
                      </HoverCard.Dropdown>
                    </HoverCard>
                  }
                >
                  <Button
                    onClick={() =>
                      window.open(`/org-settings/billing/payments?orgId=${orgId}`, '_blank', 'noopener,noreferrer')
                    }
                    data-mp-event={MixpanelEvents.ZeroClaim.Create.ButtonClicked}
                    data-mp-claim-id={claimId}
                    data-mp-source="Zero Claim"
                  >
                    Add Credit Card
                  </Button>
                </AccessGuard>
              )}
            </AccessGuard>
          )}

          <Button
            variant="default"
            onClick={() => history.push(`/${location.search}`)}
            data-mp-event={MixpanelEvents.ZeroClaim.Create.CancelClicked}
            data-mp-claim-id={claimId}
            data-mp-source="Zero Claim"
          >
            Cancel
          </Button>
        </Group>
      </>
    )
  }
)
