import { useHouse } from '@api/house'
import Datatable from '@components/Datatable'
import GridList from '@components/GridList'
import {
  ActionIcon,
  Box,
  Button,
  Divider,
  Group,
  Pagination,
  Paper,
  rem,
  SegmentedControl,
  Select,
  Skeleton,
  Text,
  TypographyStylesProvider,
  VisuallyHidden,
} from '@mantine/core'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import { PathConstants } from '@routes/routes'
import * as icons from '@tabler/icons-react'
import {
  IconCircleCheck,
  IconCircleXFilled,
  IconGridDots,
  IconLayoutList,
  IconMapPin,
  IconPencil,
  IconTrash,
} from '@tabler/icons-react'
import { VIEWDATA } from '@utils/enum'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from 'react-router-dom'

const PAGE_SIZE = [10, 50, 100]

const getPaginationText = (total, size, page) => {
  const start = (page - 1) * size + 1
  const end = Math.min(start + size - 1, total)

  return `${start} - ${end} / ${total}`
}

export default function House() {
  const { t } = useTranslation()
  const [view, setView] = useState(VIEWDATA['list'])
  const [page, setPage] = useState(1)
  const navigate = useNavigate()
  const [pageSize, setPageSize] = useState(PAGE_SIZE[0])
  const { houses, isLoading, mutate, trigger } = useHouse(page, pageSize)

  const iconProps = (dimansions = 15) => ({
    style: {
      width: rem(dimansions),
      height: rem(dimansions),
      display: 'block',
    },
    stroke: 1.5,
  })

  const onClickEdit = (editId) => () => {
    navigate(PathConstants.EDIT_LOCATION.replace(':id', editId), {
      replace: true,
    })
  }

  const onDelete = async (deleteId) => {
    console.log('delete', deleteId)
    try {
      const rs = await trigger(deleteId)
      if (rs.status === 200) {
        notifications.show({
          color: 'green.5',
          icon: <IconCircleCheck />,
          withCloseButton: true,
          title: t('ui_success'),
          message: t('message_success_delete'),
        })
        mutate()
      }
    } catch (error) {
      notifications.show({
        color: 'red.5',
        icon: <IconCircleXFilled />,
        withCloseButton: true,
        title: t('ui_error'),
        message: JSON.stringify(error),
      })
    }
  }

  const onClickDelete = (deleteId) => () => {
    modals.openConfirmModal({
      title: t('message_confirm_delete'),
      centered: true,
      children: (
        <TypographyStylesProvider fz={'sm'}>
          <div
            dangerouslySetInnerHTML={{
              __html: t('message_confirm_delete_note'),
            }}
          />
        </TypographyStylesProvider>
      ),
      labels: { confirm: t('ui_delete'), cancel: t('ui_cancel') },
      confirmProps: { color: 'red' },
      onConfirm: () => onDelete(deleteId),
    })
  }

  const columnsData = useMemo(
    () => [
      {
        title: t('table_col_icon'),
        width: '10%',
        field: 'icon',
        render: ({ icon }, view = false) => {
          const Icon = icons[icon]
          return Icon ? <Icon {...iconProps(view ? 50 : 30)} /> : null
        },
      },
      {
        title: t('table_col_name'),
        width: '35%',
        field: 'name',
        render: ({ name }) => <Text>{name}</Text>,
      },
      {
        title: t('table_col_address'),
        width: '35%',
        field: 'address',
        render: ({ address }) => <Text>{address}</Text>,
      },
      {
        title: t('table_col_action'),
        width: '20%',
        field: 'action',
        render: ({ id }, view = false) => {
          return (
            <Group justify={view ? 'flex-end' : false}>
              <ActionIcon
                variant="subtle"
                color="blue"
                onClick={onClickEdit(id)}
              >
                <IconPencil size={20} />
              </ActionIcon>
              <ActionIcon
                variant="subtle"
                color="red"
                onClick={onClickDelete(id)}
              >
                <IconTrash size={20} />
              </ActionIcon>
            </Group>
          )
        },
      },
    ],
    [],
  )

  if (isLoading) {
    return (
      <Box>
        <Divider
          label={
            <>
              <IconMapPin size={20} color="black" />
              <Text ml="xs" c="black">
                {t('ui_house')}
              </Text>
            </>
          }
          mb="md"
        />
        <Group justify="space-between">
          <Skeleton height={33} width={100} radius="lg" />
          <Group justify="flex-end">
            <Skeleton height={33} width={200} radius="lg" />
          </Group>
        </Group>
        <Box mt="sm">
          <Skeleton height={500} radius="lg" />
        </Box>
        <Group justify="space-between" mt="md">
          <Group>
            <Skeleton height={33} width={200} radius="lg" />
          </Group>
          <Skeleton height={33} width={350} radius="lg" />
        </Group>
      </Box>
    )
  }

  return (
    <Box>
      <Divider
        label={
          <>
            <IconMapPin size={20} color="black" />
            <Text ml="xs" c="black">
              {t('ui_house')}
            </Text>
          </>
        }
        mb="md"
      />
      <Paper shadow="md" p="md" radius="md">
        <Group justify="space-between">
          <SegmentedControl
            value={view}
            onChange={setView}
            data={[
              {
                label: (
                  <>
                    <IconLayoutList {...iconProps()} />
                    <VisuallyHidden>List</VisuallyHidden>
                  </>
                ),
                value: VIEWDATA['list'],
              },
              {
                label: (
                  <>
                    <IconGridDots {...iconProps()} />
                    <VisuallyHidden>Grid</VisuallyHidden>
                  </>
                ),
                value: VIEWDATA['grid'],
              },
            ]}
          />
          <Group justify="flex-end">
            <Button
              component={Link}
              to={PathConstants.CREATE_LOCATION}
              color="green"
            >
              {t('ui_create_new')}
            </Button>
          </Group>
        </Group>
        <Box mt="sm">
          {view === VIEWDATA['list'] ? (
            <Datatable columns={columnsData} data={houses?.list} />
          ) : (
            <GridList columns={columnsData} data={houses?.list} />
          )}
        </Box>
        <Group justify="space-between" mt="md">
          <Group>
            <Text inline>
              {t('ui_showing')}:{' '}
              {getPaginationText(houses?.total, pageSize, page)}
            </Text>
            <Select
              checkIconPosition="right"
              data={PAGE_SIZE.map((size) => size.toString())}
              value={pageSize.toString()}
              onChange={setPageSize}
              size="xs"
              allowDeselect={false}
              w={70}
            />
          </Group>
          <Pagination
            total={Math.ceil(houses?.total / pageSize)}
            siblings={3}
            value={page}
            onChange={setPage}
          />
        </Group>
      </Paper>
    </Box>
  )
}
