import {
  Card,
  Button,
  Group,
  Stack,
  SimpleGrid,
  Badge,
  Typography,
  Box,
  Flex,
  HoverCard,
  Modal,
  Divider
} from '@tidbcloud/uikit'
import { Form, FormTextareaInput } from '@tidbcloud/uikit/biz'
import {
  IconMessageChatSquare,
  IconHeartHand,
  IconFile05,
  IconLinkExternal01,
  IconInfoCircle,
  IconSend01
} from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useState } from 'react'

import config from 'config'
import { FormsBindedSupportPlan } from 'dbaas/services'
import { eventTracking } from 'dbaas/utils/tracking'
import Discord from 'media/logo/discord.svg?react'
import Slack from 'media/logo/slack.svg?react'

import { PlanFeatureNames, PlanLevels, PlanTier } from './plans'

type SupportBtnType = 'help' | 'feedback' | 'discord' | 'slack' | 'billing' | 'docs'

interface SupportBtnConfig {
  label: string
  url?: string
  icon?: React.ReactNode
}

const SUPPORT_BUTTON_CONFIG: Record<SupportBtnType, SupportBtnConfig> = {
  help: {
    label: 'PingCAP Help Center',
    url: 'https://tidb.support.pingcap.com/servicedesk/customer/portals',
    icon: <IconLinkExternal01 />
  },
  feedback: {
    label: 'Give us feedback'
  },
  discord: {
    label: 'Discord',
    url: 'https://discord.com/invite/KVRZBR2DrG',
    icon: <Discord />
  },
  slack: {
    label: 'Slack',
    url: 'https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=tidbcloud',
    icon: <Slack />
  },
  billing: {
    label: 'Account / Billing issues',
    url: config.CREATE_TICKET_BASIC_URL,
    icon: <IconLinkExternal01 />
  },
  docs: {
    label: 'Documentation',
    url: 'https://docs.pingcap.com/tidbcloud/',
    icon: <IconLinkExternal01 />
  }
}

const ConfigBtn = ({ type }: { type: SupportBtnType }) => {
  const [opened, setOpened] = useState(false)
  const config = SUPPORT_BUTTON_CONFIG[type]

  const onSubmit = (values: any) => {
    if (!values.comments) {
      return
    }

    eventTracking('Give us feedback Submitted', values)
    setOpened(false)
  }

  return (
    <>
      <Button
        variant="outline"
        size="xs"
        leftSection={config.icon}
        onClick={() => {
          if (config.url === undefined) {
            setOpened(true)
          } else {
            window.open(config.url, '_blank')
          }
        }}
      >
        {config.label}
      </Button>

      <Modal opened={opened} title="Give us feedback" size={480} onClose={() => setOpened(false)}>
        <Typography variant="body-lg">Help us shape the future of our support experience.</Typography>
        <Form onSubmit={onSubmit} withActions={false} layout="none" h="100%">
          <FormTextareaInput
            name="comments"
            label="Leave us a message"
            mt={24}
            minRows={5}
            placeholder="What were you trying to achieve? What stopped you? What was helpful? Any suggestions?..."
            rules={{
              maxLength: {
                value: 1000,
                message: 'The maximum number of characters is 1000.'
              },
              minLength: {
                value: 0,
                message: 'The minimum number of characters is 0.'
              }
            }}
          />

          <Divider mt={24} mb={16} mx={-24} />

          <Form.Actions h="100%" align="center" mt={0} onCancel={() => setOpened(false)} confirmText="Submit" />
        </Form>
      </Modal>
    </>
  )
}

const technicalSupportConfig = {
  icon: IconMessageChatSquare,
  iconColor: 'aqua.8',
  title: 'Get technical support',
  description: 'Get practical help and connect with others building on TiDB Cloud.',
  buttons: [<ConfigBtn type="discord" />, <ConfigBtn type="slack" />]
}

const leaveMessageConfig = {
  icon: IconSend01,
  title: 'Leave us a message.',
  description: 'Help us shape the future of our support experience.',
  buttons: [<ConfigBtn type="feedback" />]
}
const findInstanceAnswersConfig = {
  icon: IconFile05,
  iconColor: 'sky.7',
  title: 'Find instance answers.',
  description: 'Learn how to get started and troubleshoot common issues.',
  buttons: [<ConfigBtn type="docs" />]
}

const talkToAnExpertConfig = {
  icon: IconHeartHand,
  iconColor: 'rosy.7',
  title: 'Talk to an expert.',
  description: 'Get assistance from our support team.',
  buttons: [<ConfigBtn type="help" />]
}

const connectToBuildersConfig = {
  icon: IconMessageChatSquare,
  iconColor: 'aqua.8',
  title: 'Connect with builders.',
  description: 'Get practical help and connect with others building on TiDB Cloud.',
  buttons: [<ConfigBtn type="discord" />, <ConfigBtn type="slack" />]
}

