import { useEffect, useState } from 'react'
import moment from 'moment'

import {
  Avatar,
  Badge,
  Box,
  Button,
  Drawer,
  Flex,
  Group,
  HoverCard,
  Menu,
  Modal,
  Select,
  Stack,
  Table,
  Text,
  Textarea,
  TextInput,
  Tooltip,
} from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { notifications } from '@mantine/notifications'
import {
  IconEdit,
  IconFileExcel,
  IconHelpCircle,
  IconRefresh,
  IconTrash,
} from '@tabler/icons-react'
import classes from './LeaveManagement.module.css'

import {
  getLeaveManagement,
  updateNoteLeave,
  exportLeaveManagement,
  updateNoteStatus,
  deleteNote,
} from '@/api/Admin'
import { update, Xdelete } from '@/rtk/helpers/CRUD'
import { get, exportFile } from '@/rtk/helpers/apiService'
import { useSelector } from 'react-redux'
import { RootState } from '@/rtk/store'

interface User {
  id: number
  name: string
  email: string
  email_verified_at: string | null
  permission: string
  remember_token: string | null
  avatar: string
  created_at: string | null
  updated_at: string | null
}

interface LeaveDay {
  id: number
  ld_user_id: number
  ld_year: number
  ld_day_total: number
  ld_additional_day: number
  ld_special_leave_day: number
  ld_note: string
  created_at: string | null
  updated_at: string | null
}

interface MonthlyLeaveDays {
  id: number
  day: number
  leave_days: number
  month: number
  n_user_id: number
  reason_code: string
  reason_name: string
  time_type_name: string
}

interface UserData {
  user: User
  leaveDay: LeaveDay
  monthlyLeaveDays: MonthlyLeaveDays[]
}

// interface DataReason {
//   id: number
//   c_code: string
//   c_name: string
// }

// interface DataTimeType {
//   id: number
//   c_code: string
//   c_name: string
// }

