import { getProfilesData } from '@/api/Admin'
import { changePassword } from '@/api/Auth'
import PasswordRequirementInput from '@/components/PasswordRequirementInput/PasswordRequirementInput'
import { logout } from '@/rtk/dispatches/auth'
import { get, post } from '@/rtk/helpers/apiService'
import { requirementsPassword } from '@/rtk/helpers/variables'
import { useAppDispatch, useAppSelector } from '@/rtk/hooks'
import {
  Avatar,
  Box,
  Button,
  Modal,
  PasswordInput,
  Table,
  Text,
  TextInput,
  Title,
} from '@mantine/core'
import { notifications } from '@mantine/notifications'
import { IconCornerDownRight, IconPasswordUser } from '@tabler/icons-react'
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import classes from './Profile.module.css'

interface TableRow {
  // Add properties for each column in the table
  criteria: string
  note: string
  createdBy: string
  point: string
}

interface ExpandedProjects {
  [projectName: string]: boolean
}

interface ExpandedSprints {
  [projectName: string]: {
    [sprintName: string]: boolean
  }
}

const CriteriaTable = ({ data }: { data: TableRow[] }) => (
  <Table striped highlightOnHover withTableBorder withColumnBorders>
    <Table.Thead>
      <Table.Tr bg="#228be66b">
        <Table.Th style={{ textAlign: 'center', width: '25%' }}>
          Criteria
        </Table.Th>
        <Table.Th style={{ textAlign: 'center', width: '45%' }}>Note</Table.Th>
        <Table.Th style={{ textAlign: 'center', width: '20%' }}>
          Created by
        </Table.Th>
        <Table.Th style={{ textAlign: 'center', width: '10%' }}>Point</Table.Th>
      </Table.Tr>
    </Table.Thead>
    <Table.Tbody>
      {data.map((row, index) => (
        <Table.Tr key={index}>
          <Table.Td style={{ textAlign: 'start' }}>{row.criteria}</Table.Td>
          <Table.Td style={{ textAlign: 'start' }}>{row.note}</Table.Td>
          <Table.Td style={{ textAlign: 'start' }}>{row.createdBy}</Table.Td>
          <Table.Td>{row.point}</Table.Td>
        </Table.Tr>
      ))}
    </Table.Tbody>
  </Table>
)

