import { getListMaster, getTickets, handleTicket } from '@/api/Admin'
import { DataTablePagination } from '@/components/DataTable/DataTable'
import { create } from '@/rtk/helpers/CRUD'
import { get } from '@/rtk/helpers/apiService'
import {
  Badge,
  Box,
  Button,
  HoverCard,
  Modal,
  Select,
  Text,
  Textarea,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { IconCheckbox, IconSquareXFilled } from '@tabler/icons-react'
import moment from 'moment'
import { useEffect, useState } from 'react'
import classes from './TicketsManagement.module.css'
import { DateInput } from '@mantine/dates'

type TTickets = {
  ticket_id: number
  admin_note: string
  action: string
}

type TListTickets = {
  data: User[]
}

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

interface FilterInfo {
  key: string
  name: string
  type: string
}

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

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

interface FilterInfo {
  key: string
  name: string
  type: string
}

const TicketsManagement = () => {
  const [listTickets, setListTiskets] = useState<TListTickets>({
    data: [],
  })
  const [action, setAction] = useState('')
  const [item, setItem] = useState({
    id: 0,
    start_date: '',
    start_period: '',
    end_date: '',
    end_period: '',
    reason: '',
    type: '',
  })
  const [disableBtn, setDisableBtn] = useState(false)
  const [filter, setFilter] = useState({
    typeReason: '',
    statusFilter: '',
  })
  const [dataTimeType, setDataTimeType] = useState<DataTimeType[]>([])
  const [dataReason, setDataReason] = useState<DataReason[]>([])

  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 columns = [
    {
      name: 'id',
      size: '3%',
      header: 'ID',
    },
    {
      name: 'user_name',
      size: '17%',
      header: 'User',
    },
    {
      name: 'start_date',
      size: '26%',
      header: 'Time',
      render: (row: any) => {
        return (
          <Text fz={'sm'}>
            {row.startPeriodName}
            {' ('}
            {moment(row.start_date).format('DD/MM/YYYY')}
            {')'} - {row.endPeriodName}
            {' ('}
            {moment(row.end_date).format('DD/MM/YYYY')}
            {')'}
          </Text>
        )
      },
    },
    {
      name: 'typeReasonName',
      size: '10%',
      header: 'Reason',
    },
    {
      name: 'reason',
      size: '15%',
      header: 'Notes',
      render: (row: any) => {
        return (
          <HoverCard width={280} shadow="md">
            <HoverCard.Target>
              <Text fz={'sm'}>
                {row.reason !== null &&
                row.reason !== '' &&
                row.reason.length > 25
                  ? row.reason.slice(0, 25) + '...'
                  : row.reason}
              </Text>
            </HoverCard.Target>
            <HoverCard.Dropdown>
              <Textarea size="sm" autosize>
                {row.reason}
              </Textarea>
            </HoverCard.Dropdown>
          </HoverCard>
        )
      },
    },
    {
      name: 'status',
      size: '5%',
      header: 'Status',
      render: (row: any) => {
        switch (row.status) {
          case 'WAITING':
            return <Badge color="blue">Waiting</Badge>
          case 'CONFIRMED':
            return <Badge color="green">Confirmed</Badge>
          case 'REFUSED':
            return <Badge color="red">Refused</Badge>
          default:
            return null
        }
      },
    },
    {
      name: 'admin_note',
      size: '15%',
      header: 'Admin Notes',
      render: (row: any) => {
        return (
          <HoverCard width={280} shadow="md">
            <HoverCard.Target>
              <Text fz={'sm'}>
                {row.admin_note !== null &&
                row.admin_note !== '' &&
                row.admin_note.length > 25
                  ? row.admin_note.slice(0, 25) + '...'
                  : row.admin_note}
              </Text>
            </HoverCard.Target>
            <HoverCard.Dropdown>
              <Textarea size="sm" autosize>
                {row.admin_note}
              </Textarea>
            </HoverCard.Dropdown>
          </HoverCard>
        )
      },
    },
    {
      name: 'updated_by',
      size: '10%',
      header: 'Updated By',
    },
    {
      name: '#',
      size: '5%',
      header: 'Action',
      render: (row: any) => {
        return row.status === 'WAITING' ? (
          <Box className={classes.optionIcon}>
            <IconCheckbox
              className={classes.editIcon}
              onClick={() => {
                setAction('confirm')
                setItem(row)
                form.reset()
              }}
              width={20}
              height={20}
            />
            <IconSquareXFilled
              className={classes.deleteIcon}
              onClick={() => {
                setAction('refuse')
                setItem(row)
                form.reset()
              }}
              width={20}
              height={20}
            />
          </Box>
        ) : null
      },
    },
  ]

  const filterInfo: FilterInfo[] = [
    // {
    //   key: 'users.name',
    //   name: 'User',
    //   type: 'text',
    // },
    // {
    //   key: 'start_date',
    //   name: 'From Date',
    //   type: 'date',
    // },
    // {
    //   key: 'startPeriod.c_name',
    //   name: 'Start Period',
    //   type: 'text',
    // },
    // {
    //   key: 'end_date',
    //   name: 'End Date',
    //   type: 'date',
    // },
    // {
    //   key: 'endPeriod.c_name',
    //   name: 'End Period',
    //   type: 'text',
    // },
    // {
    //   key: 'typeReason.c_name',
    //   name: 'Reason',
    //   type: 'text',
    // },
    // {
    //   key: 'status',
    //   name: 'Status',
    //   type: 'text',
    // }
  ]

  const getAllTickets = async () => {
    try {
      const searchParams = new URLSearchParams(window.location.search)

      const params = {
        typeReason: filter.typeReason,
        statusFilter: filter.statusFilter,
      }

      for (const [key, value] of searchParams.entries()) {
        if (key === 'page' && value === '') {
          Object.assign(params, { [`${key}`]: 1 })
        } else {
          Object.assign(params, { [`${key}`]: value })
        }
      }

      const res = await get(getTickets, params)
      if (res.status) {
        setListTiskets(res)
      }
    } catch (error: any) {
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    }
  }

  const handleSave = async (values: TTickets) => {
    try {
      const res = await create(
        handleTicket,
        {
          ticket_id: item.id,
          action: action,
          admin_note: values.admin_note,
        },
        getAllTickets,
      )
      if (res === true) {
        setAction('')
        form.reset()
      }
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    getAllTickets()
  }, [filter])

  const form = useForm({
    initialValues: {
      ticket_id: 0,
      action: '',
      admin_note: '',
    },
  })

  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Tickets Management
        </h3>
      </div>
      <Box display={'flex'} p={15}>
        <Box style={{ display: 'flex', flexFlow: 'column' }} w={'40%'}>
          <Box w="100%" display={'flex'}>
            <Select
              clearable
              w="50%"
              value={filter.typeReason}
              size="xs"
              label="Reason"
              data={dataReason.map((user) => ({
                value: user.c_code.toString(),
                label: user.c_name,
              }))}
              onChange={(e) => {
                setFilter({ ...filter, typeReason: e! })
              }}
            ></Select>
            <Select
              clearable
              w="50%"
              value={filter.statusFilter}
              size="xs"
              ml={'sm'}
              label="Status"
              data={[
                { value: 'WAITING', label: 'WAITING' },
                { value: 'CONFIRMED', label: 'CONFIRMED' },
                { value: 'REFUSED', label: 'REFUSED' },
              ]}
              onChange={(e) => {
                setFilter({ ...filter, statusFilter: e! })
              }}
            ></Select>
          </Box>
        </Box>
      </Box>
      <Box>
        {listTickets.data.length > 0 && (
          <DataTablePagination
            filterInfo={filterInfo}
            data={listTickets}
            columns={columns}
            searchInput
            size=""
          />
        )}
      </Box>

      <Modal
        opened={action === 'confirm' || action === 'refuse'}
        onClose={() => {
          setAction('')
          form.reset()
        }}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            {action === 'confirm' ? 'Confirm Ticket' : 'Refuse Ticket'}
          </Text>
        }
      >
        <form
          onSubmit={form.onSubmit(async (values) => {
            setDisableBtn(true)
            await handleSave(values)
            setDisableBtn(false)
          })}
        >
          <Box pl={'md'} pr={'md'}>
            <Box display={'flex'}>
              <Box style={{ display: 'flex', flexFlow: 'column' }} w={'40%'}>
                <DateInput
                  variant="unstyled"
                  readOnly
                  mb={'md'}
                  label={'From Date'}
                  value={new Date(item.start_date)}
                  valueFormat="DD/MM/YYYY"
                ></DateInput>

                <Select
                  style={{ border: 'none' }}
                  variant="unstyled"
                  mb={'md'}
                  label={'Start Period'}
                  data={dataTimeType.map((item) => {
                    return { value: item.c_code.toString(), label: item.c_name }
                  })}
                  value={item.start_period}
                  error={form.errors.start_period}
                  onChange={(e) => form.setFieldValue('start_period', e!)}
                />

                <Select
                  variant="unstyled"
                  mb={'md'}
                  searchable
                  label="Type"
                  data={dataReason.map((user) => ({
                    value: user.c_code.toString(),
                    label: user.c_name,
                  }))}
                  value={item.type}
                  error={form.errors.type}
                  onChange={(e) => form.setFieldValue('type', e!)}
                />
              </Box>
              <Box
                style={{ display: 'flex', flexFlow: 'column' }}
                w={'20%'}
              ></Box>
              <Box style={{ display: 'flex', flexFlow: 'column' }} w={'40%'}>
                <DateInput
                  variant="unstyled"
                  mb={'md'}
                  label={'End Date'}
                  value={new Date(item.end_date)}
                  valueFormat="DD/MM/YYYY"
                  onChange={(e) => form.setFieldValue('end_date', e!)}
                ></DateInput>
                <Select
                  variant="unstyled"
                  mb={'md'}
                  label={'End Period'}
                  data={dataTimeType.map((item) => {
                    return { value: item.c_code.toString(), label: item.c_name }
                  })}
                  value={item.end_period}
                  error={form.errors.end_period}
                  onChange={(e) => form.setFieldValue('end_period', e!)}
                />
              </Box>
            </Box>

            <Textarea
              label="Reason"
              variant="unstyled"
              value={item.reason}
              onChange={(e) => form.setFieldValue('reason', e.target.value)}
            />

            <Textarea
              label="Admin Notes"
              required
              value={form.values.admin_note}
              onChange={(e) => form.setFieldValue('admin_note', e.target.value)}
            />
            <Box ta={'center'}>
              <Button
                mt={'lg'}
                bg={'green'}
                type="submit"
                disabled={disableBtn}
              >
                Save
              </Button>
            </Box>
          </Box>
        </form>
      </Modal>
    </div>
  )
}

export default TicketsManagement
