import { useEffect, useState } from 'react'
import {
  Box,
  Button,
  Dialog,
  Flex,
  Group,
  Loader,
  Modal,
  Select,
  Tabs,
  Text,
  TextInput,
} from '@mantine/core'
import classes from './OrganizationSettings.module.css'
import DataTableAll from '@/components/DataTable/DataTable'
import { get, post } from '@/rtk/helpers/apiService'
import { notifications } from '@mantine/notifications'
import { createTechnical, deleteTechnical, listTechnical } from '@/api/Admin'
import { useForm } from '@mantine/form'
import { Xdelete } from '@/rtk/helpers/CRUD'
import moment from 'moment'

function OrganizationSettings() {
  const [activeTab, setActiveTab] = useState<string | null>('technical')

  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Organization Settings
        </h3>
      </div>

      <Box w="100%" display={'flex'} mt={15} ml={10}>
        <Tabs w="100%" value={activeTab} onChange={setActiveTab}>
          <Tabs.List>
            <Tabs.Tab value="technical">Technical Setting</Tabs.Tab>
            <Tabs.Tab value="second">Setting 2</Tabs.Tab>
            <Tabs.Tab value="third">Setting 3</Tabs.Tab>
          </Tabs.List>

          <Tabs.Panel value="technical" pt="xs">
            <TechnicalSettingTab />
          </Tabs.Panel>

          <Tabs.Panel value="second" pt="xs">
            Setting 2
          </Tabs.Panel>

          <Tabs.Panel value="third" pt="xs">
            Setting 3
          </Tabs.Panel>
        </Tabs>
      </Box>
    </div>
  )
}

interface DataTechnical {
  id: number
  name: string
  level: number
  point: number
  updated_at: string
}

const TechnicalSettingTab = () => {
  const [dataTechnical, setDataTechnical] = useState<DataTechnical[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [addTechnicalOpen, setAddTechnicalOpen] = useState(false)
  const [deleteTechnicalOpen, setDeleteTechnicalOpen] = useState(false)
  const [selectedId, setSelectedId] = useState(0)

  const form = useForm({
    initialValues: {
      name: '',
      level: '',
    },
  })

  useEffect(() => {
    const fetchData = async () => {
      await getListTechnical()
    }
    fetchData()
  }, [])

  const columns = [
    {
      name: 'level',
      size: '5%',
      header: 'Level',
      render: (row: any) => {
        return (
          <Box
            style={
              row?.level
                ? row?.level === 1
                  ? { backgroundColor: '#d9d2e9' }
                  : row?.level === 2
                  ? { backgroundColor: '#ffd966' }
                  : { backgroundColor: '#cfe2f3' }
                : { backgroundColor: '' }
            }
            fw={500}
            ta="center"
            p={4}
          >
            {row?.level ? row.level : ''}
          </Box>
        )
      },
    },
    {
      name: 'name',
      size: '40%',
      header: 'Name',
    },
    {
      name: 'created_at',
      size: '40%',
      header: 'Created at',
      render: (row: any) => {
        if (row?.created_at) {
          return (
            <Box>{moment(row?.created_at).format('HH:mm:ss DD/MM/YYYY')}</Box>
          )
        }
      },
    },
    {
      name: 'action',
      size: '15%',
      header: 'Action',
      render: (row: any) => {
        return (
          <Flex justify="center">
            <Button
              color="red"
              onClick={() => {
                setDeleteTechnicalOpen(true)
                setSelectedId(row?.id)
              }}
            >
              Delete
            </Button>
          </Flex>
        )
      },
    },
  ]

  const getListTechnical = async () => {
    try {
      setIsLoading(true)
      const params = {}
      const res = await get(listTechnical, params)
      if (res.status) {
        setDataTechnical(res.data)
      }
    } catch (error: any) {
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    } finally {
      setIsLoading(false)
    }

    return []
  }

  const handleCreate = async (values: any) => {
    try {
      const { id, ...data } = values
      const res = await post(createTechnical, data)
      if (res.status === true) {
        setAddTechnicalOpen(false)
        form.reset()
        await getListTechnical()

        notifications.show({
          title: 'Success',
          message: res.message,
          color: 'green',
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  const handleDelete = async (id: number) => {
    try {
      await Xdelete(deleteTechnical, { id: id }, getListTechnical)
      setSelectedId(0)
      setDeleteTechnicalOpen(false)
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <>
      <Box mt={'md'} p={16}>
        <Text fw={500}>Note: </Text>

        <Flex gap={8}>
          <Box p={8} bg="#d9d2e9">
            <span style={{ fontWeight: 500 }}>Level 1:</span> 3-12 Month
          </Box>
          <Box p={8} bg="#ffd966">
            <span style={{ fontWeight: 500 }}>Level 2:</span> 3-5 Year
          </Box>
          <Box p={8} bg="#cfe2f3">
            <span style={{ fontWeight: 500 }}>Level 3:</span> 5 -8 Year
          </Box>
        </Flex>
      </Box>

      <Box mt={'md'}>
        {isLoading ? (
          <Box
            style={{
              marginTop: '10%',
              textAlign: 'center',
              display: 'block',
            }}
          >
            <Loader size={'sm'} color="green" type="bars" m={'0 auto'} />
            <Text fw={600} c={'gray'} mt={8}>
              Loading Technical...
            </Text>
          </Box>
        ) : (
          <DataTableAll
            data={dataTechnical}
            columns={columns}
            size=""
            searchInput
            infoTotal={
              <Button onClick={() => setAddTechnicalOpen(true)}>+ Add</Button>
            }
          />
        )}
      </Box>

      <Modal
        opened={addTechnicalOpen}
        onClose={() => {
          setAddTechnicalOpen(false)
          form.reset()
        }}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            Add Technical
          </Text>
        }
      >
        <form
          onSubmit={form.onSubmit(async (values) => {
            await handleCreate(values)
          })}
        >
          <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)}
              required
            />

            <Select
              label="Level"
              placeholder="Select level"
              data={['1', '2', '3']}
              value={form.values.level}
              error={form.errors.level}
              onChange={(e) => form.setFieldValue('level', e!)}
            />

            <Box ta={'center'}>
              <Button mt={'lg'} bg={'green'} type="submit">
                Create
              </Button>
            </Box>
          </Box>
        </form>
      </Modal>

      <Dialog
        opened={deleteTechnicalOpen}
        className={classes.dialog}
        withCloseButton
        onClose={() => setDeleteTechnicalOpen(false)}
        size="lg"
        radius="md"
        position={{ top: 30, right: 10 }}
      >
        <Box className={classes.dialogText} size="sm" mb="xs" fw={500}>
          Do you want to delete this technical?
          <Group justify="center" m={10}>
            <Button
              fw={700}
              size="xs"
              variant="filled"
              color="red"
              onClick={async () => handleDelete(selectedId)}
            >
              Yes
            </Button>
            <Button
              fw={700}
              size="xs"
              variant="filled"
              color="gray"
              onClick={() => setDeleteTechnicalOpen(false)}
            >
              Cancel
            </Button>
          </Group>
        </Box>
      </Dialog>
    </>
  )
}

export default OrganizationSettings
