import { yupResolver } from '@hookform/resolvers/yup'
import {
  ArrowBackIosNew,
  ArrowForwardIos,
  Close,
  HelpOutline,
  NotesSharp,
} from '@mui/icons-material'
import {
  Box,
  Button,
  Card,
  DialogContent,
  IconButton,
  Stack,
  Typography,
} from '@mui/material'
import { AxiosRequestConfig } from 'axios'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useQuery } from 'react-query'
import { toast } from 'react-toastify'
import * as yup from 'yup'
import axios, { axiosErrorToast } from '../../../../config/axios'
import { queryClient } from '../../../../contexts/QueryClientProvider'
import { FormSingleSelect, FormTextField } from '../../../HookForm'
import ImageUpload from '../../../ImageUpload'
import MediaRow from '../../../MediaRow'
import Spinner from '../../../Spinner'
import { Media } from '../../../UploadButton/types'
import {
  StyledCard,
  StyledContactBoxHeader,
  StyledContactHeader,
  StyledDialog,
  StyledDialogCard,
  StyledDialogHeader,
  Transition,
} from './styles'

const schema = yup.object().shape({
  name: yup.string().required('Name is required'),
  subject: yup.string().required('Subject is required'),
  description: yup.string().required('Description is required'),
  // categoryId: yup.string().required('Category is required'),
  // serviceId: yup.string().required('Service is required'),
})

const HelpWidgetButton = () => {
  const [open, setOpen] = useState(false)

  const onOpen = () => {
    setOpen(true)
  }
  const onClose = () => {
    setOpen(false)
  }

  return (
    <>
      <IconButton color="secondary">
        <HelpOutline onClick={onOpen} />
      </IconButton>
      <HelpWidget onClose={onClose} open={open} />
    </>
  )
}

export default HelpWidgetButton

const HelpWidget = ({ open, onClose }) => {
  const [state, setState] = useState(0)

  return (
    <StyledDialog
      fullWidth
      onClose={onClose}
      open={open}
      PaperProps={{
        elevation: 2,
        sx: { borderRadius: '10px' },
      }}
      transitionDuration={200}
      TransitionComponent={Transition}
    >
      {state == 0 ? (
        <>
          <StyledDialogHeader>
            <IconButton onClick={onClose}>
              <Close sx={{ position: 'absolute', color: 'white', top: 5 }} />
            </IconButton>
          </StyledDialogHeader>
          <DialogContent sx={{ padding: '0' }}>
            <Box>
              <StyledCard>
                <Box
                  sx={{ display: 'flex', gap: '10px', alignItems: 'center' }}
                >
                  <NotesSharp />
                  <Typography variant="h5" sx={{ fontSize: '14px' }}>
                    Knowledge Base
                  </Typography>
                </Box>
                <ArrowForwardIos sx={{ width: '15px', color: 'blue' }} />
              </StyledCard>
            </Box>
            <Box sx={{ padding: '15px 20px 20px 20px' }}>
              <Card
                sx={{
                  boxShadow: '0px 3px 15px #0000001A',
                  padding: '20px 15px',
                  marginTop: '30px',
                }}
              >
                <Stack gap={1}>
                  <Typography variant="h3">Want to get in touch?</Typography>
                  <Typography variant="subtitle2" sx={{ maxWidth: '290px' }}>
                    We’re standing by to answer all of your questions right now.
                  </Typography>
                </Stack>
                <Button
                  fullWidth
                  sx={{
                    borderRadius: '8px',
                    marginTop: '15px',
                    height: '50px',
                  }}
                  onClick={() => setState(1)}
                >
                  Contact Us
                </Button>
              </Card>
            </Box>
          </DialogContent>
        </>
      ) : (
        <>
          <Box>
            <StyledContactHeader>
              <StyledContactBoxHeader onClick={() => setState(0)}>
                <ArrowBackIosNew sx={{ fontSize: 'small', color: 'white' }} />
                <Typography sx={{ color: 'white' }} variant="h3">
                  Contact Us
                </Typography>
              </StyledContactBoxHeader>
              <IconButton onClick={onClose}>
                <Close
                  sx={{
                    position: 'absolute',
                    color: 'white',
                    top: 5,
                    right: 2,
                  }}
                />
              </IconButton>
            </StyledContactHeader>
            <DialogContent sx={{ height: '500px' }}>
              <StyledDialogCard>
                <HelpWidgetForm onClose={onClose} />
              </StyledDialogCard>
            </DialogContent>
          </Box>
        </>
      )}
    </StyledDialog>
  )
}

const HelpWidgetForm = ({ onClose }) => {
  const [uploadMedia, setUploadMedia] = useState<Media[]>([])

  const { control, handleSubmit, watch, reset } = useForm({
    resolver: yupResolver(schema),
  })
  const { data: ticketCategories, isLoading } = useQuery(
    'ticketCategories',
    () =>
      axios.get(`/square/service-tickets/categories`).then((res) => res.data),
  )

  const handleUploadImageChange = (v) => {
    setUploadMedia([
      ...uploadMedia,
      { type: 'image', url: v.url, key: v.key, id: v.id },
    ])
  }

  const handleUploadDeleteImage = (key) => {
    setUploadMedia((prev) => prev.filter((m) => m.key !== key))
  }

  const onSubmit = async (formData) => {
    const config: AxiosRequestConfig = {
      method: 'POST',
      url: '/square/service-tickets',
      data: {
        issueFiles: [uploadMedia[0]?.key],
        ...formData,
      },
    }

    try {
      await axios(config)
      queryClient.invalidateQueries('ticketCategories')
      toast.success('Ticket Created Successfully')
      reset()
      onClose()
      setUploadMedia([])
    } catch (error) {
      axiosErrorToast(error)
    }
  }

  if (isLoading) return <Spinner />
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Stack gap={'20px'}>
        <FormTextField label={'Your Name'} name={'name'} control={control} />
        <FormTextField label={'Subject'} name={'subject'} control={control} />
        <FormTextField
          label={'Description'}
          name={'description'}
          control={control}
          multiline
          rows={5}
          required
        />
        {/* <FormSingleSelect
          label={'Category'}
          name={'categoryId'}
          control={control}
          options={ticketCategories?.map((item) => {
            return { label: item.name, value: item._id }
          })}
          required
        />
        <FormSingleSelect
          label={'Service'}
          name={'serviceId'}
          control={control}
          options={
            ticketCategories
              ?.find((item) => item?._id === watch('categoryId'))
              ?.services?.map((item) => ({
                label: item.name,
                value: item._id,
              })) ?? []
          }
          required
        /> */}
        {!uploadMedia?.length ? (
          <ImageUpload
            onFileUploaded={handleUploadImageChange}
            postUrl="/square/tickets/upload-issue-file"
          />
        ) : (
          <MediaRow list={uploadMedia} onDelete={handleUploadDeleteImage} />
        )}
        <Button
          type="submit"
          fullWidth
          sx={{
            height: '60px',
            borderRadius: '10px',
            fontSize: '18px',
          }}
        >
          Send
        </Button>
      </Stack>
    </form>
  )
}
