import { createOrUpdateUser, deleteUser, getAllUsers } from '@/api/Admin'
import { ButtonCopy } from '@/components/CopyClipboard/CopyClipboard'
import DataTableAll from '@/components/DataTable/DataTable'
import { get, post } from '@/rtk/helpers/apiService'
import { update, Xdelete } from '@/rtk/helpers/CRUD'
import { TUser } from '@/variables/types'
import {
  Badge,
  Box,
  Button,
  Code,
  Dialog,
  Group,
  Modal,
  MultiSelect,
  Text,
  TextInput
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { IconEdit, IconX } from '@tabler/icons-react'
import { useEffect, useState } from 'react'
import classes from './UsersManagement.module.css'
const UsersManagement = () => {
  const [users, setUsers] = useState<TUser[]>([])
  const [action, setAction] = useState('')
  const [activeBtn, setActiveBtn] = useState(false)
  const [item, setItem] = useState({ id: 0 })
  const [disableBtn, setDisableBtn] = useState(false)
  const [info, setInfo] = useState('')
  const columns = [
    {
      name: 'id',
      size: '3%',
      header: 'ID',
    },
    {
      name: 'name',
      size: '17%',
      header: 'Name',
    },
    {
      name: 'email',
      size: '26%',
      header: 'Email',
    },
    {
      name: 'permission',
      size: '10%',
      header: 'Permission',
      render: (row: TUser) => {
        if (row.permission.includes(',')) {
          return row?.permission?.split(',').map((p) => {
            return <Badge mr={'sm'}>{p}</Badge>
          })
        } else {
          return <Badge>{row.permission}</Badge>
        }
      },
    },
    {
      name: '#',
      size: '5%',
      header: 'Action',
      render: (row: TUser) => {
        return (
          <Box className={classes.optionIcon}>
            <IconEdit
              className={classes.editIcon}
              onClick={() => {
                setAction('edit')
                form.setValues(row)
              }}
              width={20}
              height={20}
            />
            <IconX
              className={classes.deleteIcon}
              onClick={() => {
                setAction('delete')
                setItem(row)
              }}
              width={20}
              height={20}
            />
          </Box>
        )
      },
    },
  ]

  const form = useForm({
    initialValues: {
      id: 0,
      name: '',
      email: '',
      permission: '',
    },
  })

  const getAll = async () => {
    try {
      const res = await get(getAllUsers)
      if (res.status) {
        setUsers(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleCreate = async (values: TUser) => {
    try {
      const { id, ...data } = values
      const res = await post(createOrUpdateUser, data)
      if (res.status === true) {
        setAction('review')
        form.reset()
        getAll()
        setInfo(JSON.stringify(res.data, null, 2))
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleUpdate = async (values: TUser) => {
    try {
      const res = await update(createOrUpdateUser, values, getAll)
      if (res === true) {
        setAction('')
        form.reset()
      }
    } catch (error) {
      console.log(error)
    }
  }

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

  useEffect(() => {
    getAll()
  }, [])

  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Users Management
        </h3>
        <Button
          onClick={() => {
            setAction('add')
            form.reset()
          }}
        >
          + Add
        </Button>
      </div>
      <Box mt={'md'}>
        <DataTableAll data={users} columns={columns} size="" searchInput />
      </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 User' : 'Update User'}
          </Text>
        }
      >
        <form
          onSubmit={form.onSubmit(async (values) => {
            setDisableBtn(true)
            action === 'edit'
              ? await handleUpdate(values)
              : await handleCreate(values)
            setDisableBtn(false)
          })}
        >
          <Box pl={'md'} pr={'md'}>
            <TextInput
              label="Name"
              mb={'md'}
              value={form.values.name}
              error={form.errors.name}
              onChange={(e) => form.setFieldValue('name', e.target.value)}
            />

            <TextInput
              label="Email"
              mb={'md'}
              value={form.values.email}
              error={form.errors.email}
              onChange={(e) => form.setFieldValue('email', e.target.value)}
            />

            <MultiSelect
              label={'Permission(s)'}
              required
              data={['staff', 'admin', 'hr']}
              value={
                typeof form.values.permission === 'string'
                  ? form.values.permission
                      .split(',')
                      .filter((p) => p.trim() !== '')
                  : form.values.permission
              }
              error={form.errors.permisstion}
              onChange={(e) =>
                form.setFieldValue(
                  'permission',
                  e!.filter((p) => p.trim() !== '').join(','),
                )
              }
            />
            <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>

      <Modal
        opened={action === 'review'}
        onClose={() => {
          setAction('')
        }}
        size={'lg'}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            Information to get started
          </Text>
        }
      >
        <Text c={'red'} fz={'sm'} fw={700}>
          !! Important note: Please remind user to change password after logging
          in !!
        </Text>
        <Code block>
          <Box ta={'right'}>
            <ButtonCopy value={info} />
          </Box>
          {info}
        </Code>
      </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 user?
          <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 UsersManagement
