import { Box, Typography } from '@mui/material'
import moment from 'moment'
import { useState } from 'react'
import { useQuery } from 'react-query'
import ErrorBoundary from '../../ErrorBoundary'
import Spinner from '../../Spinner'
import { fetchTickets } from './services'
import { StyledCardData, StyledLeftContainer, StyledListItem } from './styles'
import TicketDetails from './TicketDetails'

function MyTickets({ close }) {
  const [currentTicket, setCurrentTicket] = useState(null)

  const { data, isLoading } = useQuery<any>('tickets', fetchTickets)

  if (isLoading) return <Spinner />
  return (
    <ErrorBoundary>
      <Box sx={{ display: 'flex', gap: '20px' }}>
        <Box sx={{ margin: '10px', borderRadius: '10px' }}>
          <StyledLeftContainer>
            {data?.result?.map((item) => (
              <TicketListItem
                key={item}
                data={item}
                setCurrentTicket={setCurrentTicket}
                currentTicket={currentTicket}
              />
            ))}
          </StyledLeftContainer>
        </Box>
        {currentTicket?._id && (
          <TicketDetails data={currentTicket} id={currentTicket._id} />
        )}
      </Box>
    </ErrorBoundary>
  )
}

export default MyTickets

const TicketListItem = ({ data, setCurrentTicket, currentTicket }) => {
  return (
    <StyledListItem
      isActive={currentTicket?._id === data?._id ? true : false}
      onClick={() => {
        setCurrentTicket(data)
      }}
    >
      <Box
        sx={{
          width: '400px',
          display: 'flex',
        }}
      >
        <Box className="left">
          <Typography variant="body2">{data?.name}</Typography>
          <Typography variant="subtitle2">
            {moment(data?.createdAt).format('DD MMMM, YYYY  hh:mm: a')}
          </Typography>
        </Box>
        <Box className="right">
          <StyledCardData>
            <Typography variant="h5" sx={{ fontSize: '9px' }}>
              {data?.status.replace('_', ' ')}
            </Typography>
          </StyledCardData>
        </Box>
      </Box>
    </StyledListItem>
  )
}
