import { addTracking, deleteTracking, getListTracking, updateTracking } from '@/api/Admin'
import { DataTablePagination } from '@/components/DataTable/DataTable'
import { Xdelete, create, update } from '@/rtk/helpers/CRUD'
import { get } from '@/rtk/helpers/apiService'
import {
  Box,
  Button,
  Dialog,
  Group,
  Modal,
  Select,
  Text
} from '@mantine/core'
import { DateTimePicker } from '@mantine/dates'
import { useForm } from '@mantine/form'
import { IconEdit, IconTrash } from '@tabler/icons-react'
import moment from 'moment'
import { useEffect, useState } from 'react'
import classes from './Tracking.module.css'
import { notifications } from '@mantine/notifications'

type TLog = {
  id: number
  name: string
  status: string
  time_string: Date
}

type TListTracking = {
  data: TLog[]
  users: 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
}

const Tracking = () => {
  const [listTracking, setListTracking] = useState<TListTracking>({
    data: [],
    users: [],
  })
  const [action, setAction] = useState('')
  const [item, setItem] = useState({ id: 0 })
  const [activeBtn, setActiveBtn] = useState(false)
  const [disableBtn, setDisableBtn] = useState(false)
  const columns = [
    {
      name: 'id',
      size: '5%',
      header: 'ID',
    },
    {
      name: 'name',
      size: '30%',
      header: 'Name',
    },
    {
      name: 'time_string',
      size: '20%',
      header: 'Time',
    },
    {
      name: 'status',
      size: '20%',
      header: 'Status',
    },
    {
      name: 'created_at',
      size: '15%',
      header: 'Created At',
      render: (row: any) => {
        return moment(row.created_at).format('YYYY/MM/DD - HH:mm:ss')
      },
    },
    {
      name: '#',
      size: '10%',
      header: 'Action',
      render: (row: any) => {
        return (
          <Box className={classes.optionIcon}>
            <IconTrash
              className={classes.deleteIcon}
              onClick={() => {
                setAction('delete')
                setItem(row)
              }}
              width={20}
              height={20}
            />
            <IconEdit
              className={classes.editIcon}
              onClick={() => {
                setAction('edit')
                console.log(row)
                form.setValues(row)
              }}
              width={20}
              height={20}
            />
          </Box>
        )
      },
    },
  ]

  const filterInfo = [
    {
      key: 'name',
      name: 'Name',
      type: 'text',
    },
    {
      key: 'status',
      name: 'Status',
      type: 'text',
    },
    {
      key: 'time_string',
      name: 'Time',
      type: 'text',
    },
  ]

  const form = useForm({
    initialValues: {
      id: 0,
      name: '',
      time_string: new Date(),
      status: '',
      created_at: '',
    },
  })

  const getAllTracking = async () => {
    try {
      const searchParams = new URLSearchParams(window.location.search)
      const params = {}

      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(getListTracking, params)
      if (res.status) {
        setListTracking(res)
      }
    } catch (error:any) {
      notifications.show({
        title: 'Error',
        message: error.message??error,
        color: 'red',
      })
    }
  }

  const handleCreate = async (values: TLog) => {
    try {
      const res = await create(addTracking, {
        status: values.status,
        name: values.name,
        time_string: moment(values.time_string).format('YYYY-MM-DD HH:mm:ss'),
        created_at: values.time_string
      }, getAllTracking)
      if (res === true) {
        setAction('')
        form.reset()
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleUpdate = async (values: TLog) => {
    try {
      const res = await update(updateTracking, {
        status: values.status,
        name: values.name,
        time_string: moment(values.time_string).format('YYYY-MM-DD HH:mm:ss'),
        created_at: new Date(values.time_string),
        id: values.id
      }, getAllTracking)
      if (res === true) {
        setAction('')
        form.reset()
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleDelete = async (id: number) => {
    try {
      await Xdelete(deleteTracking, { id: id }, getAllTracking)
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    // if (listTracking.data.length === 0) {
      getAllTracking()
    // }
    // setInterval(() => {
      // if (window.location.pathname.includes('tracking')) {
      //   getAllTracking()
      // }
    // }, 60000)
  }, [])
  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Tracking
        </h3>
        <Button
          m={5}
          onClick={() => {
            setAction('add')
            form.reset()
          }}
        >
          + Add
        </Button>
      </div>
      <Box p={20}>
        {listTracking.data.length > 0 && (
          <DataTablePagination
            filterInfo={filterInfo}
            data={listTracking}
            columns={columns}
            searchInput
            size=""
          />
        )}
      </Box>

      {/* Add/Edit User modal */}
      <Modal
        opened={action === 'add' || action === 'edit'}
        onClose={() => {
          setAction('')
          form.reset()
        }}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            {action === 'add' ? 'Add log' : 'Update log'}
          </Text>
        }
      >
        <form
          onSubmit={form.onSubmit(async (values) => {
            setDisableBtn(true)
            action === 'edit'
              ? await handleUpdate(values)
              : await handleCreate(values)
            setDisableBtn(false)
          })}
        >
          <Box pl={'md'} pr={'md'}>
            <Select
              label={'Name'}
              placeholder="Jonh"
              maxLength={255}
              required
              data={listTracking.users.map((i: User) => i.name)}
              value={form.values.name}
              error={form.errors.name}
              onChange={(e) => form.setFieldValue('name', e!)}
            />

            <Select
              label={'Status'}
              required
              data={['check in', 'check out']}
              value={form.values.status}
              error={form.errors.status}
              onChange={(e) => form.setFieldValue('status', e!)}
            />
            <DateTimePicker
              label={'Time'}
              value={new Date(form.values.time_string)}
              onChange={(e) => form.setFieldValue('time_string', e!)}
            ></DateTimePicker>

            <Box ta={'center'}>
              {action === 'add' ? (
                <Button
                  mt={'lg'}
                  bg={'green'}
                  type="submit"
                  disabled={disableBtn}
                >
                  Create
                </Button>
              ) : (
                <Button
                  mt={'lg'}
                  bg={'green'}
                  type="submit"
                  disabled={disableBtn}
                >
                  Save
                </Button>
              )}
            </Box>
          </Box>
        </form>
      </Modal>

      <Dialog
        className={classes.dialog}
        opened={action === 'delete'}
        withCloseButton
        onClose={() => setAction('')}
        size="lg"
        radius="md"
        position={{ top: 30, right: 10 }}
      >
        <Text className={classes.dialogText} size="sm" mb="xs" fw={500}>
          Do you want to delete this record?
          <Group justify="center" m={10}>
            <Button
              disabled={activeBtn}
              fw={700}
              size="xs"
              variant="light"
              onClick={async () => {
                setActiveBtn(true)
                await handleDelete(item.id)
                setActiveBtn(false)
                setAction('')
              }}
            >
              Yes
            </Button>
            <Button
              fw={700}
              size="xs"
              variant="light"
              onClick={() => setAction('')}
            >
              Cancel
            </Button>
          </Group>
        </Text>
      </Dialog>
    </div>
  )
}

export default Tracking
