import { useHouseDetail } from '@api/house'
import AreaInput from '@components/AreaInput'
import { errorTip, labelWithIcon } from '@components/Common'
import {
  Anchor,
  Box,
  Breadcrumbs,
  Button,
  Divider,
  Grid,
  Group,
  Paper,
  Select,
  Skeleton,
  Text,
  TextInput,
} from '@mantine/core'
import { useForm, yupResolver } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { PathConstants } from '@routes/routes'
import {
  IconAddressBook,
  IconCheck,
  IconCircleCheck,
  IconCircleXFilled,
  IconIcons,
  IconMapPin,
  icons,
  IconTagFilled,
  IconVector,
} from '@tabler/icons-react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, NavLink, useNavigate, useParams } from 'react-router-dom'
import * as yup from 'yup'

const houseSchema = (t) =>
  yup.object({
    icon: yup
      .string()
      .min(3, t('message_min_three_char'))
      .required(t('message_is_required', { field: t('ui_house_icon') })),
    name: yup
      .string()
      .min(3, t('message_min_three_char'))
      .required(t('message_is_required', { field: t('ui_house_name') })),
    address: yup
      .string()
      .min(3, t('message_min_three_char'))
      .required(t('message_is_required', { field: t('ui_house_address') })),
    areas: yup
      .array()
      .min(1, t('message_is_required', { field: t('ui_areas') }))
      .required(t('message_is_required', { field: t('ui_areas') })),
  })

function IconDynamic({ icon }) {
  const Icon = icons[icon]

  return Icon ? <Icon size={15} /> : null
}

export default function HouseCreate() {
  const { t } = useTranslation()
  const { id } = useParams()
  const navigate = useNavigate()

  const { house, isLoading, trigger } = useHouseDetail(id)
  const form = useForm({
    initialValues: {
      icon: '',
      name: '',
      address: '',
      areas: [],
    },
    validate: yupResolver(houseSchema(t)),
    enhanceGetInputProps: (payload) => ({
      error: errorTip(payload.inputProps.error),
    }),
  })

  useEffect(() => {
    if (id && house) {
      form.setValues(house)
    }
  }, [house])

  const onSubmit = async (values) => {
    const result = {
      ...values,
      areas: values.areas.map((item) =>
        item.isCreate ? { name: item.name, desc: item.desc } : { ...item },
      ),
    }
    try {
      const data = await trigger(result)

      if (data.status === 200) {
        notifications.show({
          color: 'green.5',
          icon: <IconCircleCheck />,
          title: t('ui_success'),
          message: t('message_action_house_success', {
            action: t(id ? 'ui_update' : 'ui_create'),
          }),
        })
        navigate(PathConstants.LOCATION)
      }
    } catch (error) {
      notifications.show({
        color: 'red.5',
        icon: <IconCircleXFilled />,
        withCloseButton: true,
        title: t('ui_error'),
        message: error
          ? error
          : t('message_action_house_fail', {
              action: t(id ? 'ui_update' : 'ui_create'),
            }),
      })
    }
  }

  if (isLoading) {
    return (
      <Box>
        <Breadcrumbs mb="md">
          <Anchor
            component={NavLink}
            fz="xs"
            to={PathConstants.LOCATION}
            underline="hover"
            c="blue"
          >
            {t('ui_house')}
          </Anchor>
          <Anchor component="span" fz="xs" underline="never" c="blue">
            {t('ui_new_house')}
          </Anchor>
        </Breadcrumbs>
        <Divider
          label={
            <>
              <IconMapPin size={20} color="black" />
              <Text ml="xs" c="black">
                {t('ui_new_house')}
              </Text>
            </>
          }
          mb="md"
        />
        <Paper shadow="md" p="md" radius="md">
          <Grid gutter="md">
            <Grid.Col span={{ base: 12, lg: 6 }}>
              <Skeleton height={33} radius="lg" />
            </Grid.Col>
            <Grid.Col span={{ base: 12, lg: 6 }}>
              <Skeleton height={33} radius="lg" />
            </Grid.Col>
            <Grid.Col span={12}>
              <Skeleton height={33} radius="lg" />
            </Grid.Col>
            <Grid.Col span={12}>
              <Skeleton height={300} radius="lg" />
            </Grid.Col>
            <Grid.Col span={12}>
              <Group position="right">
                <Skeleton height={33} width={70} radius="lg" />
                <Skeleton height={33} width={70} radius="lg" />
              </Group>
            </Grid.Col>
          </Grid>
        </Paper>
      </Box>
    )
  }

  return (
    <Box>
      <Breadcrumbs mb="md">
        <Anchor
          component={NavLink}
          fz="xs"
          to={PathConstants.LOCATION}
          underline="hover"
          c="blue"
        >
          {t('ui_house')}
        </Anchor>
        <Anchor component="span" fz="xs" underline="never" c="blue">
          {t('ui_new_house')}
        </Anchor>
      </Breadcrumbs>
      <Divider
        label={
          <>
            <IconMapPin size={20} color="black" />
            <Text ml="xs" c="black">
              {t('ui_new_house')}
            </Text>
          </>
        }
        mb="md"
      />
      <Paper shadow="md" p="md" radius="md">
        <form autoComplete="off" onSubmit={form.onSubmit(onSubmit)}>
          <Grid gutter="md">
            <Grid.Col span={{ base: 12, lg: 6 }}>
              <Select
                label={labelWithIcon(t('ui_house_icon'), IconIcons)}
                placeholder={t('ui_house_icon')}
                searchable
                limit={7}
                data={Object.entries(icons).map(([key, value]) => ({
                  value: key,
                  label: key,
                  icon: value,
                }))}
                renderOption={({ option, checked }) => {
                  const Icon = option.icon
                  return (
                    <Group flex="1" gap="xs">
                      <Icon size={20} />
                      {option.label}
                      {checked && (
                        <IconCheck
                          style={{ marginInlineStart: 'auto' }}
                          size={15}
                        />
                      )}
                    </Group>
                  )
                }}
                nothingFoundMessage={t('ui_empty')}
                leftSection={<IconDynamic icon={form.values.icon} />}
                {...form.getInputProps('icon')}
              />
            </Grid.Col>
            <Grid.Col span={{ base: 12, lg: 6 }}>
              <TextInput
                label={labelWithIcon(t('ui_house_name'), IconTagFilled)}
                placeholder={t('ui_house_name')}
                {...form.getInputProps('name')}
              />
            </Grid.Col>
            <Grid.Col span={12}>
              <TextInput
                label={labelWithIcon(t('ui_house_address'), IconAddressBook)}
                placeholder={t('ui_house_address')}
                {...form.getInputProps('address')}
              />
            </Grid.Col>
            <Grid.Col span={12}>
              <AreaInput
                label={labelWithIcon(t('ui_areas'), IconVector)}
                {...form.getInputProps('areas')}
              />
            </Grid.Col>
            <Grid.Col span={12}>
              <Group position="right">
                <Button type="submit">
                  {t(id ? 'ui_update' : 'ui_create')}
                </Button>
                <Button
                  variant="outline"
                  component={Link}
                  to={PathConstants.LOCATION}
                  color="red"
                >
                  {t('ui_cancel')}
                </Button>
              </Group>
            </Grid.Col>
          </Grid>
        </form>
      </Paper>
    </Box>
  )
}
