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 buttonTheme from '@/lib/themes/button'
import formTheme from '@/lib/themes/form'
import modalTheme from '@/lib/themes/modal'
import tabTheme from '@/lib/themes/tab'
import { FastboatName, FastboatRoute } from '@/lib/types/product/fastboat'
import { getFastboatSalesReportFileUrl } from '@/lib/services/fastboat-sales-services'
import { downloadDocument } from '@/lib/services/file-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { BookingMethod, Trip } from '../../orders/types'
import { useMerchant } from '@/lib/context/MerchantContext'
import { ORDER_BY_OPTIONS } from '@/lib/constants/order'
import { Merchant } from '@/app/(dashboard)/merchants/types'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import AgentSelector from '@/lib/components/forms/AgentSelector'
import PartnerSelector from '@/lib/components/forms/PartnerSelector'
import { PaymentMethodCode } from '@/lib/types/payment'
import {
  PAYMENT_METHODS_BY_ORDER_TYPE,
  PAYMENT_METHODS_OPTIONS,
} from '@/lib/constants/payment'
import AffiliatePartnerSelector from '@/lib/components/forms/AffiliatePartnerSelector'

interface CreateReportModalProps {
  reportModal: ModalState
  fastboatNames: FastboatName[]
  fastboatRoutes: FastboatRoute[]
  merchants: Merchant[]
  marketplaces: Marketplace[]
  setReportModal: Dispatch<SetStateAction<ModalState>>
}

interface ReportFormProps {
  date: FormattedDate
  trip: Trip | 'ALL'
  departureDate: FormattedDate
  orderPlacedBy: OrderByType | ''
  bookingMethod?: BookingMethod | ''
  paymentMethod?: PaymentMethodCode | ''
  refunded: number | string
  fastboatNameId?: string
  fastboatRouteId?: string
  reportFor: 'internal' | 'operator'
  merchantId?: number
  agentId?: number
  marketplaceId?: number
  partnerId?: number
}

