'use client'

import React, { SetStateAction, Dispatch, useState, useEffect } from 'react'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/shadcn/ui/form'
import BillingForm from './BillingForm'
import PaymentMethodForm from './PaymentMethodForm'
import { Checkbox } from '@/components/shadcn/ui/checkbox'
import { Button } from '@/components/shadcn/ui/button'
import { clearCart } from '@/lib/features/cart/cartSlice'
import { useAppDispatch, useAppSelector } from '@/lib/redux-hooks'
import { PaymentChannelCode } from '@/lib/types/payment'
import axios from 'axios'
import { useRouter } from 'next/navigation'
import { Order } from '@/lib/types/order'
import { useModalAlert } from '@/lib/hooks/useModalAlert'
import { ModalAlert } from '@/components/modal/ModalAlert'
import Spinner from '@/components/Spinner'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/shadcn/ui/dialog'

const PHONE_NUMBER_REGEX = /^\+(?:[0-9] ?){6,14}[0-9]$/

export const formSchema = z
  .object({
    billing_name: z
      .string({
        required_error: 'Name is required',
      })
      .min(1, {
        message: 'Name is required',
      })
      .max(255, { message: 'Name must be less than 255 characters' }),
    billing_email: z
      .string({ required_error: 'Email is required' })
      .email('Please enter a valid email address'),
    billing_phone: z
      .string()
      .regex(PHONE_NUMBER_REGEX, 'Please enter a valid phone number'),
    payment_method_code: z.enum(
      [
        'SECURE_PAYMENT',
        'BANK_TRANSFER',
        'CASH',
        'EDC',
        'PAY_ON_ARRIVAL',
        'ACCOUNT',
        'OTA',
      ],
      {
        message: 'Please select a payment method',
      },
    ),
    payment_channel_code: z.string().optional(),
    terms_accepted: z
      .boolean({
        required_error: 'You must accept the terms and conditions',
      })
      .refine((val) => val === true, {
        message: 'You must accept the terms and conditions',
      }),
  })
  .superRefine((data, ctx) => {
    if (data.payment_method_code === 'SECURE_PAYMENT') {
      if (!data.payment_channel_code) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: 'Please select payment channel',
          path: ['payment_channel_code'],
        })
      }
    }
  })

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

