import { getAllUserWorklogs } from '@/api/Admin'
import { get } from '@/rtk/helpers/apiService'
import {
  Avatar,
  Badge,
  Box,
  Button,
  Loader,
  Text,
  Tooltip,
} from '@mantine/core'
import { DateInput } from '@mantine/dates'
import moment from 'moment'
import { useEffect, useState } from 'react'
import classes from './Worklogs.module.css'
import { notifications } from '@mantine/notifications'

interface WorkLog {
  self: string
  author: UserInfo
  updateAuthor: UserInfo
  created: string
  updated: string
  started: string
  timeSpent: string
  timeSpentSeconds: number
  id: string
  issueId: string
  comment?: {
    content: {
      content: {
        text: string
      }[]
    }[]
  }
}

interface UserInfo {
  self: string
  accountId: string
  avatarUrls: AvatarUrls
  displayName: string
  active: boolean
  timeZone: string
  accountType: string
}

interface AvatarUrls {
  '48x48': string
  '24x24': string
  '16x16': string
  '32x32': string
}

interface Issue {
  expand: string
  id: string
  self: string
  key: string
  fields: IssueFields
  changelog: Changelog
}

interface IssueFields {
  summary: string
  timespent: number
  timeoriginalestimate: number
  project: ProjectInfo
  worklog: WorkLogList
  status: StatusInfo
}

interface ProjectInfo {
  self: string
  id: string
  key: string
  name: string
  projectTypeKey: string
  simplified: boolean
  avatarUrls: AvatarUrls
}

interface WorkLogList {
  startAt: number
  maxResults: number
  total: number
  worklogs: WorkLog[]
}

interface StatusInfo {
  self: string
  description: string
  iconUrl: string
  name: string
  id: string
  statusCategory: StatusCategory
}

interface StatusCategory {
  self: string
  id: number
  key: string
  colorName: string
  name: string
}

interface Information {
  startAt: number
  maxResults: number
  total: number
  issues: Issue[]
}

interface UserWorklog {
  username: string
  information: Information
  user: UserInfo
  tasksAssign: {
    issues: Issue[]
  }
}

interface Item {
  field: string
  fieldtype: string
  fieldId: string
  from: string | null
  fromString: string | null
  to: string | null
  toString: string | null
}

interface History {
  id: string
  author: UserInfo
  created: string
  items: Item[]
}

interface Changelog {
  startAt: number
  maxResults: number
  total: number
  histories: History[]
}

