/* eslint-disable react/jsx-key */
/* eslint-disable no-console */
import { yupResolver } from '@hookform/resolvers/yup'
import { Stack } from '@mui/material'
import moment from 'moment'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useMutation, useQueryClient } from 'react-query'
import { toast } from 'react-toastify'
import * as yup from 'yup'
import axios, { axiosErrorToast } from '../../../config/axios'
import ActionButton from '../../ActionButton'
import { FormDatePicker, FormTextField } from '../../HookForm'
import ImageUpload from '../../ImageUpload'
import { RadioGroup } from '../../Input'
import MediaRow from '../../MediaRow/MediaRow'
import { Media } from '../../UploadButton/types'
import FileUpload from '../FileUpload'
import { createUpdateWorkshop } from '../service'
const workshopsSelect = [
  {
    label: 'Attended',
    value: 'attended',
  },
  {
    label: 'Organized',
    value: 'organized',
  },
]

const schema = yup.object().shape({
  title: yup.string().required('Title is required'),
  organization: yup.string().required('Organization is required'),
  stream: yup.string().required('Stream is required'),
  program: yup.string().required('Program is required'),
  fromDate: yup.string().required('From Date is required'),
  toDate: yup
    .string()
    .required('To Date is required')
    .test(
      'endDate',
      'To date must be greater than  From date',
      function (value) {
        const { fromDate } = this.parent
        if (!fromDate) return true
        const startDateObj = new Date(fromDate)
        const endDateObj = new Date(value)
        return startDateObj < endDateObj
      },
    ),
})

export const WorkshopForm = ({ data, hideDialog }) => {
  const [media, setMedia] = useState<Media[]>([])

  const [selectedWorkshop, setSelectedWorkshop] = useState(
    data && data?.organized ? 'organized' : 'attended',
  )
  const [resource, setResource] = useState(data?.attachments || [])

  const queryClient = useQueryClient()
  const { control, handleSubmit } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      ...data,
      fromDate: data ? moment(data.fromDate).toISOString() : '',
      toDate: data ? moment(data.toDate).toISOString() : '',
      image: [{ key: data?.image?.key, url: data?.image?.url }],
    },
  })
  const { mutate, isLoading } = useMutation(createUpdateWorkshop, {
    onSuccess: () => {
      toast.success(data ? 'Workshop Updated' : 'Workshop Added')
      queryClient.invalidateQueries('dashboard')
      hideDialog()
    },
    onError: (err) => {
      console.log(err)
      axiosErrorToast(err)
    },
  })
  useEffect(() => {
    data && data?.image?.url
      ? setMedia([
          {
            key: data?.image?.key,
            url: data?.image?.url,
            type: data?.image?.mediaType,
          },
        ])
      : setMedia([])
  }, [data])
  const onSubmit = (formData) => {
    const postBody = {
      ...formData,
      organized: selectedWorkshop === 'organized',
      fromDate: moment(formData?.fromDate).format('YYYY-MM-DD'),
      toDate: moment(formData.toDate).format('YYYY-MM-DD'),
      image: media[0]?.key || null,
      attachments: resource.map((file) => file.key),
    }
    mutate(postBody)
  }
  const onError = (error) => {
    console.log(error)
  }
  const handleFileInput = (e) => {
    let filesData = e.target.files
    let fileArray = Object.keys(filesData)
    fileArray.forEach(async (file) => {
      const fileData = new FormData()
      fileData.append('file', filesData[file])
      const originalFileName = filesData[file].name

      try {
        let fileKey = await axios.post(`/square/workshops/attachment`, fileData)
        setResource([
          ...resource,
          {
            originalFileName: originalFileName,
            key: fileKey?.data?.key,
          },
        ])
      } catch (error) {
        console.log(error)
      }
    })
  }
  const onDelete = (fileKey) => {
    setResource(resource?.filter((item) => item.key !== fileKey))
  }
  const handleImageChange = (v) => {
    setMedia([{ type: 'image', url: v.url, key: v.key }])
  }
  const handleDeleteImage = (key) => {
    setMedia((prev) => prev.filter((m) => m.key !== key))
  }
  return (
    <form onSubmit={handleSubmit(onSubmit, onError)}>
      <Stack gap={2.5}>
        <>
          {!media.length ? (
            <ImageUpload
              onFileUploaded={handleImageChange}
              postUrl="/square/workshops/image"
            />
          ) : (
            <MediaRow list={media} onDelete={handleDeleteImage} />
          )}
          <RadioGroup
            row
            label="Workshop"
            name="organized"
            required
            value={selectedWorkshop}
            options={workshopsSelect.map((item) => ({
              label: item?.label,
              value: item?.value,
            }))}
            onChange={(e) => setSelectedWorkshop(e.target.value)}
          />
          <FormTextField
            control={control}
            name="title"
            label="Title"
            required
          />
          <FormTextField
            control={control}
            name="organization"
            label="Organization"
            required
          />
          <Stack direction="row" gap={2}>
            <FormDatePicker
              control={control}
              name="fromDate"
              label="From Date"
              required
            />
            <FormDatePicker
              control={control}
              name="toDate"
              label="To Date"
              required
            />
          </Stack>
          <FormTextField
            control={control}
            name="stream"
            label="Stream"
            required
          />
          <FormTextField
            control={control}
            name="program"
            label="Program"
            required
          />
          <FileUpload
            handleFileInput={handleFileInput}
            onDelete={onDelete}
            resource={resource}
          />
        </>
      </Stack>
      <Stack direction="row" gap={2} mt={2}>
        <ActionButton type="submit" fullWidth loading={isLoading}>
          {data ? 'Update Workshop' : 'Add Workshop'}
        </ActionButton>
        <ActionButton variant="outlined" fullWidth onClick={() => hideDialog()}>
          Cancel
        </ActionButton>
      </Stack>
    </form>
  )
}
