import React, { Dispatch, FormEvent, SetStateAction, useState } from 'react'
import {
  Button,
  Label,
  Modal,
  ModalBody,
  ModalHeader,
  Select,
} from 'flowbite-react'
import { toast } from 'react-toastify'

import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import buttonTheme from '@/lib/themes/button'
import modalTheme from '@/lib/themes/modal'
import formTheme from '@/lib/themes/form'
import * as fileServices from '@/lib/services/file-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { getWithdrawalReportFileUrl } from '@/lib/services/withdrawal-services'
import PartnerSelector from '@/lib/components/forms/PartnerSelector'
import { WithdrawalStatus } from '../types'

interface CreateReportModalProps {
  reportModal: ModalState
  setReportModal: Dispatch<SetStateAction<ModalState>>
}

interface ReportFormProps {
  startDate?: string | null
  endDate?: string | null
  partnerId?: number | null
  status?: WithdrawalStatus | ''
}

const CreateReportModal: React.FC<CreateReportModalProps> = (props) => {
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
  const [reportForm, setReportForm] = useState<ReportFormProps>({
    startDate: null,
    endDate: null,
    partnerId: null,
    status: '',
  })

  async function handleCreateReport(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()

    try {
      setIsDownloadingPdf(true)

      const searchParams = new URLSearchParams({
        startDate: reportForm.startDate ?? '',
        endDate: reportForm.endDate ?? '',
        partnerId: reportForm.partnerId?.toString() ?? '',
        status: reportForm.status ?? '',
      })

      const reportFileUrl = getWithdrawalReportFileUrl(searchParams)

      await fileServices.downloadDocument({
        url: reportFileUrl,
        filenameFallback: `withdrawal-report.pdf`,
      })
    } catch {
      toast.error('Failed to download withdrawal report. Please try again.')
    } finally {
      setIsDownloadingPdf(false)
    }
  }

  if (isDownloadingPdf) {
    return <FullPageLoader message="Downloading withdrawal report..." />
  }

  return (
    <Modal
      position="center"
      theme={modalTheme.modal}
      dismissible
      show={props.reportModal.isOpened && props.reportModal.type === 'create'}
      onClose={() => props.setReportModal({ type: 'create', isOpened: false })}
    >
      <ModalHeader>Create Report</ModalHeader>

      <ModalBody>
        <form
          className="flex flex-col items-start gap-4 mx-auto"
          onSubmit={handleCreateReport}
        >
          {/* Requested At */}
          <div className="flex w-full gap-4">
            <div className="flex-grow">
              <div className="mb-2 block">
                <Label htmlFor="requested_at" theme={formTheme.label}>
                  Requested At
                </Label>
              </div>
              <DatePicker
                inputId="requested_at"
                value={{
                  startDate: reportForm.startDate
                    ? new Date(reportForm.startDate)
                    : null,
                  endDate: reportForm.endDate
                    ? new Date(reportForm.endDate)
                    : null,
                }}
                onDateChange={(formattedDate: FormattedDate) => {
                  setReportForm((reportForm) => ({
                    ...reportForm,
                    startDate: formattedDate.startDate,
                    endDate: formattedDate.endDate,
                  }))
                }}
              />
            </div>
          </div>

          {/* Status */}
          <div className="w-full">
            <div className="block mb-2">
              <Label htmlFor="status" theme={formTheme.label}>
                Status
              </Label>
            </div>

            <Select
              id="status"
              theme={formTheme.select}
              className="w-full"
              defaultValue={reportForm.status as WithdrawalStatus}
              onChange={(e) => {
                setReportForm({
                  ...reportForm,
                  status: e.target.value as WithdrawalStatus,
                })
              }}
            >
              <option value="">All</option>
              <option value="pending">Pending</option>
              <option value="processing">Processing</option>
              <option value="completed">Completed</option>
              <option value="rejected">Rejected</option>
              <option value="cancelled">Cancelled</option>
            </Select>
          </div>

          {/* Partner */}
          <PartnerSelector
            fullWidth
            selectedPartnerId={reportForm.partnerId as number}
            onSelectPartner={(partner) => {
              setReportForm((prev) => ({
                ...prev,
                partnerId: partner ? partner.id : undefined,
              }))
            }}
          />

          <Button theme={buttonTheme.button} color="blue" type="submit">
            Download
          </Button>
        </form>
      </ModalBody>
    </Modal>
  )
}

export default CreateReportModal
