import { Button, Card, Flex, Typography, Grid, notifier } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

import { CopyActionIcon } from 'dbaas/components/Copy/CopyActionIcon'
import TimeComponent from 'dbaas/components/TimeComponent'
import { AccessDeniedHoverHint, useAccessCheck } from 'dbaas/contexts/access-control'
import { PageShell } from 'dbaas/layouts/v5/page'
import { useGetMspCustomer } from 'dbaas/services/account'
import useStores from 'dbaas/stores/useStores'
import { eventTracking, MixpanelEvents } from 'dbaas/utils/tracking'
import { orgNameRules } from 'dbaas/utils/validationRules'

import { Timezone } from './Timezone'

const InfoCard = observer(() => {
  const {
    store: {
      tenantData: { name: orgName, created_at, id },
      config
    },
    actions: { updateOrgName, refreshOrgData, fetchUserProfileV2 }
  } = useStores()

  const [loading, setLoading] = useState(false)

  const { data: mspCustomer } = useGetMspCustomer(id, {
    query: {
      enabled: config.isMSPCustomer
    }
  })

  const onSubmit = async (data: { name: string }) => {
    if (loading) {
      return
    }
    setLoading(true)
    eventTracking(MixpanelEvents.IAMOrganizationName.Update.SubmitClicked)
    try {
      await updateOrgName(data)
    } finally {
      setLoading(false)
    }
    notifier.success('Organization name has been updated successfully.')
    refreshOrgData()
    form.reset({ name: data.name }, { keepDirty: false })
  }

  const form = useForm({
    mode: 'all',
    defaultValues: {
      name: orgName
    }
  })

  const { formState } = form

  const { isDirty } = formState

  const accessible = useAccessCheck('OrgInfoEdit')

  useEffect(() => {
    if (!orgName) {
      fetchUserProfileV2()
        .then((data) => {
          form.setValue('name', data[1].name, { shouldDirty: false })
        })
        .catch(() => {})
    }
  }, [])

  return (
    <Card p={24}>
      <Form form={form} onSubmit={onSubmit} layout="none" withActions={false}>
        <Flex justify="space-between" align="center">
          <div>
            <Typography variant="title-lg">Organization Information</Typography>
            <Typography variant="body-lg" mt={4}>
              Used to identify your organization on TiDB Cloud
            </Typography>
          </div>
          <AccessDeniedHoverHint id="OrgInfoEdit">
            <Button
              variant="default"
              type="submit"
              size="sm"
              loading={loading}
              disabled={!accessible || !isDirty}
              data-mp-event="Organization Name Update Button Clicked"
            >
              Update
            </Button>
          </AccessDeniedHoverHint>
        </Flex>
        <Grid mt={24} columns={config.isMSPCustomer ? 13 : 12}>
          {config.isMSPCustomer && (
            <Grid.Col span={3}>
              <Typography variant="label-lg" fw={600}>
                Managed Service Partner
              </Typography>
              <Typography variant="body-lg" mt={16} sx={{ wordBreak: 'break-all' }}>
                {mspCustomer?.name}
              </Typography>
            </Grid.Col>
          )}
          <Grid.Col span={3}>
            <Typography variant="label-lg">Organization ID</Typography>
            <Flex mt={16} align="center">
              <Typography variant="body-lg" sx={{ wordBreak: 'break-all' }}>
                {id}
              </Typography>
              <CopyActionIcon text={id} actionIconProps={{ size: 28, variant: 'subtle', ml: 4 }}></CopyActionIcon>
            </Flex>
          </Grid.Col>
          <Grid.Col span={3}>
            <Typography variant="label-lg">Creation Time</Typography>
            <Typography variant="body-lg" mt={16}>
              <TimeComponent time={created_at} />
            </Typography>
          </Grid.Col>
          <Grid.Col span={config.isMSPCustomer ? 4 : 6}>
            <FormTextInput
              name="name"
              label="Organization Name"
              placeholder="Org 1"
              required
              disabled={!accessible}
              maxLength={orgNameRules.maxLength.value}
              rules={orgNameRules}
            />
          </Grid.Col>
        </Grid>
      </Form>
    </Card>
  )
})

export const General = () => {
  return (
    <PageShell
      title="General"
      headerProps={{
        sticky: true,
        bg: 'carbon.1'
      }}
      bodyProps={{ pt: 0 }}
    >
      <InfoCard />
      <Timezone />
    </PageShell>
  )
}
