import { Merchant } from '@/app/(dashboard)/merchants/types'
import { getMerchants } from '@/lib/services/merchant-services'
import {
  Button,
  Label,
  Modal,
  ModalBody,
  ModalHeader,
  Select,
} from 'flowbite-react'
import React, { useEffect, useState } from 'react'
import FullPageLoader from '../FullPageLoader'
import modalTheme from '@/lib/themes/modal'
import { downloadDocument } from '@/lib/services/file-services'
import { toast } from 'react-toastify'
import formTheme from '@/lib/themes/form'
import DatePicker, { FormattedDate } from '../DatePicker'
import buttonTheme from '@/lib/themes/button'
import { getIncomeStatementReportUrl } from '@/lib/services/income-statement-service'

export interface CreateIncomeStatementReportModalProps {
  reportModal: ModalState
  merchant: Merchant | null
  showMerchantSelection?: boolean
  setReportModal: (modalState: ModalState) => void
}

export interface ReportFormProps {
  merchantId: string
  startDate: string
  endDate: string
}

export default function CreateIncomeStatementReportModal({
  reportModal,
  merchant,
  showMerchantSelection = false,
  setReportModal,
}: CreateIncomeStatementReportModalProps) {
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
  const [merchants, setMerchants] = useState<Merchant[]>([])
  const [reportForm, setReportForm] = useState<ReportFormProps>({
    merchantId: '',
    startDate: '',
    endDate: '',
  })

  useEffect(() => {
    if (merchant) {
      setReportForm((prev) => ({
        ...prev,
        merchantId: String(merchant.id),
      }))

      return
    }

    getMerchants({
      all: true,
    }).then((data) => {
      setMerchants(data as Merchant[])
    })
  }, [merchant])

  async function handleDownloadReport(e: React.FormEvent) {
    e.preventDefault()

    try {
      setIsDownloadingPdf(true)

      const searchParams = new URLSearchParams({
        startDate: reportForm.startDate ?? '',
        endDate: reportForm.endDate ?? '',
        merchantId: reportForm.merchantId ? String(reportForm.merchantId) : '',
      })

      const reportFileUrl = getIncomeStatementReportUrl(searchParams)

      await downloadDocument({
        merchantId: merchant?.id as number,
        url: reportFileUrl,
        filenameFallback: `income-statement-report.pdf`,
      })
    } catch {
      toast.error('Failed to download report. Please try again.')
    } finally {
      setIsDownloadingPdf(false)
    }
  }

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

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

      <ModalBody>
        <form
          className="flex flex-col items-start gap-4 mx-auto"
          onSubmit={handleDownloadReport}
        >
          {/* Merchants */}
          {showMerchantSelection && (
            <div className="w-full">
              <div className="block mb-2">
                <Label htmlFor="merchant_id" theme={formTheme.label}>
                  Merchant
                </Label>
              </div>

              <Select
                id="merchant_id"
                name="merchant_id"
                theme={formTheme.select}
                value={reportForm.merchantId}
                onChange={(e) =>
                  setReportForm((prev) => ({
                    ...prev,
                    merchantId: e.target.value ? e.target.value : '',
                  }))
                }
              >
                <option value="">All</option>
                {merchants.map((merchant) => (
                  <option key={merchant.id} value={merchant.id}>
                    {merchant.name}
                  </option>
                ))}
              </Select>
            </div>
          )}

          {/* Transaction Date */}
          <div className="flex w-full gap-4">
            <div className="flex-grow">
              <div className="mb-2 block">
                <Label htmlFor="transaction_date" theme={formTheme.label}>
                  Transaction Date
                </Label>
              </div>
              <DatePicker
                inputId="transaction_date"
                value={{
                  startDate: reportForm?.startDate
                    ? new Date(reportForm?.startDate)
                    : null,
                  endDate: reportForm?.endDate
                    ? new Date(reportForm?.endDate)
                    : null,
                }}
                onDateChange={(formattedDate: FormattedDate) =>
                  setReportForm((prev) => ({
                    ...prev,
                    startDate: formattedDate.startDate ?? '',
                    endDate: formattedDate.endDate ?? '',
                  }))
                }
              />
            </div>
          </div>

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