const isCompactMenu = false
const Profile = () => {
  const user = useAppSelector((state) => state.authentication.user)
  const [opened, setOpened] = useState(false)
  const [dataChange, setDataChange] = useState({
    password: '',
    new_password: '',
    confirm_password: '',
  })
  const [loading, setLoading] = useState(false)
  const [dataProfile, setDataProfile] = useState<any>([])

  // const [projects, setProjects] = useState(projectsData)
  const [expandedProjects, setExpandedProjects] = useState<ExpandedProjects>({})
  const [expandedSprints, setExpandedSprints] = useState<ExpandedSprints>({})

  const [countSpam, setCountSpam] = useState(0)
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const passwordRegex =
    /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

  const getListProfilesData = async () => {
    try {
      const params = {}
      const res = await get(getProfilesData, 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 getListProfilesData()
      setDataProfile(result ?? [])
    }
    fetchData()
  }, [])

  const handleChangePassword = async () => {
    try {
      if (countSpam > 5) {
        setLoading(true)
        notifications.show({
          title: 'Error',
          message: 'Password error more than 5 times. Logout after 3s',
          color: 'red',
        })

        setTimeout(() => {
          localStorage.clear()
          window.location.reload()
        }, 3000)
      } else {
        setLoading(true)
        const res = await post(
          changePassword,
          {
            email: user.user.email,
            password: dataChange.password,
            new_password: dataChange.new_password,
            confirm_password: dataChange.confirm_password,
          },
          undefined,
        )

        if (res.status) {
          notifications.show({
            title: 'Success',
            message: 'Reset password success',
            color: 'green',
          })

          setOpened(false)
          setDataChange({
            password: '',
            new_password: '',
            confirm_password: '',
          })
          handleLogout()
        } else {
          notifications.show({
            title: 'Error',
            message: res.errors.password,
            color: 'red',
          })
        }
        setCountSpam(countSpam + 1)
        setLoading(false)
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      console.log(error)
      if (error.response.status === 422) {
        const errorMess = error.response.data.message
        notifications.show({
          title: 'Error',
          message: errorMess,
          color: 'red',
        })
      }
      setLoading(false)
    }
  }

  const handleLogout = useCallback(() => {
    dispatch(logout(navigate))
  }, [dispatch, navigate])
  const handleProjectToggle = (projectName: string) => {
    setExpandedProjects((prev) => ({
      ...prev,
      [projectName]: !prev[projectName], // Toggle state for this project
    }))
  }

  const handleSprintToggle = (projectName: string, sprintName: string) => {
    setExpandedSprints((prev) => ({
      ...prev,
      [projectName]: {
        ...prev[projectName],
        [sprintName]: !prev[projectName]?.[sprintName], // Toggle state for this sprint
      },
    }))
  }

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

      <Box>
        <Box className={classes.userInfoSection} display="flex">
          <Box className={classes.sidebar}>
            <Title order={3}>User Information</Title>
            <Box
              w={'100%'}
              style={{
                display: 'flex',
                flexFlow: 'column',
                alignItems: 'center',
              }}
            >
              <Avatar
                src={null || ''}
                alt="User Avatar"
                size={150}
                // radius="xl"
                mb={5}
                mt={5}
                onClick={() => {
                  console.log('update avatar')
                }}
                style={{
                  cursor: 'pointer',
                  // border: '2px solid black',
                  borderRadius: '50%',
                }}
              />
            </Box>
            <Box className={classes.userInfo} mt="md">
              <TextInput
                label="Name"
                placeholder="Name"
                mb="md"
                readOnly
                style={{ pointerEvents: 'none' }}
                value={user.user.name}
              />
              <TextInput
                label="Email"
                type="email"
                placeholder="Email"
                mb="md"
                readOnly
                style={{ pointerEvents: 'none' }}
                value={user.user.email}
              />
              <TextInput
                label="Join Date"
                type="text"
                mb="md"
                readOnly
                style={{ pointerEvents: 'none' }}
                value={user.user.createdAt}
              />
              <TextInput
                label="Permission(s)"
                placeholder="Permissions"
                readOnly
                style={{ pointerEvents: 'none' }}
                value={user.user.permission}
              />
            </Box>

            <Box
              w={'100%'}
              style={{
                display: 'flex',
                flexFlow: 'column',
                alignItems: 'center',
              }}
              mt={10}
            >
              <a
                href="#"
                className={classes.link}
                onClick={() => setOpened(true)}
              >
                <IconPasswordUser className={classes.linkIcon} stroke={1.5} />
                <span
                  className={`${classes.itemLabel} ${classes.labelCompactMenu}`}
                >
                  Change password
                </span>
              </a>
            </Box>
          </Box>

          <Box className={classes.projectInvolvement}>
            <Title order={3}>Project Involved</Title>
            <Box className={classes.project} mt="lg">
              {dataProfile.map((project: any) => (
                <div key={project.name}>
                  {/* Project Header */}
                  <Box
                    className={classes.projectHeader}
                    onClick={() => handleProjectToggle(project.name)}
                  >
                    <Text ml="sm" fw={600}>
                      {project.name}
                    </Text>
                  </Box>

                  {/* Project's Sprints */}
                  {expandedProjects[project.name] && (
                    <Box className={classes.sprintList}>
                      {project.sprints.map((sprint: any) => (
                        <div key={sprint.name}>
                          <Box
                            className={classes.sprintHeader}
                            onClick={() =>
                              handleSprintToggle(project.name, sprint.name)
                            }
                          >
                            <IconCornerDownRight size={20} />
                            <Text
                              ml="xs"
                              className={classes.sprintHeader2}
                              fw={600}
                            >
                              {sprint.name}
                            </Text>
                          </Box>

                          {/* Criteria Table */}
                          {expandedSprints[project.name]?.[sprint.name] && (
                            <Box className={classes.criteriaTable}>
                              {/* <CriteriaTable data={sprint.criteria} /> */}
                              <CriteriaTable
                                data={sprint.criterias.map((criteria: any) => ({
                                  ...criteria,
                                }))}
                              />
                            </Box>
                          )}
                        </div>
                      ))}
                    </Box>
                  )}
                </div>
              ))}
            </Box>
          </Box>
        </Box>

        <Modal
          opened={opened}
          onClose={() => {
            setOpened(false)
            setDataChange({
              password: '',
              new_password: '',
              confirm_password: '',
            })
          }}
          title={
            <Text
              fw={700}
              fz={'1.2rem'}
              className={`${classes.itemLabel} ${
                isCompactMenu ? classes.labelCompactMenu : ''
              }`}
            >
              Change password
            </Text>
          }
        >
          <Box p="sm">
            <TextInput
              label="E-mail"
              value={user.user.email}
              disabled
              mb={'md'}
            ></TextInput>

            <PasswordInput
              label="Current password"
              required
              placeholder="Current password"
              maxLength={32}
              value={dataChange.password}
              onChange={(e) => {
                setDataChange({ ...dataChange, password: e.target.value })
              }}
              error={
                dataChange.password.length < 8 &&
                dataChange.password !== '' &&
                'Length 8 characters or more'
              }
            />

            <PasswordRequirementInput
              requirements={requirementsPassword}
              value={dataChange}
              setValue={setDataChange}
              label="New password"
              placeholder="New password"
              name="new_password"
              mb="md"
            />

            <PasswordInput
              label="Confirm password"
              required
              placeholder="Confirm password"
              maxLength={32}
              value={dataChange.confirm_password}
              onChange={(e) => {
                setDataChange({
                  ...dataChange,
                  confirm_password: e.target.value,
                })
              }}
              error={
                dataChange.new_password !== dataChange.confirm_password &&
                dataChange.confirm_password !== '' &&
                'Password do not match'
              }
            ></PasswordInput>

            <Button
              style={{ float: 'right' }}
              mb={'lg'}
              mt={'lg'}
              loading={loading}
              disabled={
                loading === false &&
                dataChange.password !== '' &&
                passwordRegex.test(dataChange.new_password) &&
                dataChange.new_password === dataChange.confirm_password &&
                dataChange.new_password !== ''
                  ? false
                  : true
              }
              onClick={() => handleChangePassword()}
            >
              Update
            </Button>
          </Box>
        </Modal>
      </Box>
    </div>
  )
}

export default Profile