const FilterForm: React.FC<{
  fastboatNames: FastboatName[]
  fastboatRoutes: FastboatRoute[]
  reportForm: ReportFormProps
  merchants: Merchant[]
  marketplaces: Marketplace[]
  setReportForm: Dispatch<SetStateAction<ReportFormProps>>
}> = ({
  fastboatNames,
  fastboatRoutes,
  reportForm,
  merchants,
  marketplaces,
  setReportForm,
}) => {
  function handleChangeOrderBy(e: React.ChangeEvent<HTMLSelectElement>) {
    const selectedOrderBy = e.target.value as ReportFormProps['orderPlacedBy']

    setReportForm((prev) => ({
      ...prev,
      orderPlacedBy: selectedOrderBy,
      merchantId: undefined,
      agentId: undefined,
      marketplaceId: undefined,
      partnerId: undefined,
      paymentMethod:
        selectedOrderBy === 'merchant'
          ? 'ACCOUNT'
          : selectedOrderBy === 'marketplace'
            ? 'OTA'
            : '',
    }))
  }

  const paymentMethods = reportForm.orderPlacedBy
    ? PAYMENT_METHODS_BY_ORDER_TYPE[reportForm.orderPlacedBy as OrderByType]
    : PAYMENT_METHODS_OPTIONS

  return (
    <div className="space-y-4">
      {reportForm.reportFor === 'internal' && (
        <React.Fragment>
          {/* Order Placed By */}
          <div className="w-full">
            <div className="mb-2 block">
              <Label theme={formTheme.label} htmlFor="order_placed_by">
                Order Placed By
              </Label>
            </div>
            <Select
              theme={formTheme.select}
              name="order_placed_by"
              id="order_placed_by"
              value={reportForm.orderPlacedBy}
              onChange={handleChangeOrderBy}
            >
              <option value="">All</option>
              {ORDER_BY_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.name}
                </option>
              ))}
            </Select>
          </div>

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

          {/* Marketplaces */}
          {reportForm.orderPlacedBy === '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}
                onChange={(e) =>
                  setReportForm((prev) => ({
                    ...prev,
                    marketplaceId: e.target.value ? +e.target.value : undefined,
                  }))
                }
              >
                <option value="">All</option>
                {marketplaces.map((marketplace) => (
                  <option key={marketplace.id} value={marketplace.id}>
                    {marketplace.name}
                  </option>
                ))}
              </Select>
            </div>
          )}

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

          {/* Travel Partners */}
          {reportForm.orderPlacedBy === 'travel_partner' && (
            <PartnerSelector
              fullWidth
              selectedPartnerId={reportForm.partnerId}
              onSelectPartner={(partner) => {
                setReportForm((prev) => ({
                  ...prev,
                  partnerId: partner ? partner.id : undefined,
                }))
              }}
            />
          )}

          {/* Affiliate Partners */}
          {reportForm.orderPlacedBy === 'affiliate_partner' && (
            <AffiliatePartnerSelector
              fullWidth
              selectedPartnerId={reportForm.partnerId}
              onSelectPartner={(partner) => {
                setReportForm((prev) => ({
                  ...prev,
                  partnerId: partner ? partner.id : undefined,
                }))
              }}
            />
          )}

          {/* Payment Method */}
          <div>
            <div className="mb-2 block">
              <Label theme={formTheme.label} htmlFor="payment_method">
                Payment Method
              </Label>
            </div>
            <Select
              className="w-full"
              theme={formTheme.select}
              value={reportForm?.paymentMethod || ''}
              disabled={
                reportForm.orderPlacedBy === 'merchant' ||
                reportForm.orderPlacedBy === 'marketplace'
              }
              onChange={(e) => {
                setReportForm({
                  ...reportForm,
                  paymentMethod: e.target.value as PaymentMethodCode | '',
                })
              }}
            >
              <option value="">All</option>
              {paymentMethods.map((method) => (
                <option key={method.value} value={method.value}>
                  {method.name}
                </option>
              ))}
            </Select>
          </div>

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

            <Select
              id="refund_status"
              theme={formTheme.select}
              value={reportForm.refunded}
              className="w-full"
              onChange={(e) => {
                setReportForm((reportForm) => ({
                  ...reportForm,
                  refunded: e.target.value === '' ? '' : +e.target.value,
                }))
              }}
            >
              <option value="">All</option>
              <option value="0">Not Refunded</option>
              <option value="1">Refunded</option>
            </Select>
          </div>

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

            <Select
              id="booking_method"
              name="booking_method"
              theme={formTheme.select}
              value={reportForm.bookingMethod || ''}
              onChange={(e) =>
                setReportForm((prev) => ({
                  ...prev,
                  bookingMethod: e.target
                    .value as ReportFormProps['bookingMethod'],
                }))
              }
            >
              <option value="">All</option>
              <option value="online">Online</option>
              <option value="offline">Offline</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?.date?.startDate
                    ? new Date(reportForm?.date?.startDate)
                    : null,
                  endDate: reportForm?.date?.endDate
                    ? new Date(reportForm?.date?.endDate)
                    : null,
                }}
                onDateChange={(formattedDate: FormattedDate) =>
                  setReportForm((prev) => ({
                    ...prev,
                    date: formattedDate,
                  }))
                }
              />
            </div>
          </div>
        </React.Fragment>
      )}

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

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

        <Select
          id="fastboat_name_id"
          name="fastboat_name_id"
          theme={formTheme.select}
          value={reportForm.fastboatNameId || ''}
          onChange={(e) => {
            setReportForm((prev) => ({
              ...prev,
              fastboatNameId: e.target.value,
            }))
          }}
        >
          <option value="">All</option>
          {fastboatNames?.map((fastboatName) => (
            <option key={fastboatName.id} value={fastboatName.id}>
              {fastboatName.name}
            </option>
          ))}
        </Select>
      </div>

      {/* Trip */}
      <div className="w-full">
        <div className="mb-2 block">
          <Label theme={formTheme.label} htmlFor="trip">
            Trip
          </Label>
        </div>
        <Select
          theme={formTheme.select}
          name="trip"
          id="trip"
          defaultValue="all"
          onChange={(e) =>
            setReportForm((prev) => ({
              ...prev,
              trip: e.target.value as ReportFormProps['trip'],
            }))
          }
          value={reportForm.trip}
        >
          <option value="ALL">All</option>
          <option value="ONE_WAY">One Way</option>
          <option value="RETURN">Return</option>
        </Select>
      </div>

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

        <Select
          theme={formTheme.select}
          name="fastboat_route_id"
          id="fastboat_route_id"
          value={reportForm.fastboatRouteId}
          onChange={(e) =>
            setReportForm((prev) => ({
              ...prev,
              fastboatRouteId: e.target
                .value as ReportFormProps['fastboatRouteId'],
            }))
          }
        >
          <option value="">All</option>
          {fastboatRoutes?.map((route) => (
            <option key={route.id} value={route.id}>
              {route.departure_harbor} &#8596; {route.arrival_harbor}
            </option>
          ))}
        </Select>
      </div>
    </div>
  )
}

