'use client'

import React, { useEffect, useState, Dispatch, SetStateAction } from 'react'
import { useFormContext } from 'react-hook-form'
import { formSchema } from '.'
import { z } from 'zod'
import {
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from '@/components/shadcn/ui/form'
import { RadioGroup, RadioGroupItem } from '@/components/shadcn/ui/radio-group'
import { Label } from '@/components/shadcn/ui/label'
import { AlertCircle, CheckCircle2, Zap } from 'lucide-react'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/shadcn/ui/select'
import { usePaymentChannel } from '@/lib/hooks/usePaymentChannel'
import { useAppSelector } from '@/lib/redux-hooks'
import { PaymentChannel } from '@/lib/types/payment'
import { useCurrency } from '@/lib/hooks/useCurrency'
import { Order } from '@/lib/types/order'
import Image from 'next/image'

type FormValues = z.infer<typeof formSchema>

interface PaymentMethodFormProps {
  order: Order | null
  setOrder: Dispatch<SetStateAction<Order | null>>
}

const PaymentMethodForm: React.FC<PaymentMethodFormProps> = ({
  order,
  setOrder,
}) => {
  const { format: formatPrice } = useCurrency()
  const currency = useAppSelector((state) => state.currency)

  const merchant = useAppSelector((state) => state.merchant)
  const form = useFormContext<FormValues>()
  const { data: paymentChannels, isLoading } = usePaymentChannel()
  const [selectedPaymentChannel, setSelectedPaymentChannel] =
    useState<PaymentChannel | null>(null)

  const selectedPaymentChannelCode = form.watch('payment_channel_code')

  useEffect(() => {
    if (selectedPaymentChannelCode) {
      const paymentChannel = paymentChannels.find(
        (paymentChannel) => paymentChannel.code === selectedPaymentChannelCode,
      )

      setSelectedPaymentChannel(paymentChannel)
      applySurcharge(paymentChannel)
    } else {
      setSelectedPaymentChannel(null)
      setOrder((prev) => ({
        ...prev,
        surcharge: 0,
        total_amount: prev?.sub_total,
      }))
    }
  }, [selectedPaymentChannelCode])

  const applySurcharge = (paymentChannel: PaymentChannel) => {
    let surcharge: number = 0

    switch (paymentChannel.code) {
      case 'CREDIT_CARD':
        surcharge =
          (paymentChannel.transaction_fee / 100) * order?.sub_total +
          paymentChannel.additional_fee

        // Round up the surcharge
        surcharge = Math.round(surcharge)
        break
      case 'VIRTUAL_ACCOUNT_BCA':
      case 'VIRTUAL_ACCOUNT_BANK_MANDIRI':
      case 'VIRTUAL_ACCOUNT_BNI':
      case 'VIRTUAL_ACCOUNT_BRI':
      case 'VIRTUAL_ACCOUNT_CIMB':
      case 'VIRTUAL_ACCOUNT_BANK_SYARIAH_MANDIRI':
        surcharge = paymentChannel.transaction_fee
        break
      case 'EMONEY_LINKAJA':
      case 'EMONEY_OVO':
      case 'EMONEY_SHOPEE_PAY':
        surcharge = (paymentChannel.transaction_fee / 100) * order?.sub_total

        // Round up the surcharge
        surcharge = Math.round(surcharge)
        break
      case 'ONLINE_TO_OFFLINE_ALFA':
        surcharge = paymentChannel.transaction_fee
        break
      case 'ONLINE_TO_OFFLINE_INDOMARET':
        surcharge =
          paymentChannel.transaction_fee + paymentChannel.additional_fee
        break
    }

    setOrder((prev) => ({
      ...prev,
      surcharge,
      total_amount: prev?.sub_total + surcharge,
    }))
  }

  const renderSurchargeInformation = (paymentChannel: PaymentChannel) => {
    const transactionFee = paymentChannel?.is_percentage
      ? `${paymentChannel?.transaction_fee} %`
      : formatPrice(paymentChannel?.transaction_fee, currency.code)

    if (paymentChannel?.additional_fee) {
      const additionalFee = formatPrice(
        paymentChannel?.additional_fee,
        currency.code,
      )

      return `The ${selectedPaymentChannel?.name} surcharge of ${transactionFee} + ${additionalFee} is imposed by the bank.`
    }

    return `The ${selectedPaymentChannel?.name} surcharge of ${transactionFee} is imposed by the bank.`
  }

  return (
    <section className="w-full mt-10">
      <h2 className="text-xl md:text-2xl font-semibold">Payment Method</h2>

      <div className="space-y-6 mt-4">
        <FormField
          control={form.control}
          name="payment_method_code"
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <RadioGroup
                  onValueChange={field.onChange}
                  value={field.value}
                  className="space-y-4"
                >
                  {order.payment_method_code === 'SECURE_PAYMENT' && (
                    <div className="border rounded-md p-4 payment-option">
                      <div className="flex items-start space-x-3">
                        <RadioGroupItem
                          value="SECURE_PAYMENT"
                          id="SECURE_PAYMENT"
                          className="mt-1"
                        />

                        <div className="flex-1">
                          <Label
                            htmlFor="SECURE_PAYMENT"
                            className="font-medium block mb-1"
                          >
                            Secure Payment
                          </Label>
                          <p className="text-sm text-gray-500">
                            Support various payment channels, ranging from
                            e-wallet through Credit Card Payment
                          </p>
                          <div className="flex items-center gap-1 bg-gray-100 px-3 py-2 rounded-md mt-2 w-fit">
                            <Zap size={16} className="text-yellow-400" />
                            <span className="text-xs">
                              Instant Confirmation
                            </span>
                          </div>

                          {order.payment_method_code === 'SECURE_PAYMENT' && (
                            <div className="mt-4 animate-slide-in">
                              {selectedPaymentChannel ? (
                                <div className="p-4 border border-blue-200 rounded-md bg-blue-50 mb-4">
                                  <div className="flex items-start gap-2">
                                    <div>
                                      <AlertCircle
                                        size={16}
                                        className="mt-1 text-blue-800"
                                      />
                                    </div>
                                    <p className="text-sm text-blue-800">
                                      {renderSurchargeInformation(
                                        selectedPaymentChannel,
                                      )}
                                    </p>
                                  </div>
                                </div>
                              ) : null}

                              <FormField
                                name="payment_channel_code"
                                control={form.control}
                                render={({ field }) => (
                                  <FormItem>
                                    <Select
                                      onValueChange={field.onChange}
                                      value={field.value}
                                    >
                                      <FormControl>
                                        <SelectTrigger className="max-w-full overflow-hidden">
                                          <SelectValue
                                            placeholder="Visa/MasterCard/JCB/AMEX"
                                            className="truncate"
                                          />
                                        </SelectTrigger>
                                      </FormControl>
                                      <SelectContent>
                                        {isLoading ? null : (
                                          <React.Fragment>
                                            {paymentChannels.map(
                                              (paymentChannel) =>
                                                paymentChannel.disabled ? null : (
                                                  <SelectItem
                                                    value={paymentChannel.code}
                                                    key={paymentChannel.code}
                                                  >
                                                    {paymentChannel.name}
                                                  </SelectItem>
                                                ),
                                            )}
                                          </React.Fragment>
                                        )}
                                      </SelectContent>
                                      <FormMessage />
                                    </Select>
                                  </FormItem>
                                )}
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Bank Transfer Option */}
                  {order.payment_method_code === 'BANK_TRANSFER' && (
                    <div className="border rounded-md p-4 payment-option">
                      <div className="flex items-start space-x-3">
                        <RadioGroupItem
                          value="BANK_TRANSFER"
                          id="BANK_TRANSFER"
                          className="mt-1"
                        />
                        <div className="flex-1">
                          <Label
                            htmlFor="BANK_TRANSFER"
                            className="font-medium block mb-1"
                          >
                            Bank Transfer
                          </Label>
                          <p className="text-sm text-gray-500">
                            Transfer to bank account below. For faster
                            international payment, we recommend using{' '}
                            <span className="font-medium text-green-800">
                              Wise Transfer
                            </span>
                            . Please upload the payment proof after transfer.
                          </p>

                          <div className="flex items-center flex-wrap gap-2">
                            <div className="flex items-center gap-1 bg-gray-100 px-3 py-2 rounded-md mt-2 w-fit">
                              <CheckCircle2
                                size={16}
                                className="text-green-400"
                              />
                              <span className="text-xs">
                                Manual Confirmation
                              </span>
                            </div>

                            <div className="flex items-center gap-1 bg-green-100 px-3 py-2 rounded-md mt-2 w-fit">
                              <Image
                                className="w-8"
                                src="/images/wise.png"
                                alt="Wise Transfer"
                                width={32}
                                height={16}
                              />
                              <span className="text-xs">Recommended</span>
                            </div>
                          </div>

                          {order.payment_method_code === 'BANK_TRANSFER' && (
                            <div className="mt-4 animate-slide-in">
                              <div>
                                <p className="text-sm font-medium">
                                  Please make a payment transfer through the
                                  following bank with total amount{' '}
                                  <b>
                                    {formatPrice(
                                      order?.total_amount ?? 0,
                                      currency?.code,
                                    )}
                                  </b>
                                </p>
                                <div className="mt-2">
                                  <Image
                                    className="w-36 h-auto mt-6 mb-2"
                                    alt={
                                      merchant?.bank_transfer_channel?.bank_name
                                    }
                                    src={
                                      merchant?.bank_transfer_channel?.bank_logo
                                    }
                                    width={144}
                                    height={72}
                                  />
                                  <p className="text-lg font-semibold mt-4">
                                    {merchant?.bank_transfer_channel?.bank_name}
                                  </p>
                                  <p className="text-sm font-medium mt-2">
                                    Account Name:{' '}
                                    {
                                      merchant?.bank_transfer_channel
                                        ?.account_name
                                    }
                                  </p>
                                  <p className="text-sm font-medium mt-2">
                                    Account Number:{' '}
                                    {
                                      merchant?.bank_transfer_channel
                                        ?.account_number
                                    }
                                  </p>
                                  <p className="text-sm font-medium mt-2">
                                    Swift Code:{' '}
                                    {
                                      merchant?.bank_transfer_channel
                                        ?.swift_code
                                    }
                                  </p>
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </RadioGroup>
              </FormControl>

              <FormMessage />
            </FormItem>
          )}
        />
      </div>
    </section>
  )
}

export default PaymentMethodForm
