'use client'

import { Button } from '@/components/shadcn/ui/button'
import { Separator } from '@/components/shadcn/ui/separator'
import { useAppSelector } from '@/lib/redux-hooks'
import { BankTransferPaymentProof } from '@/lib/types/order'
import { ApprovalStatus } from '@/lib/types/order'
import { ImageUp, Info } from 'lucide-react'
import React, { FormEvent, useRef, useState } from 'react'
import * as fileUpload from '@/lib/utils/file-upload'
import { SUPPORTED_FORMATS } from '@/lib/constants/file'
import paymentService from '@/lib/services/payment-service'
import Spinner from '@/components/Spinner'
import { useCurrency } from '@/lib/hooks/useCurrency'
import { ModalAlert } from '@/components/modal/ModalAlert'
import { useModalAlert } from '@/lib/hooks/useModalAlert'
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from '@/components/shadcn/ui/alert'
import { PaymentMethod, PaymentStatus } from '@/lib/types/payment'
import PaymentInfo from '@/components/payments/PaymentInfo'

interface BankTransferPaymentDetailProps {
  invoiceNumber: string
  paymentStatus: PaymentStatus
  paymentMethod: PaymentMethod
  bankTransferPaymentProof: BankTransferPaymentProof | null
  totalAmount: number
  checkingStatus: boolean
  checkPaymentStatus: () => void
}

