'use client'

import React from 'react'
import { Separator } from '@/components/shadcn/ui/separator'
import { Button } from '@/components/shadcn/ui/button'
import Spinner from '@/components/Spinner'
import {
  PaymentChannel,
  PaymentMethod,
  PaymentStatus,
} from '@/lib/types/payment'
import PaymentInfo from '@/components/payments/PaymentInfo'

interface DokuPaymentDetailProps {
  paymentMethod: PaymentMethod
  paymentChannel: PaymentChannel
  paymentStatus: PaymentStatus
  paymentUrl: string
  checkingStatus: boolean
  checkPaymentStatus: () => void
}

const DokuPaymentDetail: React.FC<DokuPaymentDetailProps> = ({
  paymentMethod,
  paymentChannel,
  paymentStatus,
  paymentUrl,
  checkingStatus,
  checkPaymentStatus,
}) => {
  const safeRedirect = (url: string) => {
    const newWindow = window.open(url, '_blank')

    if (newWindow) {
      newWindow.opener = null
    }
  }

  return (
    <React.Fragment>
      <PaymentInfo
        paymentMethod={paymentMethod}
        paymentChannel={paymentChannel}
        paymentStatus={paymentStatus}
      />

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

          <div className="mt-2">
            <Button
              type="button"
              variant="black"
              className={`w-full bg-blue-800 hover:bg-blue-700 text-white py-6 mt-2`}
              disabled={checkingStatus}
              onClick={() => {
                safeRedirect(paymentUrl)
              }}
            >
              {paymentStatus === 'FAILED' ? 'RETRY PAYMENT' : 'PAY NOW'}
            </Button>

            <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>
          </div>
        </React.Fragment>
      )}
    </React.Fragment>
  )
}

export default DokuPaymentDetail