const LeaveManagement = () => {
  const user = useSelector((state: RootState) => state.authentication)

  const [opened1, { open: open1, close: close1 }] = useDisclosure(false)
  const [openedDetailOff, { open: openDetailOff, close: closeDetailOff }] =
    useDisclosure(false)
  const [detailOffItem, setDetailOffItem] = useState<UserData>({
    user: {
      id: 0,
      name: '',
      email: '',
      email_verified_at: '',
      permission: '',
      remember_token: '',
      avatar: '',
      created_at: '',
      updated_at: '',
    },
    leaveDay: {
      id: 0,
      ld_user_id: 0,
      ld_year: 0,
      ld_day_total: 0,
      ld_additional_day: 0,
      ld_special_leave_day: 0,
      ld_note: '',
      created_at: '',
      updated_at: '',
    },
    monthlyLeaveDays: [],
  })

  const [isStatusConfirmOpen, setIsStatusConfirmOpen] = useState(false)
  const [isDisableStatusBtn, setIsDisableStatusBtn] = useState(false)
  const [noteStatus, setNoteStatus] = useState<{
    id: number
    reason: string
  }>({
    id: 0,
    reason: '',
  })

  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false)
  const [isDisableDeleteBtn, setIsDisableDeleteBtn] = useState(false)
  const [noteToDelete, setNoteToDelete] = useState<any>(null)

  const [disableBtn, setDisableBtn] = useState(false)
  const monthInYear = getMonthNames()
  const [customAddNotes, setCustomAddNotes] = useState<{
    id: number
    user: {
      id: number
      name: string
    }
    note: string
    totalLeave: string
    dayAdditional: string
    specialLeave: string
  }>({
    id: 0,
    user: {
      id: 0,
      name: '',
    },
    note: '',
    totalLeave: '',
    dayAdditional: '',
    specialLeave: '',
  })

  const [data, setData] = useState<UserData[]>([])
  const [date, setDate] = useState({
    year: new Date().getFullYear().toString(),
  })
  // const [dataTimeType, setDataTimeType] = useState<DataTimeType[]>([])
  // const [dataReason, setDataReason] = useState<DataReason[]>([])

  const now = new Date()
  const currentMonth = now.getMonth() + 1 // getMonth() trả về 0-11
  const currentYear = now.getFullYear()

  // const getListMasterByType = async (type: string) => {
  //   try {
  //     const params = {
  //       type: type,
  //     }
  //     const res = await get(getListMaster, params)
  //     if (res.status) {
  //       return res.data
  //     }
  //   } catch (error: any) {
  //     notifications.show({
  //       title: 'Error',
  //       message: error.message ?? error,
  //       color: 'red',
  //     })
  //   }
  //   return []
  // }

  // useEffect(() => {
  //   const fetchData = async () => {
  //     const resultTimeType = await getListMasterByType('TIME_TYPE')
  //     setDataTimeType(
  //       resultTimeType.filter((item: DataTimeType) => item.c_code !== 'ALL'),
  //     )

  //     const resultReason = await getListMasterByType('REASON')
  //     setDataReason(resultReason)
  //   }

  //   fetchData()
  // }, [])

  const getLeaveList = async () => {
    try {
      const res = await get(getLeaveManagement, {
        year: date.year,
      })
      if (res.status) {
        setData(
          res.data.filter((u: UserData) => u.user.permission.includes('staff')),
        )
      }
    } catch (error: any) {
      console.log(error)
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    }
  }

  useEffect(() => {
    getLeaveList()
  }, [date])

  const updateInfoNote = async (
    id: number,
    users: {
      id: number
      name: string
    },
    totalLeave: string,
    dayAdditional: string,
    specialLeave: string,
    note: string,
  ) => {
    try {
      await update(
        updateNoteLeave,
        {
          id: id,
          users: users,
          totalLeave: totalLeave,
          dayAdditional: dayAdditional,
          specialLeave: specialLeave,
          note: note,
        },
        getLeaveList,
      )

      setDisableBtn(false)
    } catch (error) {
      console.log(error)
    }
  }

  const updateNote = async () => {
    setIsDisableStatusBtn(true)
    try {
      await update(
        updateNoteStatus,
        {
          id: noteStatus.id,
          n_reason: noteStatus.reason,
        },
        getLeaveList,
      )
    } catch (error) {
      console.log(error)
    } finally {
      setIsDisableStatusBtn(false)
      closeDetailOff()
      setIsStatusConfirmOpen(false)
      setNoteStatus({
        id: 0,
        reason: '',
      })
    }
  }

  const handleDeleteNote = async () => {
    if (noteToDelete) {
      setIsDisableDeleteBtn(true)

      try {
        await Xdelete(
          deleteNote,
          { id: noteToDelete.id, month: noteToDelete.month, year: date.year },
          getLeaveList,
        )
      } catch (error) {
        console.log(error)
      } finally {
        setIsDisableDeleteBtn(false)
        closeDetailOff()
        setIsDeleteConfirmOpen(false)
        setNoteToDelete(null)
      }
    }
  }

  function getMonthNames() {
    const monthNames = [
      {
        value: 1,
        name: 'January',
      },
      {
        value: 2,
        name: 'February',
      },
      {
        value: 3,
        name: 'March',
      },
      {
        value: 4,
        name: 'April',
      },
      {
        value: 5,
        name: 'May',
      },
      {
        value: 6,
        name: 'June',
      },
      {
        value: 7,
        name: 'July',
      },
      {
        value: 8,
        name: 'August',
      },
      {
        value: 9,
        name: 'September',
      },
      {
        value: 10,
        name: 'October',
      },
      {
        value: 11,
        name: 'November',
      },
      {
        value: 12,
        name: 'December',
      },
    ]
    return monthNames.map((month) => {
      return {
        value: month.value,
        name: month.name.substring(0, 3),
      }
    })
  }

  const getDetailLeaveDay = (monthlyLeaveDays: MonthlyLeaveDays[]) => {
    type MonthlyLeaveDaysAcc = {
      [key: string]: { n_user_id: number; month: number; leave_days: number }
    }
    const summedLeaveDaysByUserAndMonth = monthlyLeaveDays.reduce(
      (acc: MonthlyLeaveDaysAcc, record) => {
        const { n_user_id, month, leave_days } = record
        const key = `${month}`

        if (!acc[key]) {
          acc[key] = { n_user_id, month, leave_days: 0 }
        }

        acc[key].leave_days += Number(leave_days)

        return acc
      },
      {},
    )
    return summedLeaveDaysByUserAndMonth
  }

  const showAllOff = (monthlyLeaveDays: MonthlyLeaveDays[]) => {
    return monthInYear.map((d, i) => {
      let totalOnLeaveMonth = 0
      let totalLeaveWithoutPayMonth = 0
      let totalTempMonth = 0

      monthlyLeaveDays
        .filter((item) => item.month === d.value)
        .map((item) => {
          if (item.reason_code === 'ONLEAVE') {
            totalOnLeaveMonth += Number(item.leave_days)
          } else if (item.reason_code === 'LEAVE_WITHOUT_PAY') {
            totalLeaveWithoutPayMonth += Number(item.leave_days)
          } else {
            totalTempMonth += Number(item.leave_days)
          }
        })

      if (totalOnLeaveMonth === 0 && totalLeaveWithoutPayMonth === 0) {
        return ''
      }

      return (
        <Box key={i} px="xs" my="xs">
          <Group gap="xs">
            {totalOnLeaveMonth > 0 && (
              <Badge color="teal" variant="light">
                {totalOnLeaveMonth} có phép
              </Badge>
            )}
            {totalLeaveWithoutPayMonth > 0 && (
              <Badge color="red" variant="light">
                {totalLeaveWithoutPayMonth} không phép
              </Badge>
            )}
            <Text size="xs" color="dimmed">
              ({d.value}/2025)
            </Text>
          </Group>
        </Box>
      )
    })
  }

  const showAllTotal = (
    ld_day_total: number,
    ld_additional_day: number,
    ld_special_leave_day: number,
  ): JSX.Element => {
    const showItem = (label: string, value: number, color: string = 'gray') => {
      if (value === 0) return null

      return (
        <Group justify="space-between" gap="xs">
          <Text size="sm" c="dimmed">
            {label}
          </Text>
          <Text size="sm" fw={500} c={color}>
            {value}
          </Text>
        </Group>
      )
    }

    return (
      <Box p="sm">
        <Stack gap={4}>
          {showItem(
            'Tổng phép hiện có:',
            ld_day_total + ld_additional_day + ld_special_leave_day,
            'white',
          )}
          {showItem('+ Phép được cấp năm nay:', ld_day_total, 'teal')}
          {showItem('+ Phép tồn năm trước:', ld_additional_day, 'violet')}
          {showItem('+ Phép đặc biệt:', ld_special_leave_day, 'orange')}
        </Stack>
      </Box>
    )
  }

  const handleExport = async () => {
    try {
      const timestamp = moment().format('DDMMYYYY_HHmmss')
      const fileName = `LeaveManagement_${date.year}_${timestamp}.xlsx`

      await exportFile(
        exportLeaveManagement,
        {
          year: parseInt(date.year),
        },
        fileName,
      )
    } catch (error) {
      console.error('Export error:', error)
      notifications.show({
        title: 'Error',
        message: 'Export failed',
        color: 'red',
      })
    }
  }

  return (
    <div>
      <div className={classes.title}>
        <h3>Leave Management</h3>
      </div>
      {/* Update Leave Day */}
      <Drawer
        opened={opened1}
        onClose={close1}
        position="right"
        title={<strong>Update Day Leave</strong>}
      >
        <TextInput
          mb={'md'}
          value={customAddNotes.totalLeave}
          onChange={(e) => {
            const value = e.target.value
            if (value) {
              const floatValue = parseFloat(value)
              if (
                /^\d*\.?\d?$/.test(value) &&
                floatValue >= 0 &&
                floatValue <= 20
              ) {
                setCustomAddNotes({
                  ...customAddNotes,
                  totalLeave: value,
                })
              }
            } else {
              setCustomAddNotes({
                ...customAddNotes,
                totalLeave: value,
              })
            }
          }}
          label={'Phép năm'}
          placeholder="Nhập số ngày phép năm"
          disabled={
            !['admin', 'hr'].some((role) =>
              user.user.user.permission
                .split(',')
                .map((p: string) => p.trim())
                .includes(role),
            )
          }
        />
        <TextInput
          mb={'md'}
          value={customAddNotes.dayAdditional}
          onChange={(e) => {
            const value = e.target.value
            if (value) {
              const floatValue = parseFloat(value)
              if (
                /^\d*\.?\d?$/.test(value) &&
                floatValue >= 0 &&
                floatValue <= 20
              ) {
                setCustomAddNotes({
                  ...customAddNotes,
                  dayAdditional: value,
                })
              }
            } else {
              setCustomAddNotes({
                ...customAddNotes,
                dayAdditional: '',
              })
            }
          }}
          label={'Phép năm cũ'}
          placeholder="Nhập số ngày phép năm cũ"
          disabled={
            !['admin', 'hr'].some((role) =>
              user.user.user.permission
                .split(',')
                .map((p: string) => p.trim())
                .includes(role),
            )
          }
        />
        <TextInput
          mb={'md'}
          value={customAddNotes.specialLeave}
          onChange={(e) => {
            const value = e.target.value
            if (value) {
              const floatValue = parseFloat(value)
              if (
                /^\d*\.?\d?$/.test(value) &&
                floatValue >= 0 &&
                floatValue <= 20
              ) {
                setCustomAddNotes({
                  ...customAddNotes,
                  specialLeave: value,
                })
              }
            } else {
              setCustomAddNotes({
                ...customAddNotes,
                specialLeave: '',
              })
            }
          }}
          label={'Phép đặc biệt'}
          placeholder="Nhập số ngày phép đặc biệt"
          disabled={
            !['admin', 'hr'].some((role) =>
              user.user.user.permission
                .split(',')
                .map((p: string) => p.trim())
                .includes(role),
            )
          }
        />
        <Textarea
          mb={'md'}
          label="Note"
          value={customAddNotes.note}
          onChange={(e) => {
            setCustomAddNotes({ ...customAddNotes, note: e.target.value })
          }}
          rows={10}
          disabled={
            !['admin', 'hr'].some((role) =>
              user.user.user.permission
                .split(',')
                .map((p: string) => p.trim())
                .includes(role),
            )
          }
        />

        {['admin', 'hr'].some((role) =>
          user.user.user.permission
            .split(',')
            .map((p: string) => p.trim())
            .includes(role),
        ) ? (
          <Button
            onClick={() => {
              setDisableBtn(true)
              if (
                customAddNotes.id === 0
                // ||
                // customAddNotes.totalLeave === '' ||
                // customAddNotes.totalLeave === '0'
                // customAddNotes.dayAdditional === 0 ||
                // customAddNotes.note === ''
              ) {
                notifications.show({
                  title: 'Error',
                  message: 'Input data required',
                  color: 'red',
                })
                setDisableBtn(false)
              } else {
                updateInfoNote(
                  customAddNotes.id,
                  customAddNotes.user,
                  customAddNotes.totalLeave,
                  customAddNotes.dayAdditional,
                  customAddNotes.specialLeave,
                  customAddNotes.note,
                )
              }
            }}
            disabled={disableBtn}
          >
            Save
          </Button>
        ) : (
          ''
        )}
      </Drawer>

      {/* Filter Year, Export Btn */}
      <Flex justify="space-between" align="flex-end">
        <Select
          value={date.year}
          size="xs"
          label="Year"
          data={Array.from({ length: 10 }, (_, index) => {
            return {
              value: (
                parseInt(moment(Date.now()).format('YYYY')) -
                3 +
                index
              ).toString(),
              label: (
                parseInt(moment(Date.now()).format('YYYY')) -
                3 +
                index
              ).toString(),
              disabled:
                parseInt(moment(Date.now()).format('YYYY')) - 3 + index >
                parseInt(moment(Date.now()).format('YYYY')),
            }
          })}
          onChange={(e) => {
            setDate({ ...date, year: e! })
          }}
          w={200}
        />

        <Button
          size="xs"
          onClick={handleExport}
          leftSection={<IconFileExcel size={16} />}
        >
          Export Excel
        </Button>
      </Flex>

      {/* Leave Day Table */}
      <Box style={{ overflowX: 'auto' }}>
        <Table
          striped
          highlightOnHover
          withTableBorder
          withColumnBorders
          mt={'md'}
          miw={1580}
        >
          <Table.Thead>
            <Table.Tr bg={'#228be66b'}>
              <Table.Th ta={'center'} style={{ width: '40px' }}></Table.Th>
              <Table.Th>User</Table.Th>
              {monthInYear.map((d) => {
                const isCurrentMonth =
                  Number(date.year) === currentYear && d.value === currentMonth
                return (
                  <Menu width={200} shadow="md" key={d.value}>
                    <Menu.Target>
                      <Table.Th
                        ta={'center'}
                        style={{
                          cursor: 'pointer',
                          width: '40px',
                          backgroundColor: isCurrentMonth
                            ? '#F2E891'
                            : undefined,
                          color: isCurrentMonth ? '#000' : undefined,
                          fontWeight: isCurrentMonth ? 'bold' : undefined,
                        }}
                      >
                        <span>{d.name}</span>
                      </Table.Th>
                    </Menu.Target>
                  </Menu>
                )
              })}
              <Table.Th ta={'center'} style={{ width: '80px' }}>
                Total
              </Table.Th>
              <Table.Th ta={'center'} style={{ width: '130px' }}>
                Off
              </Table.Th>
              <Table.Th ta={'center'} style={{ width: '80px' }}>
                Remaining
              </Table.Th>
              <Table.Th ta={'center'}>Notes</Table.Th>
              <Table.Th ta={'center'} style={{ width: '50px' }}></Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>
            {data.map((user, index) => {
              let totalDayOff = 0
              let totalDayLeave =
                user.leaveDay.ld_day_total +
                user.leaveDay.ld_additional_day +
                user.leaveDay.ld_special_leave_day
              let ld_day_total = user.leaveDay.ld_day_total
              let ld_additional_day = user.leaveDay.ld_additional_day
              let ld_special_leave_day = user.leaveDay.ld_special_leave_day
              let ld_note = user.leaveDay.ld_note
              let totalOnLeave = 0
              let totalLeaveWithoutPay = 0

              return (
                <Table.Tr key={user.user.id} className={classes.tableTr}>
                  <Table.Td ta={'center'}>{index + 1}</Table.Td>
                  <Table.Td>
                    <Tooltip multiline label={user.user.name}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Avatar
                          size={'md'}
                          mr={'md'}
                          src={
                            import.meta.env.VITE_BACKEND_URL.includes('local')
                              ? import.meta.env.VITE_BACKEND_URL +
                                'storage/' +
                                user.user.avatar
                              : import.meta.env.VITE_BACKEND_URL +
                                'image/storage/' +
                                user.user.avatar
                          }
                        />
                        {user.user.name}
                      </div>
                    </Tooltip>
                  </Table.Td>

                  {/* On leave per month */}
                  {monthInYear.map((d, i) => {
                    let leaveDataByMonth = getDetailLeaveDay(
                      user.monthlyLeaveDays,
                    )

                    const monthData = leaveDataByMonth[d.value]
                    let total = monthData ? monthData.leave_days : 0
                    totalDayOff = totalDayOff + total

                    let onleaveDaysInMonth: MonthlyLeaveDays[] = []
                    let nopayDaysInMonth: MonthlyLeaveDays[] = []
                    let tempDaysInMonth: MonthlyLeaveDays[] = []

                    let totalOnLeaveMonth = 0
                    let totalLeaveWithoutPayMonth = 0
                    let totalTempMonth = 0
                    let usedAdditionalDay = 0

                    user.monthlyLeaveDays
                      .filter((item) => item.month === d.value)
                      .map((item) => {
                        if (item.reason_code === 'ONLEAVE') {
                          totalOnLeaveMonth += Number(item.leave_days)
                          onleaveDaysInMonth.push(item)
                        } else if (item.reason_code === 'LEAVE_WITHOUT_PAY') {
                          totalLeaveWithoutPayMonth += Number(item.leave_days)
                          nopayDaysInMonth.push(item)
                        } else {
                          totalTempMonth += Number(item.leave_days)
                          tempDaysInMonth.push(item)
                        }
                      })

                    // Xử lý hiện thị phép tồn sử dụng
                    let tmpTotalOnleave = totalOnLeave
                    totalOnLeave += totalOnLeaveMonth

                    if (d.value < 4) {
                      if (totalOnLeave < ld_additional_day) {
                        usedAdditionalDay = totalOnLeaveMonth
                        totalOnLeaveMonth = 0
                      } else {
                        usedAdditionalDay = ld_additional_day - tmpTotalOnleave
                        if (usedAdditionalDay >= 0) {
                          totalOnLeaveMonth -= usedAdditionalDay
                        }
                      }
                    }

                    totalLeaveWithoutPay += totalLeaveWithoutPayMonth

                    return (
                      <Table.Td
                        bg={total > 0 ? '#ffb5b5' : ''}
                        opacity={d.value > currentMonth ? 0.4 : 1}
                        key={i}
                        ta={'center'}
                      >
                        <Tooltip
                          multiline
                          label={
                            <Box p={4}>
                              {usedAdditionalDay > 0 && (
                                <Text fw={500} c="violet" size="sm" mb={4}>
                                  Phép tồn: {usedAdditionalDay}
                                </Text>
                              )}

                              {totalOnLeaveMonth > 0 && (
                                <Box>
                                  <Text fw={500} c="teal" size="sm" mb={4}>
                                    Có phép: {totalOnLeaveMonth}
                                  </Text>
                                </Box>
                              )}

                              {totalOnLeaveMonth > 0 ||
                              usedAdditionalDay > 0 ? (
                                <Stack gap={2} pl="md">
                                  {onleaveDaysInMonth?.map(
                                    (itemDay: any, indexDay: number) => (
                                      <Text size="xs" key={indexDay}>
                                        • {itemDay.time_type_name} (
                                        {itemDay.day}/{itemDay.month})
                                      </Text>
                                    ),
                                  )}
                                </Stack>
                              ) : (
                                ''
                              )}

                              {totalLeaveWithoutPayMonth > 0 && (
                                <Box mt={6}>
                                  <Text fw={500} c="red" size="sm" mb={4}>
                                    Không phép: {totalLeaveWithoutPayMonth}
                                  </Text>
                                  <Stack gap={2} pl="md">
                                    {nopayDaysInMonth?.map(
                                      (itemDay: any, indexDay: number) => (
                                        <Text size="xs" key={indexDay}>
                                          • {itemDay.time_type_name} (
                                          {itemDay.day}/{itemDay.month})
                                        </Text>
                                      ),
                                    )}
                                  </Stack>
                                </Box>
                              )}

                              {totalTempMonth > 0 && (
                                <Box mt={6}>
                                  <Group align="center">
                                    <Text fw={500} c="blue" size="sm" mb={3}>
                                      Nghỉ dự kiến: {totalTempMonth}
                                    </Text>

                                    <Tooltip
                                      multiline
                                      opened
                                      position="right"
                                      label={
                                        <Text size="xs">
                                          Ngày nghỉ đã được duyệt, sẽ tính phép
                                          khi đến tháng nghỉ.
                                        </Text>
                                      }
                                      offset={{ mainAxis: 15 }}
                                    >
                                      <Text fw={500} c="blue">
                                        <IconHelpCircle
                                          width={15}
                                          height={15}
                                        />
                                      </Text>
                                    </Tooltip>
                                  </Group>

                                  <Stack gap={2} pl="md">
                                    {tempDaysInMonth?.map(
                                      (itemDay: any, indexDay: number) => (
                                        <Text size="xs" key={indexDay}>
                                          • {itemDay.time_type_name} (
                                          {itemDay.day}/{itemDay.month})
                                        </Text>
                                      ),
                                    )}
                                  </Stack>
                                </Box>
                              )}
                            </Box>
                          }
                        >
                          <Text size="sm">{total === 0 ? '' : total}</Text>
                        </Tooltip>
                      </Table.Td>
                    )
                  })}

                  {/* Total */}
                  <Table.Td ta={'center'} bg="#92e6f2">
                    <Tooltip
                      multiline
                      label={showAllTotal(
                        ld_day_total,
                        ld_additional_day,
                        ld_special_leave_day,
                      )}
                    >
                      <Text size="sm">{totalDayLeave}</Text>
                    </Tooltip>
                  </Table.Td>

                  {/* Off */}
                  <Table.Td
                    onClick={() => {
                      openDetailOff()
                      setDetailOffItem(user)
                    }}
                  >
                    {totalDayOff > 0 ? (
                      <Tooltip
                        multiline
                        label={showAllOff(user.monthlyLeaveDays)}
                      >
                        <Box>
                          <Flex justify="space-between" mb="xs" align="center">
                            <Text size="sm">Có phép: </Text>
                            <Text
                              size="sm"
                              bg="#c3ffc3"
                              fw="bold"
                              p={5}
                              style={{ borderRadius: 5 }}
                            >
                              {totalOnLeave}
                            </Text>
                          </Flex>

                          <Flex justify="space-between" align="center">
                            <Text size="sm">Không phép: </Text>
                            <Text
                              size="sm"
                              bg="#ffb5b5"
                              fw="bold"
                              p={5}
                              style={{ borderRadius: 5 }}
                            >
                              {totalLeaveWithoutPay}
                            </Text>
                          </Flex>
                        </Box>
                      </Tooltip>
                    ) : (
                      ''
                    )}
                  </Table.Td>

                  {/* Remaining */}
                  <Table.Td
                    ta={'center'}
                    bg={totalDayLeave - totalOnLeave > 0 ? '#b5cafb' : ''}
                  >
                    <Text size="sm">{totalDayLeave - totalOnLeave}</Text>
                  </Table.Td>

                  {/* Note */}
                  <Table.Td>
                    <Box
                      style={{
                        display:
                          ld_note === '' || ld_note === null ? 'none' : 'block',
                      }}
                    >
                      <HoverCard width={280} shadow="md">
                        <HoverCard.Target>
                          <Text fz={'sm'}>
                            {ld_note !== null &&
                            ld_note !== '' &&
                            ld_note.length > 25
                              ? ld_note.slice(0, 25) + '...'
                              : ld_note}
                          </Text>
                        </HoverCard.Target>
                        <HoverCard.Dropdown>
                          <Textarea
                            size="sm"
                            autosize
                            value={ld_note}
                            readOnly
                          />
                        </HoverCard.Dropdown>
                      </HoverCard>
                    </Box>
                  </Table.Td>

                  {/* Action */}
                  <Table.Td ta={'center'}>
                    <IconEdit
                      color="green"
                      width={20}
                      style={{ cursor: 'pointer' }}
                      onClick={() => {
                        let totalLeave =
                          user.leaveDay.ld_day_total == 0
                            ? ''
                            : String(user.leaveDay.ld_day_total)
                        let dayAdditional =
                          user.leaveDay.ld_additional_day == 0
                            ? ''
                            : String(user.leaveDay.ld_additional_day)
                        let specialLeave =
                          user.leaveDay.ld_special_leave_day == 0
                            ? ''
                            : String(user.leaveDay.ld_special_leave_day)
                        open1()
                        setCustomAddNotes({
                          ...customAddNotes,
                          id: user.leaveDay.id,
                          note: ld_note,
                          totalLeave: totalLeave,
                          dayAdditional: dayAdditional,
                          specialLeave: specialLeave,
                          user: {
                            id: user.user.id,
                            name: user.user.name,
                          },
                        })
                      }}
                    />
                  </Table.Td>
                </Table.Tr>
              )
            })}
          </Table.Tbody>
        </Table>
      </Box>

      <Modal
        opened={openedDetailOff}
        onClose={() => {
          closeDetailOff()
          setDetailOffItem({
            user: {
              id: 0,
              name: '',
              email: '',
              email_verified_at: '',
              permission: '',
              remember_token: '',
              avatar: '',
              created_at: '',
              updated_at: '',
            },
            leaveDay: {
              id: 0,
              ld_user_id: 0,
              ld_year: 0,
              ld_day_total: 0,
              ld_additional_day: 0,
              ld_special_leave_day: 0,
              ld_note: '',
              created_at: '',
              updated_at: '',
            },
            monthlyLeaveDays: [],
          })
        }}
        title={
          <Stack>
            <Text size="lg" fw={600}>
              Chi tiết nghỉ phép {date.year}
            </Text>
            <Text size="md" c="dimmed">
              Nhân viên:{' '}
              <Text span fw={700} c="dark">
                {detailOffItem.user.name}
              </Text>
            </Text>
          </Stack>
        }
        size="70%"
      >
        <Table striped highlightOnHover withTableBorder withColumnBorders>
          <Table.Thead>
            <Table.Tr>
              <Table.Th>Time</Table.Th>
              <Table.Th>Status</Table.Th>

              {['admin', 'hr'].some((role) =>
                user.user.user.permission
                  .split(',')
                  .map((p: string) => p.trim())
                  .includes(role),
              ) ? (
                <Table.Th>Action</Table.Th>
              ) : (
                ''
              )}
            </Table.Tr>
          </Table.Thead>

          <Table.Tbody>
            {detailOffItem.monthlyLeaveDays
              .slice()
              .reverse()
              .map((item: MonthlyLeaveDays) => {
                return (
                  <Table.Tr key={item.id}>
                    <Table.Td>
                      {item.time_type_name} ({item.day}/{item.month})
                    </Table.Td>
                    <Table.Td>
                      <Badge
                        color={
                          item.reason_code === 'ONLEAVE'
                            ? 'teal'
                            : item.reason_code === 'LEAVE_WITHOUT_PAY'
                            ? 'red'
                            : 'blue'
                        }
                      >
                        {item.reason_name}
                      </Badge>
                    </Table.Td>

                    {['admin', 'hr'].some((role) =>
                      user.user.user.permission
                        .split(',')
                        .map((p: string) => p.trim())
                        .includes(role),
                    ) ? (
                      <Table.Td>
                        {item.reason_code === 'ONLEAVE' ? (
                          <IconRefresh
                            className={classes.deleteIcon}
                            onClick={() => {
                              setIsStatusConfirmOpen(true)
                              setNoteStatus({
                                id: item.id,
                                reason: 'LEAVE_WITHOUT_PAY',
                              })
                            }}
                            title="Chuyển thành không phép"
                            width={20}
                            height={20}
                          />
                        ) : item.reason_code === 'LEAVE_WITHOUT_PAY' ? (
                          <IconRefresh
                            className={classes.editIcon}
                            onClick={() => {
                              setIsStatusConfirmOpen(true)
                              setNoteStatus({
                                id: item.id,
                                reason: 'ONLEAVE',
                              })
                            }}
                            title="Chuyển thành có phép"
                            width={20}
                            height={20}
                          />
                        ) : (
                          ''
                        )}

                        <IconTrash
                          className={classes.deleteIcon}
                          onClick={() => {
                            setNoteToDelete(item)
                            setIsDeleteConfirmOpen(true)
                          }}
                          title="Xóa Note"
                          width={20}
                          height={20}
                        />
                      </Table.Td>
                    ) : (
                      ''
                    )}
                  </Table.Tr>
                )
              })}
          </Table.Tbody>
        </Table>

        {/* Confirm Change Status Note Modal */}
        <Modal
          opened={isStatusConfirmOpen}
          onClose={() => {
            setIsStatusConfirmOpen(false)
            setNoteStatus({
              id: 0,
              reason: '',
            })
          }}
          centered
          size="sm"
          classNames={{
            content: classes.deleteModal,
          }}
        >
          <Text className={classes.deleteModalTitle} c="dark">
            Confirm Change Note Status
          </Text>

          {noteStatus.reason === 'ONLEAVE' ? (
            <Text className={classes.deleteModalContent}>
              This action will change the note status from{' '}
              <Text span c="red" fw="bold">
                Không phép
              </Text>{' '}
              to{' '}
              <Text span c="teal" fw="bold">
                Nghỉ phép
              </Text>
            </Text>
          ) : (
            <Text className={classes.deleteModalContent}>
              This action will change the note status from{' '}
              <Text span c="teal" fw="bold">
                Nghỉ phép
              </Text>{' '}
              to{' '}
              <Text span c="red" fw="bold">
                Không phép
              </Text>
            </Text>
          )}

          <Text className={classes.deleteModalContent}>
            Are you sure you want to proceed?
          </Text>
          <Box className={classes.deleteModalFooter}>
            <Button
              variant="outline"
              onClick={() => {
                setIsStatusConfirmOpen(false)
                setNoteStatus({
                  id: 0,
                  reason: '',
                })
              }}
              disabled={isDisableStatusBtn}
            >
              Cancel
            </Button>
            <Button
              className={classes.deleteButton}
              onClick={updateNote}
              disabled={isDisableStatusBtn}
              bg={noteStatus.reason === 'ONLEAVE' ? 'teal' : 'red'}
            >
              Confirm
            </Button>
          </Box>
        </Modal>

        {/* Confirm Delete Note Modal */}
        <Modal
          opened={isDeleteConfirmOpen}
          onClose={() => {
            setIsDeleteConfirmOpen(false)
            setNoteToDelete(null)
          }}
          centered
          size="sm"
          classNames={{
            content: classes.deleteModal,
          }}
        >
          <Text className={classes.deleteModalTitle}>Confirm Delete</Text>
          <Text className={classes.deleteModalContent}>
            This action will change the ticket status to{' '}
            <strong>Refused</strong> and delete all related notes.
          </Text>
          <Text className={classes.deleteModalContent}>
            Are you sure you want to proceed?
          </Text>
          <Box className={classes.deleteModalFooter}>
            <Button
              variant="outline"
              onClick={() => {
                setIsDeleteConfirmOpen(false)
                setNoteToDelete(null)
              }}
              disabled={isDisableDeleteBtn}
            >
              Cancel
            </Button>
            <Button
              className={classes.deleteButton}
              onClick={handleDeleteNote}
              disabled={isDisableDeleteBtn}
            >
              Delete
            </Button>
          </Box>
        </Modal>
      </Modal>
    </div>
  )
}

export default LeaveManagement
