import React, { useState } from 'react'
import {
  Button,
  HelperText,
  Label,
  Modal,
  ModalBody,
  ModalHeader,
  Textarea,
} from 'flowbite-react'
import * as yup from 'yup'
import { toast } from 'react-toastify'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'

import modalTheme from '@/lib/themes/modal'
import { Withdrawal } from '@/lib/types/withdrawal'
import { cancelWithdrawal } from '@/lib/services/withdrawal-services'
import { handleApiError } from '@/lib/utils/error-handler'
import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'

interface WithdrawalCancelledModalProps {
  withdrawal?: Withdrawal | null
  withdrawalCancelledModal: ModalState
  onSuccess?: (withdrawal: Withdrawal) => void
  setWithdrawalCancelledModal: React.Dispatch<React.SetStateAction<ModalState>>
}

const withdrawalCancelledFormSchema = yup.object({
  cancellation_reason: yup.string().required('Cancellation reason is required'),
})

export type WithdrawalCancelledFormData = yup.InferType<
  typeof withdrawalCancelledFormSchema
>

export default function WithdrawalCancelledModal({
  withdrawal,
  withdrawalCancelledModal,
  onSuccess,
  setWithdrawalCancelledModal,
}: WithdrawalCancelledModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const {
    register,
    handleSubmit,
    setError,
    watch,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(withdrawalCancelledFormSchema),
    defaultValues: {
      cancellation_reason: '',
    },
  })
  const formValues = watch()

  async function onSubmit(data: WithdrawalCancelledFormData) {
    try {
      if (!withdrawal) return

      setIsSubmitting(true)

      const cancelledWithdrawal = await cancelWithdrawal(withdrawal.id, data)

      toast.success('Withdrawal request cancelled successfully.')
      onSuccess?.(cancelledWithdrawal)
      setWithdrawalCancelledModal({ type: 'edit', isOpened: false })
      reset()
    } catch (error) {
      handleApiError(
        error,
        'Failed to cancel withdrawal request. Please try again later.',
        (formErrors) => {
          Object.keys(formErrors).forEach((field) => {
            setError(field as keyof WithdrawalCancelledFormData, {
              type: 'server',
              message: formErrors[field][0],
            })
          })
        },
      )
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Modal
      position="center"
      theme={modalTheme.modal}
      dismissible
      show={withdrawalCancelledModal.isOpened}
      onClose={() => {
        setWithdrawalCancelledModal({ type: 'edit', isOpened: false })
      }}
    >
      <ModalHeader>
        <p>Cancel Withdrawal #{withdrawal?.code}</p>
        <p className="text-sm font-normal text-slate-500 mt-2">
          Please provide a reason for cancelling this withdrawal request. This
          action cannot be undone.
        </p>
      </ModalHeader>

      <ModalBody>
        <form className="space-y-8" onSubmit={handleSubmit(onSubmit)}>
          {/* Cancellation Reason */}
          <div className="w-full">
            <div className="mb-2 block">
              <Label theme={formTheme.label} htmlFor="cancellation_reason">
                Cancellation Reason <span className="text-red-500">*</span>
              </Label>
            </div>
            <Textarea
              id="cancellation_reason"
              theme={formTheme.textarea}
              rows={4}
              className="resize-none"
              placeholder="Enter the cancellation reason..."
              {...register('cancellation_reason')}
            >
              {formValues.cancellation_reason}
            </Textarea>
            <HelperText color="failure">
              {errors.cancellation_reason?.message}
            </HelperText>
          </div>

          <div className="ml-auto w-fit flex items-center gap-2 mt-4">
            <Button
              color="alternative"
              disabled={isSubmitting}
              theme={buttonTheme.button}
              onClick={() =>
                setWithdrawalCancelledModal({ type: 'edit', isOpened: false })
              }
            >
              Keep Withdrawal
            </Button>
            <Button
              color="blue"
              type="submit"
              theme={buttonTheme.button}
              disabled={isSubmitting}
            >
              Cancel Withdrawal
            </Button>
          </div>
        </form>
      </ModalBody>
    </Modal>
  )
}