const Worklogs = () => {
  const [loader, setLoader] = useState(true)
  const [updating, setUpdating] = useState(true)
  const [worklogs, setWorklogs] = useState<UserWorklog[]>([])
  const [date, setDate] = useState({
    startDate:
      localStorage.getItem('data') !== null
        ? JSON.parse(localStorage.getItem('data')!).date.startDate
        : moment(Date.now() - 604800000).format('YYYY-MM-DD'),
    endDate:
      localStorage.getItem('data') !== null
        ? JSON.parse(localStorage.getItem('data')!).date.endDate
        : moment(Date.now()).format('YYYY-MM-DD'),
  })

  const getAllWorklogs = async (
    startDate = date.startDate,
    endDate = date.endDate,
  ) => {
    try {
      setUpdating(false)
      const res = await get(getAllUserWorklogs, {
        startDate: startDate,
        endDate: endDate,
      })
      if (res.status) {
        const data = res.data.filter(
          (user: UserWorklog) => user.information.issues.length > 0,
        )
        setWorklogs(data)
        localStorage.setItem(
          'data',
          JSON.stringify({ time: Date.now(), data: data, date: date }),
        )
        setLoader(false)
      }

      setUpdating(true)
    } catch (error: any) {
      console.log(error)
      notifications.show({
        title: 'Error',
        message: error.message ?? error,
        color: 'red',
      })
    }
  }

  useEffect(() => {
    const localData = localStorage.getItem('data')
    if (localData !== null) {
      setWorklogs(JSON.parse(localData!).data)
      setDate(JSON.parse(localData!).date)
      setLoader(false)
      if (Date.now() - JSON.parse(localData!).time > 300000) {
        getAllWorklogs()
      }
    } else {
      getAllWorklogs()
    }
  }, [])

  return loader ? (
    <Box ta={'center'}>
      <Loader size={40} mt={'15%'} />
    </Box>
  ) : (
    <div style={{ display: 'flex', flexFlow: 'column' }}>
      <div className={classes.title}>
        <h3>
          Worklogs
          {!updating ? (
            <Text fs={'italic'} fz={'xs'} c={'gray'}>
              Updating data in the background ...
            </Text>
          ) : (
            ''
          )}
        </h3>
      </div>
      <Box
        display={'flex'}
        style={{
          flexFlow: 'column',
        }}
      >
        <Text fz={12} fs={'italic'} c={'red'} fw={600} mt={'md'}>
          {`* The current data is from ${
            JSON.parse(localStorage.getItem('data')!).date.startDate
          } to ${JSON.parse(localStorage.getItem('data')!).date.endDate}`}
        </Text>
        <Text fz={12} fs={'italic'} c={'red'} fw={600}>
          {`* If you need data outside this time period, please select a date and click "Search" to update the latest data.`}
        </Text>
        <Box w={'100%'} display={'flex'} style={{ flexFlow: 'column' }}>
          <Box
            w={'100%'}
            display={'flex'}
            style={{
              alignItems: 'end',
              // justifyContent: 'space-between',
              flexWrap: 'wrap',
            }}
          >
            <DateInput
              size="xs"
              label="From date:"
              value={new Date(date.startDate)}
              w={'20%'}
              // clearable
              onChange={(e) => {
                setDate({ ...date, startDate: moment(e).format('YYYY-MM-DD') })
              }}
            />
            <DateInput
              size="xs"
              label="To date:"
              value={new Date(date.endDate)}
              // clearable
              m={'0 10px'}
              w={'20%'}
              onChange={(e) => {
                setDate({ ...date, endDate: moment(e).format('YYYY-MM-DD') })
              }}
            />
            <Button
              size="xs"
              onClick={() => {
                getAllWorklogs()
              }}
            >
              Search
            </Button>
          </Box>
        </Box>
      </Box>
      {/* Box main content */}
      <Box display={'flex'} mt={'lg'} style={{ flexWrap: 'wrap' }}>
        <Box w={{ base: '100%', md: '15%' }} mb={'lg'}>
          <Text fw={700} fz={14}>
            Members
          </Text>
          <Box
            style={{
              border: 'solid 1px gray',
              padding: '10px 20px',
              marginRight: '10px',
              borderRadius: '5px',
              boxShadow: '1px 1px 5px 1px gray',
            }}
          >
            {worklogs.map((w) => (
              <Box
                key={w.username}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  fontSize: '13px',
                }}
                mb={'xs'}
                className={classes.menuUser}
              >
                <Avatar src={w.user.avatarUrls['16x16']} size={'xs'} mr={5} />
                <a
                  className={classes.menuLink}
                  href={'/worklogs#' + w.username}
                  style={{ textDecoration: 'none' }}
                >
                  {w.username}
                </a>
              </Box>
            ))}
          </Box>
        </Box>
        <Box
          w={{ base: '100%', md: '85%' }}
          h={'85vh'}
          display={'flex'}
          style={{ overflowX: 'auto', flexFlow: 'column' }}
        >
          {worklogs?.map((user, index) => (
            // Box user
            <Box
              id={user.username}
              key={index}
              p={'sm'}
              style={{
                border: 'solid 1px gray',
                borderRadius: '5px',
                borderColor: '#afafaf',
                marginBottom: '10px',
                backgroundColor:
                  index % 2 === 0 ? 'rgb(201 201 201 / 28%)' : 'white',
              }}
            >
              <Text ta={'left'} mb={'xs'} fw={800} display={'flex'}>
                <Avatar
                  src={user.user.avatarUrls['48x48']}
                  size={'sm'}
                  m={'0 5px'}
                />
                {user.username}(
                {user?.information.issues.reduce((total, issue) => {
                  const totalSpent = issue.fields.worklog.worklogs?.reduce(
                    (accumulator, currentValue) => {
                      if (
                        parseInt(moment(date.startDate).format('YYYYMMDD')) <=
                          parseInt(
                            moment(currentValue.started).format('YYYYMMDD'),
                          ) &&
                        parseInt(
                          moment(currentValue.started).format('YYYYMMDD'),
                        ) <=
                          parseInt(moment(date.endDate).format('YYYYMMDD')) &&
                        currentValue.updateAuthor.displayName === user.username
                      ) {
                        return accumulator + currentValue.timeSpentSeconds
                      }
                      return accumulator
                    },
                    0,
                  )
                  return total + totalSpent
                }, 0) /
                  60 /
                  60}
                h)
              </Text>
              {/* Box issue-todo */}
              <Box
                display={'flex'}
                style={{ justifyContent: 'space-between', flexWrap: 'wrap' }}
              >
                {/* Box issue */}
                <Box
                  w={{ base: '100%', md: '50%' }}
                  style={{
                    border: 'solid 1px gray',
                    borderRadius: '5px',
                    padding: '10px',
                    marginBottom: '5px',
                    overflowX: 'hidden',
                    color: '#412d2d',
                    backgroundColor: '#d1cdce',
                  }}
                >
                  <Text fw={700} ta={'center'} mb={'5px'}>
                    WORKLOG
                  </Text>
                  {user.information.issues.map((iss) => {
                    if (
                      iss.fields.worklog.worklogs.filter(
                        (w) =>
                          parseInt(moment(date.startDate).format('YYYYMMDD')) <=
                            parseInt(moment(w.started).format('YYYYMMDD')) &&
                          parseInt(moment(date.endDate).format('YYYYMMDD')) >=
                            parseInt(moment(w.started).format('YYYYMMDD')) &&
                          w.updateAuthor.displayName === user.username,
                      ).length > 0
                    ) {
                      return (
                        <Box
                          key={iss.id}
                          style={{
                            border: 'solid 1px gray',
                            borderRadius: '5px',
                            boxShadow: '1px 1px 5px 1px gray',
                            padding: '10px',
                            marginBottom: '8px',
                            maxHeight: '90vh',
                            overflowX: 'hidden',
                            color: '#412d2d',
                            backgroundColor: 'white',
                          }}
                        >
                          {/* Box information issue */}
                          <Box>
                            <Text
                              fz={14}
                              c={iss.fields.status.statusCategory.colorName}
                            >
                              <b>{iss.fields.status.name}</b>
                            </Text>
                            <Badge color="#6140c0e0">
                              <Box
                                display={'flex'}
                                style={{ alignItems: 'center' }}
                              >
                                <Avatar
                                  src={iss.fields.project?.avatarUrls['16x16']}
                                  size={'xs'}
                                  m={'0 5px 0 0'}
                                />
                                {iss.fields.project.name}
                              </Box>
                            </Badge>
                            <Text
                              fz={14}
                              display={'flex'}
                              style={{ alignItems: 'start' }}
                            >
                              <b>Summary:</b>{' '}
                              <Tooltip label={iss.fields.summary}>
                                <Badge color="#228be64f" fz={12}>
                                  <a
                                    href={`https://apactechvn.atlassian.net/browse/${iss.key}`}
                                    target="_blank"
                                    style={{ textDecoration: 'none' }}
                                  >
                                    [{iss.key}]{` ${iss.fields.summary}`}
                                  </a>
                                </Badge>
                              </Tooltip>
                            </Text>
                            <Text fz={14}>
                              <b>Estimate:</b>{' '}
                              <Badge color="red" size="sm">
                                {iss.fields.timeoriginalestimate / 60 / 60}h
                              </Badge>
                            </Text>
                            <Text fz={14}>
                              <b>Total time spent:</b>{' '}
                              <Badge color="orange" size="sm">
                                {iss.fields.timespent / 60 / 60}h
                              </Badge>
                            </Text>
                            <Text fz={14}>
                              <b>
                                Time spent{' '}
                                <span style={{ fontSize: '11px' }}>
                                  (
                                  {date.startDate === date.endDate
                                    ? date.startDate
                                    : date.startDate + ' to ' + date.endDate}
                                  )
                                </span>
                                :
                              </b>{' '}
                              <Badge color="green" size="sm" mb={'xs'}>
                                {iss.fields.worklog.worklogs?.reduce(
                                  (accumulator, currentValue) => {
                                    if (
                                      parseInt(
                                        moment(date.startDate).format(
                                          'YYYYMMDD',
                                        ),
                                      ) <=
                                        parseInt(
                                          moment(currentValue.started).format(
                                            'YYYYMMDD',
                                          ),
                                        ) &&
                                      parseInt(
                                        moment(currentValue.started).format(
                                          'YYYYMMDD',
                                        ),
                                      ) <=
                                        parseInt(
                                          moment(date.endDate).format(
                                            'YYYYMMDD',
                                          ),
                                        ) &&
                                      currentValue.updateAuthor.displayName ===
                                        user.username
                                    ) {
                                      return (
                                        accumulator +
                                        currentValue.timeSpentSeconds
                                      )
                                    }
                                    return accumulator
                                  },
                                  0,
                                ) /
                                  60 /
                                  60}
                                h
                              </Badge>
                            </Text>
                          </Box>
                          {iss.fields.worklog.worklogs?.map((log, index) => {
                            if (
                              moment(date.startDate).format('YYYYMMDD') <=
                                moment(log.started).format('YYYYMMDD') &&
                              moment(log.started).format('YYYYMMDD') <=
                                moment(date.endDate).format('YYYYMMDD') &&
                              log.updateAuthor.displayName === user.username
                            ) {
                              return (
                                // Box worklog
                                <Box
                                  key={index}
                                  style={{
                                    padding: '4px 8px',
                                    marginBottom: '5px',
                                    marginLeft: '10px',
                                    backgroundColor: '#d9d9d9',
                                  }}
                                >
                                  <Text fz={13}>
                                    <b>Start date:</b>{' '}
                                    {moment(log.started).format(
                                      'HH:mm YYYY/MM/DD',
                                    )}
                                  </Text>
                                  <Text fz={13}>
                                    <b>Time spent:</b> {log.timeSpent}
                                  </Text>
                                  {log?.comment &&
                                    log?.comment?.content[0]?.content[0]
                                      ?.text && (
                                      <Text fz={13}>
                                        <b>Comment:</b>{' '}
                                        {
                                          log?.comment?.content[0]?.content[0]
                                            ?.text
                                        }
                                      </Text>
                                    )}
                                </Box>
                              )
                            }
                          })}
                        </Box>
                      )
                    }
                  })}
                </Box>
                {/* Box todo */}
                <Box
                  w={{ base: '100%', md: '49%' }}
                  style={{
                    border: 'solid 1px gray',
                    borderRadius: '5px',
                    padding: '10px',
                    marginBottom: '5px',
                    overflowX: 'hidden',
                    color: '#412d2d',
                    backgroundColor: '#f9ffa47a',
                  }}
                >
                  <Text fw={700} ta={'center'} mb={'5px'}>
                    ASSIGNMENT
                  </Text>
                  {user.tasksAssign.issues?.map((iss, index) => {
                    return (
                      <Box
                        key={index}
                        style={{
                          border: 'solid 1px gray',
                          borderRadius: '5px',
                          boxShadow: '1px 1px 5px 1px gray',
                          padding: '10px',
                          marginBottom: '5px',
                          overflowX: 'hidden',
                          color: '#412d2d',
                          backgroundColor: 'white',
                        }}
                      >
                        <Text
                          fz={14}
                          c={iss.fields.status.statusCategory.colorName}
                        >
                          <b>{iss.fields.status.name}</b>
                        </Text>

                        <Badge color="#6140c0e0">
                          <Box
                            display={'flex'}
                            style={{ alignItems: 'center' }}
                          >
                            <Avatar
                              src={iss.fields.project?.avatarUrls['16x16']}
                              size={'xs'}
                              m={'0 5px 0 0'}
                            />
                            {iss.fields.project.name}
                          </Box>
                        </Badge>
                        <Text
                          fz={14}
                          display={'flex'}
                          style={{ alignItems: 'start' }}
                        >
                          <b>Summary:</b>{' '}
                          <Tooltip label={iss.fields.summary}>
                            <Badge color="#228be64f" fz={12}>
                              <a
                                href={`https://apactechvn.atlassian.net/browse/${iss.key}`}
                                target="_blank"
                                style={{ textDecoration: 'none' }}
                              >
                                [{iss.key}]{` ${iss.fields.summary}`}
                              </a>
                            </Badge>
                          </Tooltip>
                        </Text>
                        <Text fz={13}>
                          <b>Time spent:</b>{' '}
                          <Badge color="orange" size="sm">
                            {iss.fields.timespent / 60 / 60}h
                          </Badge>
                        </Text>
                        <Text fz={13}>
                          <b>Estimate:</b>{' '}
                          <Badge color="red" size="sm">
                            {iss.fields.timeoriginalestimate / 60 / 60}h
                          </Badge>
                        </Text>
                        {/* History issue */}
                        {iss.changelog?.histories?.map((h) => {
                          return h.items.find((i) => i.field === 'assignee') ? (
                            <Text fz={13} fw={600}>{'Assigned at: ' + moment(h.created).format("HH:mm:ss DD/MM/YYYY")}</Text>
                          ) : h.items.find((i) => i.field === 'status')? (
                            <Text fz={13} fw={600}>{h.items.find((i) => i.field === 'status')
                            ?.fromString+" ➯ "+h.items.find((i) => i.field === 'status')
                            ?.toString +": "+ moment(h.created).format("HH:mm:ss DD/MM/YYYY")}</Text>
                          ) : (
                            ''
                          )
                        })}
                      </Box>
                    )
                  })}
                </Box>
              </Box>
            </Box>
          ))}
        </Box>
      </Box>
    </div>
  )
}

export default Worklogs