const PLAN_DATA_MAP = {
  [PlanLevels.BASIC]: {
    type: 'Basic',
    title: 'Basic',
    description: [
      'Billing & account support  / Community support  / Documentation and knowledge base  / TiDB AI assistance (tidb.ai)'
    ],
    responseTime: 'Community-based (best effort)',
    cards: [
      technicalSupportConfig,
      {
        icon: IconHeartHand,
        iconColor: 'rosy.7',
        title: 'Account & Billing',
        description: 'Get assistance with billing or account issues.',
        buttons: [<ConfigBtn type="billing" />]
      },
      {
        icon: IconFile05,
        iconColor: 'sky.7',
        title: 'Self-service help',
        description: 'Learn how to get started and troubleshoot common issues.',
        buttons: [<ConfigBtn type="docs" />]
      },
      leaveMessageConfig
    ]
  },
  [PlanLevels.DEVELOPER]: {
    type: 'Developer',
    title: 'Developer',
    description: [
      'Ticket-based technical support / Direct access to support engineers / Development-focused database guidance / Community support'
    ],
    cards: [talkToAnExpertConfig, connectToBuildersConfig, findInstanceAnswersConfig, leaveMessageConfig]
  },
  [PlanLevels.ENTERPRISE]: {
    type: 'Enterprise',
    title: 'Enterprise',
    description: [
      'Priority technical support tickets / IM notifications and ticket updates / Production monitoring guidance / Immediate handling for critical incidents'
    ],
    cards: [talkToAnExpertConfig, connectToBuildersConfig, findInstanceAnswersConfig, leaveMessageConfig]
  },
  [PlanLevels.PREMIUM]: {
    type: 'Premium',
    title: 'Premium',
    description: [
      'Fastest response times / Proactive support and escalation / Dedicated Technical Account Manager / IM-based ticket creation and interaction'
    ],
    cards: [talkToAnExpertConfig, connectToBuildersConfig, findInstanceAnswersConfig, leaveMessageConfig]
  }
}

const FeatureCard = ({ icon: Icon, iconColor = 'carbon.9', title, description, buttons, bg }) => (
  <Card padding="lg" bg={bg} radius="md" withBorder sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
    <Icon c={iconColor} size={24} />

    <Typography variant="title-lg" mb={4} mt={16}>
      {title}
    </Typography>
    <Typography variant="body-lg">{description}</Typography>

    <Group gap="xs" mt="xl">
      {buttons.map((btn) => (
        <>{btn}</>
      ))}
    </Group>
  </Card>
)

const PriceDetail: React.FC<React.PropsWithChildren<{ plan: PlanTier }>> = ({ plan }) => {
  const PriceItem = <Typography variant="title-lg">{plan.price}</Typography>

  return (
    <Group gap={4} align="center">
      {plan.level === PlanLevels.PREMIUM ? (
        <Typography variant="label-lg">Contact sales to learn more about Pricing</Typography>
      ) : (
        <>
          <Typography variant="body-lg" c="carbon.9" ta="left">
            {plan.subtitle}
          </Typography>
          <Flex align="flex-end">
            {plan.withoutUnit ? (
              PriceItem
            ) : (
              <>
                <Typography variant="title-lg">$</Typography>
                {PriceItem}
                <Typography variant="title-lg" fw={400} mx={4}>
                  /
                </Typography>
                <Typography variant="title-lg" fw={400}>
                  month
                </Typography>
                <Typography variant="title-lg" fw={400} mx={4}>
                  / org
                </Typography>
              </>
            )}
          </Flex>
        </>
      )}
      {plan.pricingTips && (
        <HoverCard width={320} position="top-end" withArrow={false}>
          <HoverCard.Target>
            <IconInfoCircle size={16} sx={{ cursor: 'pointer' }} />
          </HoverCard.Target>
          <HoverCard.Dropdown>{plan.pricingTips}</HoverCard.Dropdown>
        </HoverCard>
      )}
    </Group>
  )
}

export const ActivePlan: React.FC<
  React.PropsWithChildren<{
    bindedPlan: FormsBindedSupportPlan
    planTier: PlanTier
  }>
> = observer(({ bindedPlan, planTier }) => {
  const plan = PLAN_DATA_MAP[bindedPlan.level ?? PlanLevels.BASIC]
  const responseTimeTitle = PlanFeatureNames.INITIAL_RESPONSE_TIME
  const responseTimeFeatures = planTier.features.find((feat) => feat.title === responseTimeTitle)?.features ?? []

  return (
    <Stack gap={24}>
      <Box>
        <Group justify="space-between" align="center">
          <Group>
            <Typography variant="headline-lg">{planTier.title}</Typography>
            <Badge color="carbon.7" variant="outline" size="sm">
              current support plan
            </Badge>
          </Group>

          <PriceDetail plan={planTier} />
        </Group>

        <Group gap={4} align="center" mt={8}>
          <Typography variant="label-lg">Includes:</Typography>
          {plan.description.map((line, index) => (
            <Typography variant="body-lg" key={index}>
              {line}
            </Typography>
          ))}
        </Group>

        <Group gap={2}>
          <Typography variant="label-lg">Response Time:</Typography>
          <Typography ml={4}>
            {responseTimeFeatures.length === 0 ? (plan?.responseTime ?? '') : responseTimeFeatures.join(' / ')}
          </Typography>
        </Group>
      </Box>

      <SimpleGrid cols={4} spacing={8}>
        {plan.cards.map((card, index) => (
          <FeatureCard key={index} {...card} bg={index === plan.cards.length - 1 ? '' : 'carbon.2'} />
        ))}
      </SimpleGrid>
    </Stack>
  )
})
