import {
  createTestCase,
  deleteTestCase,
  getAllBoardByIdProject,
  getAllProject,
  getAllSprintByIdBoard,
  getAllTestCase,
} from '@/api/Admin'
import { get, post } from '@/rtk/helpers/apiService'
import { Xdelete } from '@/rtk/helpers/CRUD'
import {
  Box,
  Button,
  Dialog,
  Group,
  Loader,
  Modal,
  Select,
  Table,
  Text,
  Textarea,
  TextInput,
  Title,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { notifications } from '@mantine/notifications'
import { IconInfoSquare, IconSquareXFilled } from '@tabler/icons-react'
import { useEffect, useState } from 'react'
import classes from './TestReport.module.css'

type DataProject = {
  id: number
  name: string
}
type DataSprint = {
  id: number
  name: string
  startDate: string
  endDate: string
  completeDate: string
}

type DataTestCases = {
  id?: number
  name: string
  position: string
  input: string
  expect_output: string
  actual_output: string
  issue_id_on_jira: string
  bug_id_on_jira: string
  note: string
  created_by?: string
  project_id?: string
  sprint_name?: string
  start_date?: string
  end_date?: string
  complete_date?: string
}

const TestReport = () => {
  const [action, setAction] = useState('')
  const [activeBtn, setActiveBtn] = useState(false)
  const [item, setItem] = useState<DataTestCases>({
    id: 0,
    name: '',
    position: '',
    input: '',
    expect_output: '',
    actual_output: '',
    issue_id_on_jira: '',
    bug_id_on_jira: '',
    note: '',
    created_by: '',
  })
  const [disableBtn, setDisableBtn] = useState(false)
  const [loading, setLoading] = useState(false)
  const [loadingProject, setLoadingProject] = useState(true)
  const [isDisabledSprint, setIsDisabledSprint] = useState(true)
  const [infoBoard, setInfoBoard] = useState('')
  const [filter, setFilter] = useState({
    project: '',
    sprint: '',
  })
  const [dataProject, setDataProject] = useState<DataProject[]>([])
  const [dataSprint, setDataSprint] = useState<DataSprint[]>([])

  const [dataListTestCases, setDataListTestCases] = useState<any[]>([])

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

  const getBoardByIdProject = async (id: string) => {
    try {
      const params = {}
      const res = await get(`${getAllBoardByIdProject}?id=${id}`, params)
      if (res.status) {
        return res.data
      }
    } catch (error: any) {
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    }
    return []
  }

  const getListDataSprint = async (id: string) => {
    try {
      const params = {}
      const res = await get(`${getAllSprintByIdBoard}?id=${id}`, params)
      if (res.status) {
        return res.data
      }
    } catch (error: any) {
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    }
    return []
  }

  const getListTestCase = async (id: string) => {
    try {
      const params = {}
      const res = await get(`${getAllTestCase}/${id}`, 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 result = await getListDataProject()
      setDataProject(result ?? [])
      setLoadingProject(false)
    }
    fetchData()
  }, [])

  useEffect(() => {
    if (filter.project) {
      setLoading(true)
      const fetchData = async () => {
        const result = await getBoardByIdProject(filter.project)
        if (result.values[0]) {
          setInfoBoard(result.values[0].id ?? '')
          setLoading(false)
        }
      }
      fetchData()
    } else {
      setIsDisabledSprint(true)
      setDataSprint([])
      setInfoBoard('')
    }
  }, [filter.project])

  useEffect(() => {
    if (infoBoard != '') {
      const fetchData = async () => {
        const result = await getListDataSprint(infoBoard)
        if (result.values) {
          setDataSprint(
            result.values.filter(
              (item: any) =>
                typeof item.completeDate !== 'undefined' &&
                item.completeDate !== '',
            ) ?? [],
          )
          setIsDisabledSprint(false)
        }
      }
      fetchData()
    }
  }, [infoBoard])

  useEffect(() => {
    setLoading(true)
    setDataListTestCases([])
    if (filter.sprint) {
      const fetchData = async () => {
        const result = await getListTestCase(filter.sprint)
        if (result) {
          setDataListTestCases(result ?? [])
          setLoading(false)
        }
      }
      fetchData()
    } else {
      setLoading(false)
    }
  }, [filter])

  const form = useForm({
    initialValues: {
      name: '',
      position: '',
      input: '',
      expect_output: '',
      actual_output: '',
      issue_id_on_jira: '',
      bug_id_on_jira: '',
      note: '',
    },
  })

  const handleCreate = async (values: DataTestCases) => {
    try {
      const dataSprintSearch = dataSprint.find(
        (item: DataSprint) => item.id == Number(filter.sprint),
      )
      const { ...data } = values
      data.sprint_name = dataSprintSearch?.name
      data.project_id = filter.project
      data.start_date = dataSprintSearch?.startDate
      data.end_date = dataSprintSearch?.endDate
      data.complete_date = dataSprintSearch?.completeDate
      delete data.id

      const res = await post(`${createTestCase}/${filter.sprint}`, data)
      if (res.status === true) {
        setAction('')
        form.reset()
        getAll()
        notifications.show({
          title: 'Success',
          message: 'Add success',
          color: 'green',
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  const getAll = async () => {
    const fetchData = async () => {
      const result = await getListTestCase(filter.sprint)
      if (result) {
        setDataListTestCases(result ?? [])
        setLoading(false)
      }
    }
    fetchData()
  }

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

  const rowStyle = {
    height: '30px', // Điều chỉnh chiều cao hàng
  }

  return (
    <div>
      <div className={classes.title}>
        <h3>
          <Text>Admin/</Text>
          Test Report
        </h3>
        <Button
          onClick={() => {
            setAction('add')
            form.reset()
          }}
          style={{
            display: filter.sprint ? 'block' : 'none',
          }}
        >
          + Add
        </Button>
      </div>
      <Box
        style={{
          marginTop: '20%',
          textAlign: 'center',
          display: loadingProject ? 'block' : 'none',
          // display: 'none',
        }}
      >
        <Loader size={'sm'} color="green" type="bars" m={'0 auto'} />
        <Text fw={600} c={'gray'}>
          Loading . . .
        </Text>
      </Box>
      <Box display={'flex'} p={15}>
        <Box
          style={[
            {
              display: 'flex',
              flexFlow: 'column',
            },
            loadingProject ? { display: 'none' } : {},
          ]}
          w={'50%'}
        >
          <Box w="100%" display={'flex'}>
            <Text
              mr={'xs'}
              style={{ alignContent: 'center' }}
              fw={600}
              size={'md'}
            >
              Project:
            </Text>
            <Select
              searchable
              clearable
              w="60%"
              value={filter.project || null}
              size="xs"
              label=""
              data={dataProject.map((project) => ({
                value: project.id.toString(),
                label: project.name,
              }))}
              onChange={(e) => {
                if (e === null) {
                  // Clear project
                  setFilter({ project: '', sprint: '' }) // Clear cả project và sprint
                  setDataSprint([]) // Reset dataSprint để không hiển thị các giá trị sprint cũ
                  setInfoBoard('')
                  setIsDisabledSprint(true) // Vô hiệu hóa Select của sprint
                } else {
                  // Chọn project mới
                  setFilter({ project: e, sprint: '' }) // Clear sprint khi chọn project mới
                  setDataSprint([]) // Xóa dữ liệu sprint khi đổi project
                  setIsDisabledSprint(true) // Vô hiệu hóa lại Select sprint cho đến khi load xong
                }
              }}
            ></Select>
            <Text
              ml={'lg'}
              style={{ alignContent: 'center' }}
              fw={600}
              size={'md'}
            >
              Sprint:
            </Text>
            <Select
              disabled={isDisabledSprint}
              searchable
              clearable
              w="40%"
              value={filter.sprint || null} // Đảm bảo rằng nếu filter.sprint trống, thì giá trị sẽ là null
              size="xs"
              ml={'sm'}
              label=""
              data={dataSprint.map((sprint) => ({
                value: sprint.id.toString(),
                label: sprint.name,
              }))}
              onChange={(e) => {
                setFilter({ ...filter, sprint: e! })
              }}
            ></Select>
          </Box>
        </Box>
        <Box
          style={{
            display: 'flex',
            flexFlow: 'column',
            // backgroundColor: 'yellow',
            alignSelf: 'center',
          }}
          w={'50%'}
        >
          <Text style={{ textAlign: 'center' }} fw={600}>
            {dataProject.find((item: any) => item.id === filter.project)?.name}{' '}
            {dataSprint.find((item: any) => item.id === Number(filter.sprint))
              ?.name
              ? '/'
              : ''}{' '}
            {dataSprint.find((item) => item.id === Number(filter.sprint))?.name}
          </Text>
        </Box>
      </Box>

      <Box
        style={{
          marginTop: '20%',
          textAlign: 'center',
          display: loading ? 'block' : 'none',
          // display: 'none',
        }}
      >
        <Loader size={'sm'} color="green" type="bars" m={'0 auto'} />
        <Text fw={600} c={'gray'}>
          Loading . . .
        </Text>
      </Box>
      <Box style={loading || !filter.sprint ? { display: 'none' } : {}}>
        {/* Tiêu đề Criteria for Sprint */}
        <Title order={5} ml="xs">
          List bug:
        </Title>

        {/* Bảng Criteria for Sprint */}
        <Table
          striped
          highlightOnHover
          withTableBorder
          withColumnBorders
          // me={'xs'}
        >
          <Table.Thead>
            <Table.Tr bg="#228be66b" style={rowStyle}>
              <Table.Th style={{ textAlign: 'center', width: '150px' }}>
                Test case
              </Table.Th>
              <Table.Th style={{ textAlign: 'center', width: '150px' }}>
                Position
              </Table.Th>
              <Table.Th style={{ textAlign: 'center', width: '220px' }}>
                Input
              </Table.Th>
              <Table.Th style={{ textAlign: 'center', width: '220px' }}>
                Expect output
              </Table.Th>
              <Table.Th style={{ textAlign: 'center', width: '220px' }}>
                Actual output
              </Table.Th>
              <Table.Th style={{ textAlign: 'center' }}>Note</Table.Th>
              <Table.Th style={{ textAlign: 'center', width: '100px' }}>
                Action
              </Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>
            {dataListTestCases.map((item, index) => (
              <Table.Tr key={index} style={rowStyle}>
                <Table.Td>{item.name}</Table.Td>
                <Table.Td>{item.position}</Table.Td>
                <Table.Td>{item.input}</Table.Td>
                <Table.Td>{item.expect_output}</Table.Td>
                <Table.Td>{item.actual_output}</Table.Td>
                <Table.Td>{item.note}</Table.Td>
                <Table.Td>
                  <Box className={classes.optionIcon}>
                    <IconInfoSquare
                      className={classes.editIcon}
                      onClick={() => {
                        setAction('review')
                        setItem(item)
                        form.reset()
                      }}
                      width={20}
                      height={20}
                    />
                    <IconSquareXFilled
                      className={classes.deleteIcon}
                      onClick={() => {
                        setAction('delete')
                        setItem(item)
                        form.reset()
                      }}
                      width={20}
                      height={20}
                    />
                  </Box>
                </Table.Td>
              </Table.Tr>
            ))}
          </Table.Tbody>
        </Table>
      </Box>

      {/* Add Test modal */}
      <Modal
        opened={action === 'add'}
        onClose={() => {
          setAction('')
          form.reset()
        }}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            {action === 'add' ? 'Add Test Report' : ''}
          </Text>
        }
      >
        <form
          onSubmit={form.onSubmit(async (values) => {
            setDisableBtn(true)
            await handleCreate(values)
            setDisableBtn(false)
          })}
        >
          <Box pl={'md'} pr={'md'}>
            <TextInput
              required
              label="Name"
              mb={'md'}
              value={form.values.name}
              error={form.errors.name}
              onChange={(e) => form.setFieldValue('name', e.target.value)}
            />

            <TextInput
              required
              label="Position"
              mb={'md'}
              value={form.values.position}
              onChange={(e) => form.setFieldValue('position', e.target.value)}
            />

            <Textarea
              style={{ marginTop: '10px' }}
              autosize
              minRows={2}
              maxRows={4}
              label="Input"
              required
              value={form.values.input}
              onChange={(e) => form.setFieldValue('input', e.target.value)}
            />
            <Textarea
              style={{ marginTop: '10px' }}
              autosize
              minRows={2}
              maxRows={4}
              label="Expect Output"
              required
              value={form.values.expect_output}
              onChange={(e) =>
                form.setFieldValue('expect_output', e.target.value)
              }
            />
            <Textarea
              style={{ marginTop: '10px' }}
              autosize
              minRows={2}
              maxRows={4}
              label="Actual Output"
              required
              value={form.values.actual_output}
              onChange={(e) =>
                form.setFieldValue('actual_output', e.target.value)
              }
            />

            <Box display={'flex'} style={{ marginTop: '10px' }}>
              <Box style={{ display: 'flex', flexFlow: 'column' }} w={'45%'}>
                <TextInput
                  label="Issue ID On Jira"
                  mb={'md'}
                  value={form.values.issue_id_on_jira}
                  onChange={(e) =>
                    form.setFieldValue('issue_id_on_jira', e.target.value)
                  }
                />
              </Box>
              <Box
                style={{ display: 'flex', flexFlow: 'column' }}
                w={'10%'}
              ></Box>
              <Box style={{ display: 'flex', flexFlow: 'column' }} w={'45%'}>
                <TextInput
                  label="Bug ID On Jira"
                  mb={'md'}
                  value={form.values.bug_id_on_jira}
                  onChange={(e) =>
                    form.setFieldValue('bug_id_on_jira', e.target.value)
                  }
                />
              </Box>
            </Box>
            <Textarea
              style={{ marginTop: '10px' }}
              autosize
              minRows={2}
              maxRows={4}
              label="Note"
              required
              value={form.values.note}
              onChange={(e) => form.setFieldValue('note', e.target.value)}
            />
            <Box ta={'center'}>
              <Button
                mt={'lg'}
                bg={'green'}
                type="submit"
                disabled={disableBtn}
              >
                Create
              </Button>
            </Box>
          </Box>
        </form>
      </Modal>

      <Modal
        opened={action === 'review'}
        onClose={() => {
          setAction('')
        }}
        size={'lg'}
        title={
          <Text pl={'sm'} fw={700} fz={'lg'}>
            Detail Test Report
          </Text>
        }
      >
        <Box pl={'md'} pr={'md'}>
          <TextInput
            label="Name"
            readOnly
            style={{ pointerEvents: 'none' }}
            mb={'md'}
            value={item.name}
          />

          <TextInput
            label="Position"
            readOnly
            style={{ pointerEvents: 'none' }}
            mb={'md'}
            value={item.position}
          />

          <Textarea
            readOnly
            style={{ marginTop: '10px' }}
            autosize
            minRows={2}
            maxRows={4}
            label="Input"
            value={item.input}
          />

          <Textarea
            readOnly
            style={{ marginTop: '10px' }}
            label="Expect Output"
            value={item.expect_output}
            autosize
            minRows={2}
            maxRows={4}
          />

          <Textarea
            readOnly
            style={{ marginTop: '10px' }}
            autosize
            minRows={2}
            maxRows={4}
            label="Actual Output"
            value={item.actual_output}
          />
          <Box display={'flex'} style={{ marginTop: '10px' }}>
            <Box style={{ display: 'flex', flexFlow: 'column' }} w={'45%'}>
              <TextInput
                readOnly
                style={{ pointerEvents: 'none' }}
                label="Issue ID On Jira"
                mb={'md'}
                value={item.issue_id_on_jira}
              />
            </Box>
            <Box
              style={{ display: 'flex', flexFlow: 'column' }}
              w={'10%'}
            ></Box>
            <Box style={{ display: 'flex', flexFlow: 'column' }} w={'45%'}>
              <TextInput
                readOnly
                style={{ pointerEvents: 'none' }}
                label="Bug ID On Jira"
                mb={'md'}
                value={item.bug_id_on_jira}
              />
            </Box>
          </Box>
          <Textarea
            readOnly
            style={{ marginTop: '10px' }}
            autosize
            minRows={2}
            maxRows={4}
            label="Note"
            value={item.note}
          />
          <TextInput
            readOnly
            style={{ pointerEvents: 'none', marginTop: '10px' }}
            label="Create By"
            mb={'md'}
            value={item.created_by}
          />
        </Box>
      </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)
                if (item.id !== undefined) {
                  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 TestReport