const BankTransferPaymentDetail: React.FC<BankTransferPaymentDetailProps> = ({
  invoiceNumber,
  paymentStatus,
  paymentMethod,
  bankTransferPaymentProof,
  totalAmount,
  checkingStatus,
  checkPaymentStatus,
}) => {
  const { format } = useCurrency()
  const transferProofRef = useRef<HTMLInputElement>(null)
  const merchant = useAppSelector((state) => state.merchant)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [justSubmitted, setJustSubmitted] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const {
    open: modalAlertOpened,
    setOpen: setModalAlertOpened,
    alertOptions,
    showSuccessAlert,
    showInfoAlert,
    showErrorAlert,
  } = useModalAlert()

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    try {
      const file = event.target.files?.[0] || null

      if (!file) return

      fileUpload.checkSingleFormat(file)
      fileUpload.checkSingleSize(file)

      setSelectedFile(file)
    } catch (e: any) {
      alert(e.message)
    }
  }

  const renderPaymentProofStatusAlert = (status: ApprovalStatus) => {
    switch (status) {
      case 'PENDING':
        return (
          <Alert variant="amber">
            <Info />
            <AlertTitle>Your payment proof is being verified</AlertTitle>
            <AlertDescription>
              <p>
                We are currently reviewing your payment proof. If you need
                further assistance, you could reach us via email on{' '}
                <a
                  href={`mailto:${merchant?.business_profile?.email}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.email}
                  </span>
                </a>{' '}
                or WhatsApp at{' '}
                <a
                  href={`https://wa.me/${merchant?.business_profile?.last_booking_phone}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.last_booking_phone}
                  </span>
                </a>
                .
              </p>
            </AlertDescription>
          </Alert>
        )
      case 'APPROVED':
        return (
          <Alert variant="success">
            <Info />
            <AlertTitle>Your payment proof has been approved</AlertTitle>
            <AlertDescription>
              <p>
                Your e-ticket and/or voucher already sent to your email. If you
                don&apos;t receive any email yet, please check your spam or junk
                folder. For further assistance, you could reach us via email on{' '}
                <a
                  href={`mailto:${merchant?.business_profile?.email}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.email}
                  </span>
                </a>{' '}
                or WhatsApp at{' '}
                <a
                  href={`https://wa.me/${merchant?.business_profile?.last_booking_phone}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.last_booking_phone}
                  </span>
                </a>
                .
              </p>
            </AlertDescription>
          </Alert>
        )
      case 'REJECTED':
        return (
          <Alert variant="destructive">
            <Info />
            <AlertTitle>Your payment proof was rejected</AlertTitle>
            <AlertDescription>
              <p>
                Unfortunately, your payment proof was rejected. Please upload a
                valid payment proof. For further assistance, you could reach us
                via email on{' '}
                <a
                  href={`mailto:${merchant?.business_profile?.email}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.email}
                  </span>
                </a>{' '}
                or WhatsApp at{' '}
                <a
                  href={`https://wa.me/${merchant?.business_profile?.last_booking_phone}`}
                  className="underline"
                >
                  <span className="font-medium">
                    {merchant?.business_profile?.last_booking_phone}
                  </span>
                </a>
                .
              </p>
            </AlertDescription>
          </Alert>
        )
    }
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault()

    if (!selectedFile) {
      showInfoAlert(
        'Please upload payment proof',
        'Please upload payment proof before submitting',
      )
      return
    }

    try {
      setSubmitting(true)

      await paymentService.bankTransferPayment(invoiceNumber, selectedFile)

      setJustSubmitted(true)
      showSuccessAlert(
        'Payment Proof Submitted',
        'Please regulary check your email for our payment approval. Once it approved you will receive the tickets and invoice of your order. If you need further assistance you could reach us via email on ' +
          `${merchant?.business_profile?.email} or WhatsApp at ${merchant?.business_profile?.last_booking_phone}.`,
      )
    } catch (error: any) {
      showErrorAlert(
        'Failed to submit payment proof',
        error?.response?.data?.message ||
          error?.message ||
          'Failed to submit payment proof',
      )
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <React.Fragment>
      <PaymentInfo
        paymentMethod={paymentMethod}
        paymentStatus={paymentStatus}
        showBankDetails={true}
        bankTransferChannel={merchant?.bank_transfer_channel}
      />

      {paymentStatus === 'PENDING' && (
        <React.Fragment>
          <Separator className="my-4" />

          <div className="space-y-4">
            {justSubmitted && renderPaymentProofStatusAlert('PENDING')}

            {bankTransferPaymentProof && !justSubmitted && (
              <React.Fragment>
                {renderPaymentProofStatusAlert(bankTransferPaymentProof.status)}
              </React.Fragment>
            )}

            {justSubmitted ||
              (bankTransferPaymentProof?.status === 'PENDING' && (
                <Button
                  type="button"
                  variant="ghost"
                  className={`py-6 mt-2 w-full bg-gray-200 hover:bg-gray-300 flex items-center gap-2 justify-center`}
                  disabled={checkingStatus}
                  onClick={checkPaymentStatus}
                >
                  {checkingStatus ? (
                    <React.Fragment>
                      <Spinner color="secondary" size="sm" />
                      Checking...
                    </React.Fragment>
                  ) : (
                    <React.Fragment>CHECK PAYMENT STATUS</React.Fragment>
                  )}
                </Button>
              ))}

            {(!bankTransferPaymentProof ||
              bankTransferPaymentProof.status === 'REJECTED') &&
            !justSubmitted ? (
              <React.Fragment>
                <p className="text-sm text-gray-700">
                  Please make a payment transfer through the following bank with
                  the provided total amount {format(totalAmount ?? 0, 'IDR')}
                </p>

                <form onSubmit={handleSubmit}>
                  <div className="space-y-2">
                    <div className="text-sm text-gray-500">
                      Proof of Payment <span className="text-red-500">*</span>
                    </div>
                    <button
                      type="button"
                      className="border border-dashed border-gray-300 rounded-md p-4 text-center cursor-pointer hover:bg-gray-100 transition-colors w-full"
                      onClick={() => {
                        transferProofRef?.current?.click()
                      }}
                    >
                      <div className="flex items-center gap-2">
                        <ImageUp className="h-5 w-5 text-gray-400" />
                        <span
                          className={`text-sm ${selectedFile ? '' : 'text-gray-500'} overflow-hidden text-ellipsis text-nowrap`}
                        >
                          {selectedFile
                            ? selectedFile.name
                            : 'Select a file...'}
                        </span>
                      </div>
                    </button>
                    <span className="text-sm text-red-500">
                      *Please upload file that is not larger than 2MB
                    </span>
                    <input
                      ref={transferProofRef}
                      type="file"
                      className="hidden"
                      accept={SUPPORTED_FORMATS.join(',')}
                      onChange={handleFileChange}
                    />
                  </div>

                  <Button
                    type="submit"
                    disabled={submitting}
                    className="w-full bg-blue-800 hover:bg-blue-700 text-white py-6 mt-2"
                  >
                    {submitting ? (
                      <>
                        <Spinner color="white" size="sm" />
                        <span className="ml-2">CONFIRMING...</span>
                      </>
                    ) : (
                      <>
                        <span>CONFIRM PAYMENT</span>
                      </>
                    )}
                  </Button>
                </form>
              </React.Fragment>
            ) : null}
          </div>
        </React.Fragment>
      )}

      <ModalAlert
        open={modalAlertOpened}
        onOpenChange={setModalAlertOpened}
        {...alertOptions}
      />
    </React.Fragment>
  )
}

export default BankTransferPaymentDetail
