import { Button, Checkbox, Spinner, Table } from '@/components/ui'
import NotificationChannels from '@/constants/notification-channel.enum'
import { NotificationRuleDto } from '@/proxy/notification/models'
import {
  deleteMyNotificationRules,
  getMyNotificationRules,
  getMyNotificationTypes,
  postMyNotificationRule,
} from '@/services/notification-rule.service'
import classNames from 'classnames'
import isEmpty from 'lodash/isEmpty'
import { useEffect, useState } from 'react'
import { FaHistory } from 'react-icons/fa';

const { Tr, Th, Td, THead, TBody } = Table

const NotificationSettings = () => {
  const [loading, setLoading] = useState(true)
  const [list, setList] = useState<NotificationRuleDto[][]>([])
  const [notificationTypes, setNotificationTypes] = useState<string[]>([])
  const [channels, setChannels] = useState<string[]>([])

  const fetchData = async () => {
    setLoading(true)
    const channels = Object.keys(NotificationChannels)
    setChannels(channels)
    const response = await getMyNotificationTypes()
    const notificationTypes = response.data
    setNotificationTypes(response.data)
    const responseRules = await getMyNotificationRules()
    const rules = responseRules.data
    const finalList: NotificationRuleDto[][] = []
    for (const notificationType of notificationTypes) {
      const x: NotificationRuleDto[] = []
      for (const channel of channels) {
        const rule = rules.find(
          (a) => a.channel == channel && a.notificationType == notificationType,
        )
        x.push(
          rule ??
            ({
              channel,
              notificationType,
              isActive: false,
            } as NotificationRuleDto),
        )
      }
      finalList.push(x)
    }
    setList(finalList)
    setLoading(false)
  }

  useEffect(() => {
    if (isEmpty(list)) {
      fetchData()
    }
  }, [])

  const onClickCheckbox = async (checked: boolean, rule: NotificationRuleDto) => {
    await postMyNotificationRule({
      channel: rule.channel,
      notificationType: rule.notificationType,
      isActive: checked,
    })
    fetchData()
  }

  const resetMyNotifications = async (notificationType: string) => {
    await deleteMyNotificationRules(notificationType)
    fetchData()
  }

  return (
    <>
      {loading ? (
        <div className={classNames('flex items-center justify-center')}>
          <Spinner size={40} />
        </div>
      ) : (
        <>
          {list.length ? (
            <Table compact={true}>
              <THead>
                <Tr>
                  <Th></Th>
                  {channels.map((a) => (
                    <Th key={a} className="text-center">
                      {a}
                    </Th>
                  ))}
                </Tr>
              </THead>
              <TBody>
                {notificationTypes.map((a, m) => (
                  <Tr key={a}>
                    <Th>
                      <Button
                        shape="circle"
                        variant="plain"
                        type="button"
                        size="xs"
                        title="Reset"
                        icon={<FaHistory />}
                        onClick={async (e) => {
                          e.preventDefault()
                          resetMyNotifications(a)
                        }}
                      />
                      {a}
                    </Th>
                    {channels.map((b, n) => (
                      <Td key={a + b} className="text-center">
                        <Checkbox
                          name={a + b}
                          disabled={list[m][n].isFixed}
                          checked={list[m][n].isActive}
                          onChange={(e) => onClickCheckbox(e, list[m][n])}
                          color={list[m][n].isCustomized ? 'red-500' : undefined}
                          title={list[m][n].id}
                        ></Checkbox>
                      </Td>
                    ))}
                  </Tr>
                ))}
              </TBody>
            </Table>
          ) : (
            <></>
          )}
        </>
      )}
    </>
  )
}

export default NotificationSettings