export default function CreateReportModal(props: CreateReportModalProps) {
  const { merchant } = useMerchant()
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
  const [reportForm, setReportForm] = useState<ReportFormProps>({
    reportFor: 'internal',
    trip: 'ALL',
    orderPlacedBy: '',
    fastboatNameId: '',
    bookingMethod: '',
    paymentMethod: '',
    refunded: '',
    merchantId: undefined,
    agentId: undefined,
    marketplaceId: undefined,
    partnerId: undefined,
    date: { startDate: null, endDate: null },
    departureDate: { startDate: null, endDate: null },
  })

  function handleActiveTabChange(activeTab: number) {
    switch (activeTab) {
      case 0: // Internal
        setReportForm({
          ...reportForm,
          reportFor: 'internal',
        })
        break
      case 1: // Operator
        setReportForm({
          ...reportForm,
          reportFor: 'operator',
        })
        break
    }
  }

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

    try {
      setIsDownloadingPdf(true)

      const searchParams = new URLSearchParams({
        trip: reportForm.trip,
        orderPlacedBy: reportForm.orderPlacedBy,
        paymentMethod: reportForm.paymentMethod ?? '',
        refunded: reportForm.refunded.toString(),
        bookingMethod: reportForm.bookingMethod ?? '',
        fastboatNameId: reportForm.fastboatNameId ?? '',
        fastboatRouteId: reportForm.fastboatRouteId ?? '',
        reportFor: reportForm.reportFor,
        startDate: reportForm.date.startDate ?? '',
        endDate: reportForm.date.endDate ?? '',
        startDepartureDate: reportForm.departureDate.startDate ?? '',
        endDepartureDate: reportForm.departureDate.endDate ?? '',
        merchantId: reportForm.merchantId ? String(reportForm.merchantId) : '',
        agentId: reportForm.agentId ? String(reportForm.agentId) : '',
        marketplaceId: reportForm.marketplaceId
          ? String(reportForm.marketplaceId)
          : '',
        partnerId: reportForm.partnerId ? String(reportForm.partnerId) : '',
      })

      const reportFileUrl = getFastboatSalesReportFileUrl(searchParams)

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

  if (isDownloadingPdf) {
    return <FullPageLoader message="Downloading fast boat sales 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 Fast Boat Sales 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}
          >
            {/* Internal */}
            <TabItem active title="Internal">
              <FilterForm
                merchants={props.merchants}
                marketplaces={props.marketplaces}
                fastboatRoutes={props.fastboatRoutes}
                fastboatNames={props.fastboatNames}
                reportForm={reportForm}
                setReportForm={setReportForm}
              />
            </TabItem>

            {/* Operator */}
            <TabItem title="Operator">
              <FilterForm
                merchants={props.merchants}
                marketplaces={props.marketplaces}
                fastboatRoutes={props.fastboatRoutes}
                fastboatNames={props.fastboatNames}
                reportForm={reportForm}
                setReportForm={setReportForm}
              />
            </TabItem>
          </Tabs>

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