import React, { FormEvent } from 'react'
import { Button, Label, Select, TextInput } from 'flowbite-react'
import { DateType } from 'react-tailwindcss-datepicker'

import formTheme from '@/lib/themes/form'
import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import {
  PAYMENT_STATUS_LABELS,
  PaymentMethodCode,
  PaymentStatus,
} from '@/lib/types/payment'
import SearchButton from '@/lib/components/buttons/SearchButton'
import buttonTheme from '@/lib/themes/button'
import { BookingMethod } from '../../orders/types'
import { SearchFormProps } from '../types'
import { Merchant } from '@/app/(dashboard)/merchants/types'
import AgentSelector from '@/lib/components/forms/AgentSelector'
import PartnerSelector from '@/lib/components/forms/PartnerSelector'
import {
  PAYMENT_METHODS_BY_ORDER_TYPE,
  PAYMENT_METHODS_OPTIONS,
  PAYMENT_STATUS,
} from '@/lib/constants/payment'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { ORDER_BY_OPTIONS } from '@/lib/constants/order'
import AffiliatePartnerSelector from '@/lib/components/forms/AffiliatePartnerSelector'

interface Props {
  merchants: Merchant[]
  marketplaces: Marketplace[]
  searchForm: SearchFormProps
  handleSearch: (e: FormEvent) => void
  setSearchForm: React.Dispatch<React.SetStateAction<SearchFormProps>>
}

export default function SearchForm(props: Props) {
  const paymentMethods = props.searchForm.params?.orderBy
    ? PAYMENT_METHODS_BY_ORDER_TYPE[
        props.searchForm.params.orderBy as OrderByType
      ]
    : PAYMENT_METHODS_OPTIONS

  function resetSearchParams() {
    props.setSearchForm({
      ...props.searchForm,
      params: {
        paymentStatus: '',
        paymentMethod: '',
        startDate: '',
        endDate: '',
        merchantId: '',
        agentId: '',
        marketplaceId: '',
        partnerId: '',
        orderBy: '',
        invoiceNumber: '',
        page: 1,
        limit: 10,
      },
    })
  }

  return (
    <form className="mt-10" onSubmit={props.handleSearch}>
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 w-full gap-4 max-w-6xl">
        {/* Transaction Date */}
        <div className="w-full max-w-96">
          <div className="mb-2 block">
            <Label htmlFor="transaction_date" theme={formTheme.label}>
              Transaction Date
            </Label>
          </div>

          <DatePicker
            inputId="transaction_date"
            value={{
              startDate: props.searchForm.params?.startDate as DateType,
              endDate: props.searchForm.params?.endDate as DateType,
            }}
            onDateChange={(formattedDate: FormattedDate) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  startDate: formattedDate?.startDate ?? null,
                  endDate: formattedDate?.endDate ?? null,
                },
              })
            }}
          />
        </div>

        {/* Invoice Number */}
        <div className="w-full">
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="invoice_number">
              Invoice Number
            </Label>
          </div>
          <TextInput
            theme={formTheme.textInput}
            id="invoice_number"
            type="text"
            className="w-full max-w-96"
            placeholder="Invoice Number"
            value={props.searchForm.params?.invoiceNumber}
            onChange={(e) =>
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  invoiceNumber: e.target.value,
                },
              })
            }
          />
        </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"
            theme={formTheme.select}
            className="w-full max-w-96"
            onChange={(e) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  paymentMethod: e.target.value as PaymentMethodCode,
                },
              })
            }}
          >
            <option value="">All</option>
            {paymentMethods?.map((paymentMethod) => (
              <option
                key={paymentMethod.name}
                value={paymentMethod.value}
                selected={
                  paymentMethod.value === props.searchForm.params?.paymentMethod
                }
              >
                {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"
            theme={formTheme.select}
            value={props.searchForm.params?.paymentStatus || ''}
            className="w-full max-w-96"
            onChange={(e) => {
              props.setSearchForm((searchForm) => ({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  paymentStatus: e.target.value as PaymentStatus,
                },
              }))
            }}
          >
            <option value="">All</option>
            <option value={PAYMENT_STATUS.SUCCESS}>
              {PAYMENT_STATUS_LABELS[PAYMENT_STATUS.SUCCESS]}
            </option>
            <option value={PAYMENT_STATUS.PARTIALLY_REFUNDED}>
              {PAYMENT_STATUS_LABELS[PAYMENT_STATUS.PARTIALLY_REFUNDED]}
            </option>
            <option value={PAYMENT_STATUS.FULLY_REFUNDED}>
              {PAYMENT_STATUS_LABELS[PAYMENT_STATUS.FULLY_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"
            theme={formTheme.select}
            className="w-full max-w-96"
            onChange={(e) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  bookingMethod: e.target.value as BookingMethod,
                },
              })
            }}
          >
            <option value="">All</option>
            <option value="Online">Online</option>
            <option value="Offline">Offline</option>
          </Select>
        </div>

        {/* 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"
            theme={formTheme.select}
            className="w-full max-w-96"
            onChange={(e) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  agentId: undefined,
                  merchantId: undefined,
                  marketplaceId: undefined,
                  partnerId: undefined,
                  orderBy: e.target.value as OrderByType,
                },
              })
            }}
          >
            <option value="">All</option>
            {ORDER_BY_OPTIONS.map((orderBy) => (
              <option
                key={orderBy.value}
                value={orderBy.value}
                selected={orderBy.value === props.searchForm.params.orderBy}
              >
                {orderBy.name}
              </option>
            ))}
          </Select>
        </div>

        {/* Merchants */}
        {props.searchForm.params.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={props.searchForm.params.merchantId}
              onChange={(e) =>
                props.setSearchForm(() => ({
                  ...props.searchForm,
                  params: {
                    ...props.searchForm.params,
                    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 */}
        {props.searchForm.params.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={props.searchForm.params.marketplaceId}
              onChange={(e) =>
                props.setSearchForm(() => ({
                  ...props.searchForm,
                  params: {
                    ...props.searchForm.params,
                    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 */}
        {props.searchForm.params.orderBy === 'agent' && (
          <AgentSelector
            selectedAgentId={Number(props.searchForm.params?.agentId ?? 0)}
            onSelectAgent={(agent) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  agentId: agent ? agent.id : undefined,
                },
              })
            }}
          />
        )}

        {/* Travel Partners */}
        {props.searchForm.params.orderBy === 'travel_partner' && (
          <PartnerSelector
            selectedPartnerId={Number(props.searchForm.params?.partnerId ?? 0)}
            onSelectPartner={(partner) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  partnerId: partner ? partner.id : undefined,
                },
              })
            }}
          />
        )}

        {/* Affiliate Partners */}
        {props.searchForm.params.orderBy === 'affiliate_partner' && (
          <AffiliatePartnerSelector
            selectedPartnerId={Number(props.searchForm.params?.partnerId ?? 0)}
            onSelectPartner={(partner) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  partnerId: partner ? partner.id : undefined,
                },
              })
            }}
          />
        )}
      </div>

      {/* Action Buttons */}
      <div className="flex gap-4 mt-5">
        <SearchButton isProcessing={props.searchForm.searching} />
        <Button
          type="button"
          color="alternative"
          onClick={resetSearchParams}
          theme={buttonTheme.button}
        >
          Reset
        </Button>
      </div>
    </form>
  )
}