const BillingDetail: React.FC<BillingDetailProps> = ({ order, setOrder }) => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const merchant = useAppSelector((state) => state.merchant)
  const [termModalOpen, setTermModalOpen] = useState(false)
  const [hasReadTerms, setHasReadTerms] = useState(false)
  const [hasScrolledToBottom, setHasScrolledToBottom] = useState(false)
  const [processing, setProcessing] = useState(false)
  const { open, alertOptions, showErrorAlert, setOpen } = useModalAlert()
  const termsContentRef = React.useRef<HTMLDivElement>(null)
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      payment_method_code: order?.payment_method_code,
    },
  })

  // Reset scroll state when modal opens/closes
  useEffect(() => {
    if (termModalOpen) {
      // Reset scroll position when modal is opened
      if (termsContentRef.current) {
        termsContentRef.current.scrollTop = 0
      }
      setHasScrolledToBottom(false)
    }
  }, [termModalOpen])

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      setProcessing(true)

      const res = await axios.put(
        `${process.env.NEXT_PUBLIC_API_URL}/bookings`,
        {
          invoice_number: order?.invoice_number,
          billing_name: values.billing_name,
          billing_email: values.billing_email,
          billing_phone: values.billing_phone,
          payment_channel_code:
            values.payment_channel_code as PaymentChannelCode,
        },
      )

      if (res.status === 200) {
        dispatch(clearCart({ merchantID: merchant.id }))

        const { data }: { data: Order } = res.data

        router.push(`/${merchant?.username}/payments/${data.invoice_number}`)
      }
    } catch (error: any) {
      showErrorAlert(
        "Oops! Your order can't be processed",
        `But dont worry, you could request change for the payment method to Pay On Arrival by contacting us on ${merchant?.business_profile?.phone_number}.`,
      )
      console.error(error.message)
    } finally {
      setProcessing(false)
    }
  }

  const openTermsModal = (isChecked: boolean) => {
    setTermModalOpen(true)
    setHasReadTerms(isChecked)
    // Reset scroll state whenever modal opens
    setHasScrolledToBottom(false)
  }

  const handleTermsScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const { currentTarget } = event
    // Check if user has scrolled to the bottom (with a small threshold)
    const isAtBottom =
      currentTarget.scrollHeight - currentTarget.scrollTop <=
      currentTarget.clientHeight + 20 // 20px threshold
    if (isAtBottom) {
      setHasScrolledToBottom(true)
    }
  }

  return (
    <React.Fragment>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          {/* Billing Form */}
          <BillingForm />

          {/* Payment Method Form */}
          <PaymentMethodForm order={order} setOrder={setOrder} />

          <FormField
            control={form.control}
            name="terms_accepted"
            render={({ field }) => (
              <FormItem className="space-y-1 mt-4">
                <div className="flex items-center gap-2">
                  <FormControl>
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={(checked) => {
                        if (checked) {
                          openTermsModal(true)
                        } else {
                          field.onChange(false)
                        }
                      }}
                    />
                  </FormControl>
                  <FormLabel>
                    I have agree to the{' '}
                    <Dialog
                      open={termModalOpen}
                      onOpenChange={(open) => {
                        if (!open) {
                          setTermModalOpen(false)
                        }
                      }}
                    >
                      <DialogTrigger asChild>
                        <button
                          type="button"
                          className="text-sm font-medium underline text-blue-500 hover:text-blue-400"
                          onClick={() => {
                            openTermsModal(field.value)
                          }}
                        >
                          terms & conditions
                        </button>
                      </DialogTrigger>

                      <DialogContent
                        hideCloseButton
                        className="!w-[90%] !max-w-2xl max-h-[90vh] overflow-y-auto"
                      >
                        <DialogHeader>
                          <DialogTitle className="font-semibold text-2xl">
                            Terms & Conditions
                          </DialogTitle>
                        </DialogHeader>
                        <div
                          ref={termsContentRef}
                          className="max-h-[65vh] overflow-auto rounded-md mb-4 border border-gray-100 p-4"
                          onScroll={handleTermsScroll}
                        >
                          <div
                            className="rich-text"
                            dangerouslySetInnerHTML={{
                              __html: merchant?.term_and_condition?.terms,
                            }}
                          />
                        </div>
                        <div className="flex justify-end items-center gap-4">
                          {!hasScrolledToBottom && (
                            <p className="text-sm text-gray-500">
                              Please read all terms before continuing
                            </p>
                          )}
                          {hasReadTerms ? (
                            <Button
                              type="button"
                              onClick={() => {
                                setTermModalOpen(false)
                                field.onChange(true)
                              }}
                              className="bg-blue-800 hover:bg-blue-700"
                              disabled={!hasScrolledToBottom}
                            >
                              I UNDERSTAND
                            </Button>
                          ) : (
                            <Button
                              type="button"
                              onClick={() => {
                                setTermModalOpen(false)
                                field.onChange(true)
                              }}
                              className="bg-blue-800 hover:bg-blue-700"
                              disabled={!hasScrolledToBottom}
                            >
                              I AGREE
                            </Button>
                          )}
                        </div>
                      </DialogContent>
                    </Dialog>
                  </FormLabel>
                </div>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button
            type="submit"
            disabled={processing}
            className="w-full mt-8 py-6 bg-blue-800 hover:bg-blue-700 text-white font-medium rounded transition-all"
          >
            {processing ? (
              <>
                <Spinner color="white" size="sm" />
                <span className="ml-2">PROCESSING...</span>
              </>
            ) : (
              <>
                <span>PROCEED TO PAYMENT</span>
              </>
            )}
          </Button>
        </form>
      </Form>

      <ModalAlert
        open={open}
        onOpenChange={(open) => {
          setOpen(open)
        }}
        {...alertOptions}
      />
    </React.Fragment>
  )
}

export default BillingDetail
