import { ErrorMessage } from '@hookform/error-message'
import { Autocomplete, AutocompleteProps, Checkbox, TypographyProps, Text, Group, Avatar } from '@tidbcloud/uikit'
import {
  Box,
  BoxProps,
  Center,
  Flex,
  SimpleGrid,
  SimpleGridProps,
  Stack,
  Typography,
  useMantineTheme
} from '@tidbcloud/uikit'
import { IconCheck } from '@tidbcloud/uikit/icons'
import { mergeSxList } from '@tidbcloud/uikit/utils'
import React from 'react'
import { Controller, useFormContext, RegisterOptions } from 'react-hook-form'

export interface ItemContainerProps extends BoxProps {
  name: string
  active?: boolean
}

export const ItemContainer: React.FC<React.PropsWithChildren<ItemContainerProps>> = ({
  sx,
  name,
  p = 32,
  active = false,
  children,
  ...rest
}) => {
  return (
    <label htmlFor={name}>
      <Box
        h={170}
        p={p}
        sx={mergeSxList([
          (theme) => ({
            boxSizing: 'border-box',
            borderRadius: theme.defaultRadius,
            border: `1px solid ${theme.colors.carbon[4]}`,
            boxShadow: '0px 2px 4px 0px rgba(0, 0, 0, 0.04)',
            cursor: 'pointer',
            backgroundColor: active ? theme.colors.carbon[8] : undefined,
            backgroundSize: 'cover',
            ':hover': {
              borderWidth: active ? 1 : 2,
              padding: `${active ? Number(p) : Number(p) - 1}px !important`,
              borderColor: active ? undefined : theme.colors.peacock[7]
            }
          }),
          sx
        ])}
        {...rest}
      >
        {children}
      </Box>
    </label>
  )
}

export interface CheckItemProps extends BoxProps {
  value: string | number
  icon: React.ReactNode
  description: string
  checked?: boolean
  iconProps?: BoxProps
  descrptionProps?: TypographyProps
  withCheckbox?: boolean
}
export const CheckItem: React.FC<CheckItemProps> = ({
  value,
  icon,
  description,
  checked,
  iconProps,
  descrptionProps,
  withCheckbox = true,
  ...rest
}) => {
  return (
    <ItemContainer name={value.toString()} active={checked} {...rest}>
      <Stack justify="space-between" h="100%" gap={0}>
        <Flex justify="space-between">
          <Box c={checked ? 'white' : undefined} {...iconProps}>
            {icon}
          </Box>
          <Checkbox
            styles={{
              inner: {
                display: !withCheckbox ? 'none' : undefined
              }
            }}
            value={value}
            id={value.toString()}
          />
        </Flex>
        <Typography variant="body-lg" c={checked ? 'white' : undefined} {...descrptionProps}>
          {description}
        </Typography>
      </Stack>
    </ItemContainer>
  )
}

export interface FormCheckItemProps extends SimpleGridProps {
  name: string
  multiple?: boolean
  options: CheckItemProps[]
  itemProps?: BoxProps & {
    iconProps?: CheckItemProps['iconProps']
    descrptionProps?: CheckItemProps['descrptionProps']
    withCheckbox?: CheckItemProps['withCheckbox']
  }
  rules?: RegisterOptions
}

export const FormCheckItemGroup = ({ options, name, rules, multiple, itemProps, ...rest }: FormCheckItemProps) => {
  const { control, formState, getFieldState } = useFormContext()
  const { error } = getFieldState(name, formState)
  return (
    <Controller
      control={control}
      name={name}
      rules={rules}
      render={({ field }) => {
        const { onChange: handleChange, value, ...restField } = field
        const realValue = Array.isArray(value) ? value : [value]
        return (
          <Checkbox.Group
            value={realValue}
            onChange={(val) => {
              if (multiple) {
                handleChange(val)
              } else {
                val = val?.filter((item) => item !== realValue?.[0])
                handleChange(val?.[0])
              }
            }}
            {...restField}
            error={error ? <ErrorMessage errors={formState.errors} name={name} /> : undefined}
          >
            <SimpleGrid {...rest}>
              {options.map((option) => (
                <CheckItem key={option.value} checked={realValue.includes(option.value)} {...itemProps} {...option} />
              ))}
            </SimpleGrid>
          </Checkbox.Group>
        )
      }}
    ></Controller>
  )
}

export interface SectorProps {
  label?: React.ReactNode
  size?: number
  value?: number
  thickness?: number
  completed?: boolean
  onlyText?: boolean
}

export const Sector = ({ label, size = 36, value = 0, thickness = 2, completed, onlyText }: SectorProps) => {
  const theme = useMantineTheme()
  const r = (size - thickness) / 2
  const base = 3.1415926
  const active = !completed && value > 0

  if (onlyText) {
    return (
      <Flex
        sx={() => ({
          width: size,
          height: size,
          color: 'white',
          borderRadius: '50%',
          backgroundColor: theme.colors.peacock[7]
        })}
        justify="center"
        align="center"
      >
        {label}
      </Flex>
    )
  }

  return (
    <Box
      sx={() => ({
        width: size,
        height: size,
        position: 'relative',
        circle: {
          cx: size / 2,
          cy: size / 2,
          r: r,
          fill: 'none',
          strokeWidth: thickness
          // transition: `stroke-dasharray .4s linear, stroke .3s`
        },
        color: active ? theme.colors.peacock[7] : theme.colors.carbon[6]
      })}
    >
      <svg width="100%" height="100%" style={{ transform: 'rotate(-90deg)' }}>
        <circle stroke={completed ? theme.colors.peacock[4] : theme.colors.carbon[4]} />
        <circle
          stroke={theme.colors.peacock[7]}
          style={{
            opacity: active ? 1 : 0,
            strokeDasharray: `${2 * base * r * (value / 100)}, 1000`
          }}
        />
      </svg>
      <Center
        sx={() => ({
          position: 'absolute',
          left: thickness,
          right: thickness,
          top: thickness,
          bottom: thickness,
          borderRadius: '50%',
          backgroundColor: completed ? theme.colors.peacock[2] : undefined,
          backgroundImage: active
            ? `conic-gradient(
            ${theme.colors.peacock[2]} 0, ${theme.colors.peacock[2]} ${value}%,
            transparent ${value}%, transparent 100%
        )`
            : undefined
        })}
      >
        {completed ? <IconCheck c="peacock.7" size={20} /> : label}
      </Center>
    </Box>
  )
}

interface FormAutocompleteProps extends AutocompleteProps {
  name: string
  rules?: RegisterOptions
}

export const FormAutocomplete = ({ name, rules, onChange, ...rest }: FormAutocompleteProps) => {
  const { control, formState, getFieldState } = useFormContext()
  const { error } = getFieldState(name, formState)
  return (
    <Controller
      control={control}
      name={name}
      rules={rules}
      render={({ field }) => {
        const { onChange: handleChange, value, ...restField } = field
        return (
          <Autocomplete
            styles={{
              input: {
                height: 40
              }
            }}
            value={value}
            onChange={(val) => {
              handleChange(val)
              onChange?.(val)
            }}
            {...restField}
            {...rest}
            error={error ? <ErrorMessage errors={formState.errors} name={name} /> : undefined}
          />
        )
      }}
    ></Controller>
  )
}

export interface CompanyItemProps {
  logo: string
  value: string
}

export const CompanyItem = ({ value, logo, ...others }: CompanyItemProps) => {
  return (
    <div {...others}>
      <Group wrap="nowrap">
        <Avatar size={32} src={logo} />
        <div>
          <Text>{value}</Text>
        </div>
      </Group>
    </div>
  )
}
