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 SearchButton from '@/lib/components/buttons/SearchButton'
import buttonTheme from '@/lib/themes/button'
import { FastboatName, FastboatRoute } from '@/lib/types/product/fastboat'
import { BookingMethod, Trip } from '../../orders/types'
import { SearchFormProps } from '../types'
import { PaymentMethodCode } from '@/lib/types/payment'
import {
  PAYMENT_METHODS_BY_ORDER_TYPE,
  PAYMENT_METHODS_OPTIONS,
} from '@/lib/constants/payment'
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 AffiliatePartnerSelector from '@/lib/components/forms/AffiliatePartnerSelector'

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

export default function SearchForm({
  searchForm,
  fastboatNames,
  fastboatRoutes,
  merchants,
  marketplaces,
  handleSearch,
  setSearchForm,
}: Props) {
  const paymentMethods = searchForm.params.orderPlacedBy
    ? PAYMENT_METHODS_BY_ORDER_TYPE[
        searchForm.params.orderPlacedBy as OrderByType
      ]
    : PAYMENT_METHODS_OPTIONS

  function resetSearchParams() {
    setSearchForm({
      ...searchForm,
      params: {
        startDate: '',
        endDate: '',
        paymentMethod: '',
        refunded: '',
        bookingMethod: '',
        bookingCode: '',
        trip: '',
        fastboatNameId: '',
        fastboatRouteId: '',
        startDepartureDate: '',
        endDepartureDate: '',
        invoiceNumber: '',
        merchantId: '',
        agentId: '',
        marketplaceId: '',
        partnerId: '',
        orderPlacedBy: '',
        page: 1,
        limit: 10,
      },
    })
  }

  function handleChangeOrderBy(orderPlacedBy: OrderByType) {
    setSearchForm((searchForm) => ({
      ...searchForm,
      params: {
        ...searchForm.params,
        merchantId: undefined,
        marketplaceId: undefined,
        agentId: undefined,
        partnerId: undefined,
        orderPlacedBy,
      },
    }))
  }

  return (
    <form className="mt-10" onSubmit={handleSearch}>
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 w-full gap-4 max-w-7xl">
        {/* 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: searchForm.params?.startDate as DateType,
              endDate: searchForm.params?.endDate as DateType,
            }}
            onDateChange={(formattedDate: FormattedDate) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  startDate: formattedDate?.startDate ?? null,
                  endDate: formattedDate?.endDate ?? null,
                },
              })
            }}
          />
        </div>

        {/* Departure Date */}
        <div className="w-full max-w-96">
          <div className="mb-2 block">
            <Label htmlFor="departure_date" theme={formTheme.label}>
              Departure Date
            </Label>
          </div>

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

        {/* Booking Code */}
        <div>
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="booking_code">
              Booking Code
            </Label>
          </div>
          <TextInput
            theme={formTheme.textInput}
            id="booking_code"
            type="text"
            className="w-full max-w-96"
            placeholder="Booking Code"
            value={searchForm.params?.bookingCode}
            onChange={(e) =>
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  bookingCode: e.target.value,
                },
              })
            }
          />
        </div>

        {/* Invoice Number */}
        <div>
          <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={searchForm.params?.invoiceNumber}
            onChange={(e) =>
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  invoiceNumber: e.target.value,
                },
              })
            }
          />
        </div>

        {/* Trip */}
        <div>
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="trip">
              Trip
            </Label>
          </div>
          <Select
            className="w-full max-w-96"
            theme={formTheme.select}
            value={searchForm.params?.trip || ''}
            onChange={(e) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  trip: e.target.value as Trip | '',
                },
              })
            }}
          >
            <option value="">All</option>
            <option value="ONE_WAY">One Way</option>
            <option value="RETURN">Return</option>
          </Select>
        </div>

        {/* Port Route */}
        <div>
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="fastboat_route_id">
              Port Route
            </Label>
          </div>
          <Select
            id="fastboat_route_id"
            className="w-full max-w-96"
            theme={formTheme.select}
            value={searchForm.params?.fastboatRouteId || ''}
            onChange={(e) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  fastboatRouteId: e.target.value ? +e.target.value : '',
                },
              })
            }}
          >
            <option value="">All</option>
            {fastboatRoutes?.map((route) => (
              <option key={route.id} value={route.id}>
                {route.departure_harbor} &#8596; {route.arrival_harbor}
              </option>
            ))}
          </Select>
        </div>

        {/* Fast Boat Name ID */}
        <div>
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="fastboat_name_id">
              Boat Name
            </Label>
          </div>
          <Select
            id="fastboat_name_id"
            className="w-full max-w-96"
            theme={formTheme.select}
            value={searchForm.params?.fastboatNameId || ''}
            onChange={(e) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  fastboatNameId: e.target.value ? +e.target.value : '',
                },
              })
            }}
          >
            <option value="">All</option>
            {fastboatNames?.map((fastboatName) => (
              <option key={fastboatName.id} value={fastboatName.id}>
                {fastboatName.name}
              </option>
            ))}
          </Select>
        </div>

        {/* Payment Method */}
        <div>
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="payment_method">
              Payment Method
            </Label>
          </div>
          <Select
            className="w-full max-w-96"
            theme={formTheme.select}
            value={searchForm.params?.paymentMethod || ''}
            onChange={(e) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  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={searchForm.params.refunded}
            className="w-full max-w-96"
            onChange={(e) => {
              setSearchForm((searchForm) => ({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  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>
          <div className="block mb-2">
            <Label htmlFor="booking_method" theme={formTheme.label}>
              Booking Method
            </Label>
          </div>

          <Select
            id="booking_method"
            className="w-full max-w-96"
            theme={formTheme.select}
            onChange={(e) => {
              setSearchForm({
                ...searchForm,
                params: {
                  ...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>
          <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"
            className="w-full max-w-96"
            value={searchForm.params.orderPlacedBy || ''}
            onChange={(e) => handleChangeOrderBy(e.target.value as OrderByType)}
          >
            <option value="">All</option>
            {ORDER_BY_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.name}
              </option>
            ))}
          </Select>
        </div>

        {/* Merchants */}
        {searchForm.params.orderPlacedBy === 'merchant' && (
          <div>
            <div className="block mb-2">
              <Label htmlFor="merchant_id" theme={formTheme.label}>
                Merchant
              </Label>
            </div>

            <Select
              id="merchant_id"
              name="merchant_id"
              className="w-full max-w-96"
              theme={formTheme.select}
              value={searchForm.params.merchantId as number}
              onChange={(e) =>
                setSearchForm((searchForm) => ({
                  ...searchForm,
                  params: {
                    ...searchForm.params,
                    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 */}
        {searchForm.params.orderPlacedBy === 'marketplace' && (
          <div>
            <div className="block mb-2">
              <Label htmlFor="marketplace_id" theme={formTheme.label}>
                Marketplace
              </Label>
            </div>

            <Select
              id="marketplace_id"
              name="marketplace_id"
              className="w-full max-w-96"
              theme={formTheme.select}
              value={searchForm.params.marketplaceId as number}
              onChange={(e) =>
                setSearchForm((searchForm) => ({
                  ...searchForm,
                  params: {
                    ...searchForm.params,
                    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 */}
        {searchForm.params.orderPlacedBy === 'agent' && (
          <AgentSelector
            selectedAgentId={searchForm.params?.agentId as number}
            onSelectAgent={(agent) => {
              setSearchForm((searchForm) => ({
                ...searchForm,
                params: {
                  ...searchForm.params,
                  agentId: agent ? agent.id : undefined,
                },
              }))
            }}
          />
        )}

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

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

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