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

import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'
import tabTheme from '@/lib/themes/tab'
import modalTheme from '@/lib/themes/modal'
import { PaymentMethodCode, PaymentStatus } from '@/lib/types/payment'
import {
  PAYMENT_METHODS_BY_ORDER_TYPE,
  PAYMENT_METHODS_OPTIONS,
  PAYMENT_STATUS_OPTIONS,
} from '@/lib/constants/payment'
import { getTransactionReportFileUrl } from '@/lib/services/order-services'
import { downloadDocument } from '@/lib/services/file-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { BookingMethod } from '../../orders/types'
import { useMerchant } from '@/lib/context/MerchantContext'
import { Merchant } from '@/app/(dashboard)/merchants/types'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { OFFLINE_ORDER_BY_OPTIONS } from '@/lib/constants/order'
import AgentSelector from '@/lib/components/forms/AgentSelector'

interface ModalCreateReportProps {
  merchants: Merchant[]
  marketplaces: Marketplace[]
  reportModal: ModalState
  setReportModal: Dispatch<SetStateAction<ModalState>>
}

const FilterForm: React.FC<{
  reportForm: ReportForm
  setReportForm: Dispatch<SetStateAction<ReportForm>>
}> = ({ reportForm, setReportForm }) => {
  const paymentMethods = reportForm.orderBy
    ? PAYMENT_METHODS_BY_ORDER_TYPE[reportForm.orderBy as OrderByType]
    : PAYMENT_METHODS_OPTIONS

  return (
    <React.Fragment>
      {/* 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((reportForm) => ({
                ...reportForm,
                startDate: formattedDate.startDate,
                endDate: formattedDate.endDate,
              }))
            }}
          />
        </div>
      </div>

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

        <Select
          id="payment_method"
          name="payment_method"
          value={reportForm.paymentMethod}
          theme={formTheme.select}
          disabled={
            reportForm.orderBy === 'merchant' ||
            reportForm.orderBy === 'marketplace'
          }
          onChange={(e) => {
            setReportForm((reportForm) => ({
              ...reportForm,
              paymentMethod: e.target.value as PaymentMethodCode,
            }))
          }}
        >
          <option value="">All</option>
          {paymentMethods.map((paymentMethod) => (
            <option key={paymentMethod.value} value={paymentMethod.value}>
              {paymentMethod.name}
            </option>
          ))}
        </Select>
      </div>

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

        <Select
          id="payment_status"
          name="payment_status"
          value={reportForm.paymentStatus}
          theme={formTheme.select}
          onChange={(e) => {
            setReportForm((reportForm) => ({
              ...reportForm,
              paymentStatus: e.target.value as PaymentStatus,
            }))
          }}
        >
          <option value="">All</option>
          {PAYMENT_STATUS_OPTIONS.map((paymentStatus) => (
            <option key={paymentStatus.value} value={paymentStatus.value}>
              {paymentStatus.name}
            </option>
          ))}
        </Select>
      </div>
    </React.Fragment>
  )
}

interface ReportForm {
  paymentMethod?: PaymentMethodCode | ''
  paymentStatus?: PaymentStatus | ''
  bookingMethod: BookingMethod
  startDate?: string | null
  endDate?: string | null
  orderBy?: OrderByType | ''
  reportType?: 'transaction' | 'commission'
  reportFor?: 'internal' | 'agent'
  agentId?: number | null
  marketplaceId?: number | null
  merchantId?: number | null
  partnerId?: number | null
}

export default function CreateReportModal(props: ModalCreateReportProps) {
  const { merchant } = useMerchant()
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
  const [reportForm, setReportForm] = useState<ReportForm>({
    paymentMethod: '',
    paymentStatus: '',
    startDate: null,
    endDate: null,
    agentId: null,
    marketplaceId: null,
    merchantId: null,
    bookingMethod: 'offline',
    orderBy: '',
    reportType: 'transaction',
    reportFor: 'internal',
  })

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

    try {
      setIsDownloadingPdf(true)

      const searchParams = new URLSearchParams({
        bookingMethod: reportForm.bookingMethod,
        paymentMethod: reportForm.paymentMethod ?? '',
        paymentStatus: reportForm.paymentStatus ?? '',
        startDate: reportForm.startDate ?? '',
        endDate: reportForm.endDate ?? '',
        orderBy: reportForm.orderBy ?? '',
        reportType: reportForm.reportType ?? 'transaction',
        reportFor: reportForm.reportFor ?? 'internal',
        agentId: reportForm.agentId?.toString() ?? '',
        marketplaceId: reportForm.marketplaceId?.toString() ?? '',
        merchantId: reportForm.merchantId?.toString() ?? '',
      })

      const reportFileUrl = getTransactionReportFileUrl(searchParams)

      await downloadDocument({
        merchantId: merchant?.id as number,
        url: reportFileUrl,
        filenameFallback: `${reportForm.reportType === 'commission' ? 'commission' : 'transaction'}-report.pdf`,
      })
    } catch {
      toast.error(
        reportForm.reportType === 'commission'
          ? 'Failed to download commission report'
          : 'Failed to download transaction report',
      )
    } finally {
      setIsDownloadingPdf(false)
    }
  }

  function handleActiveTabChange(activeTab: number) {
    switch (activeTab) {
      case 0: // Transaction Report
        setReportForm((prev) => ({
          ...prev,
          orderBy: '',
          merchantId: null,
          marketplaceId: null,
          agentId: null,
          reportType: 'transaction',
        }))
        break
      case 1: // Commission Report
        setReportForm((prev) => ({
          ...prev,
          orderBy: 'agent',
          merchantId: null,
          marketplaceId: null,
          agentId: null,
          reportType: 'commission',
        }))
        break
      default:
        setReportForm((prev) => ({
          ...prev,
          orderBy: '',
          merchantId: null,
          marketplaceId: null,
          agentId: null,
          reportType: 'transaction',
        }))
        break
    }
  }

  function handleChangeOrderBy(orderBy: OrderByType) {
    setReportForm((reportForm) => ({
      ...reportForm,
      merchantId: null,
      marketplaceId: null,
      agentId: null,
      paymentMethod:
        orderBy === 'merchant'
          ? 'ACCOUNT'
          : orderBy === 'marketplace'
            ? 'OTA'
            : '',
      orderBy: orderBy,
    }))
  }

  if (isDownloadingPdf) {
    return (
      <FullPageLoader
        message={
          reportForm.reportType === 'commission'
            ? 'Downloading commission report...'
            : 'Downloading transaction 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={handleDownloadReport}
        >
          <Tabs
            aria-label="Report For Tab"
            variant="underline"
            theme={tabTheme.tabs}
            className="w-full"
            onActiveTabChange={handleActiveTabChange}
          >
            {/* Transaction */}
            <TabItem
              title="Transaction"
              active={reportForm.reportType === 'transaction'}
            >
              <div className="space-y-4">
                {/* Order Placed By */}
                <div className="w-full">
                  <div className="block mb-2">
                    <Label htmlFor="order_placed_by" theme={formTheme.label}>
                      Order Placed By
                    </Label>
                  </div>

                  <Select
                    id="order_placed_by"
                    name="order_placed_by"
                    value={reportForm.orderBy}
                    theme={formTheme.select}
                    onChange={(e) => {
                      handleChangeOrderBy(e.target.value as OrderByType)
                    }}
                  >
                    <option value="">All</option>
                    {OFFLINE_ORDER_BY_OPTIONS.map((orderBy) => (
                      <option key={orderBy.value} value={orderBy.value}>
                        {orderBy.name}
                      </option>
                    ))}
                  </Select>
                </div>

                {/* Merchants */}
                {reportForm.orderBy === 'merchant' && (
                  <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 as number}
                      onChange={(e) => {
                        setReportForm((reportForm) => ({
                          ...reportForm,
                          merchantId: e.target.value
                            ? +e.target.value
                            : undefined,
                        }))
                      }}
                    >
                      <option value="">All</option>
                      {props.merchants.map((merchant) => (
                        <option key={merchant.id} value={merchant.id}>
                          {merchant.name}
                        </option>
                      ))}
                    </Select>
                  </div>
                )}

                {/* Marketplaces */}
                {reportForm.orderBy === 'marketplace' && (
                  <div className="w-full">
                    <div className="block mb-2">
                      <Label htmlFor="marketplace_id" theme={formTheme.label}>
                        Marketplace
                      </Label>
                    </div>

                    <Select
                      id="marketplace_id"
                      name="marketplace_id"
                      theme={formTheme.select}
                      value={reportForm.marketplaceId as number}
                      onChange={(e) => {
                        setReportForm((reportForm) => ({
                          ...reportForm,
                          marketplaceId: e.target.value
                            ? +e.target.value
                            : undefined,
                        }))
                      }}
                    >
                      <option value="">All</option>
                      {props.marketplaces.map((marketplace) => (
                        <option key={marketplace.id} value={marketplace.id}>
                          {marketplace.name}
                        </option>
                      ))}
                    </Select>
                  </div>
                )}

                {/* Agents */}
                {reportForm.orderBy === 'agent' && (
                  <AgentSelector
                    fullWidth
                    selectedAgentId={reportForm.agentId as number}
                    onSelectAgent={(agent) => {
                      setReportForm((reportForm) => ({
                        ...reportForm,
                        agentId: agent ? agent.id : undefined,
                      }))
                    }}
                  />
                )}

                <FilterForm
                  reportForm={reportForm}
                  setReportForm={setReportForm}
                />
              </div>
            </TabItem>

            {/* Commission */}
            <TabItem
              title="Commission"
              active={reportForm.reportType === 'commission'}
            >
              <div className="space-y-4">
                {/* Agent */}
                {reportForm.orderBy === 'agent' && (
                  <AgentSelector
                    fullWidth
                    selectedAgentId={reportForm.agentId as number}
                    onSelectAgent={(agent) => {
                      setReportForm((reportForm) => ({
                        ...reportForm,
                        agentId: agent ? agent.id : undefined,
                      }))
                    }}
                  />
                )}

                {/* Report For */}
                <div className="w-full">
                  <div className="block mb-2">
                    <Label htmlFor="report_for" theme={formTheme.label}>
                      Report For
                    </Label>
                  </div>
                  <Select
                    id="report_for"
                    name="report_for"
                    value={reportForm.reportFor}
                    theme={formTheme.select}
                    onChange={(e) => {
                      setReportForm((reportForm) => ({
                        ...reportForm,
                        reportFor: e.target.value as 'internal' | 'agent',
                      }))
                    }}
                  >
                    <option value="internal">Internal</option>
                    <option value="agent">Agent (B2B)</option>
                  </Select>
                </div>

                <FilterForm
                  reportForm={reportForm}
                  setReportForm={setReportForm}
                />
              </div>
            </TabItem>
          </Tabs>

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