﻿/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
/* eslint-disable @typescript-eslint/no-misused-promises */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import React, { useEffect, useState } from 'react'
import { actions } from 'astro:actions'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm, useWatch } from 'react-hook-form'
import { es } from 'date-fns/locale'

import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'

import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select'

import { Calendar } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { cn } from '@/lib/utils'
import { format } from 'date-fns'
import { ArrowLeft, CalendarIcon } from 'lucide-react'
import { Checkbox } from '../ui/checkbox'
import { schedulingSchema } from '@/validations/schedulingScheme'
import type { z } from 'zod'
import { toast } from 'sonner'
import { Toaster } from '../ui/sonner'
import TableScheduling from '../Table'
import SchedulingPricingCard from './SchedulingPricingCard'
import { formatCOP } from '@/lib/FormaterCOP'
import { getVehicleCategory, serviceTypes } from '@/lib/schedulingPricing'

const today = new Date()
const PENDING_VOUCHER_KEY = 'previcar_pending_wompi_voucher'
const SENT_VOUCHER_PREFIX = 'previcar_sent_wompi_voucher_'
const SUCCESSFUL_SCHEDULING_PREFIX = 'previcar_successful_scheduling_'
const WOMPI_APPROVAL_POLL_ATTEMPTS = 12
const WOMPI_APPROVAL_POLL_DELAY_MS = 1000

interface PendingVoucherPayload {
  nombre: string
  placa: string
  identificacion: string
  telefono: string
  correo: string
  recipient_email: string
  ciudad: string
  sede: string
  sede_nombre?: string
  tipo_vehiculo: string
  servicio: string
  antiguedad: number | null
  fecha_agendamiento: string
  hora: string
  subtotal: number
  descuento: number
  total: number
  numero_baucher?: string
  pagador_nombre: string
  pagador_correo: string
  pagador_tipo_identificacion: string
  pagador_numero_identificacion: string
}

interface ConfirmedPaymentModalData {
  nombre: string
  placa: string
  correoVoucher: string
  total: number
  fechaAgendada: string
  horaAgendada: string
}

const sanitizeDigits = (value: string, maxLength: number) => value.replace(/\D/g, '').slice(0, maxLength)
const sanitizeName = (value: string) => value.replace(/[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ\s]/g, '').slice(0, 60)
const sanitizePlate = (value: string) => value.replace(/\s+/g, '').replace(/[^a-zA-Z0-9]/g, '').toUpperCase().slice(0, 6)
const isValidEmail = (value?: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value?.trim() ?? '')
const isTenDigitPhone = (value?: string) => /^\d{10}$/.test(value?.trim() ?? '')
const isValidOwnerId = (value?: string) => /^\d{6,10}$/.test(value?.trim() ?? '')
const toArray = (value: unknown) => Array.isArray(value) ? value : []
const wait = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds))
const normalizeText = (value?: string) => (value ?? '')
  .normalize('NFD')
  .replace(/[\u0300-\u036f]/g, '')
  .toUpperCase()
const isCaliNorteHeadquarters = (value?: string) => normalizeText(value).includes('CALI NORTE')

const getScheduleMinutes = (value: unknown) => {
  const time = String(value ?? '').match(/(\d{1,2}):(\d{2})(?::\d{2})?/)

  if (!time) return null

  const hours = Number(time[1])
  const minutes = Number(time[2])

  if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null

  return hours * 60 + minutes
}

const filterCaliNorteScheduleOptions = (options: unknown[]) => (
  options.filter((option) => {
    const minutes = getScheduleMinutes(option)
    return minutes == null || minutes <= 15 * 60
  })
)

const isSundayDate = (date?: Date) => date instanceof Date && date.getDay() === 0

const fetchLegacyDirectArray = async (url: string) => {
  const response = await fetch(url, {
    method: 'GET',
    redirect: 'follow'
  })

  if (!response.ok) {
    throw new Error(`Sistema de agendamiento respondio ${response.status}.`)
  }

  const responseText = await response.text()

  try {
    const parsed = JSON.parse(responseText) as unknown
    return toArray(parsed)
  } catch {
    return []
  }
}

const clearWompiReturnQueryParam = () => {
  const url = new URL(window.location.href)

  if (!url.searchParams.has('id')) return

  url.searchParams.delete('id')
  window.history.replaceState({}, '', url.toString())
}

const waitForApprovedWompiTransaction = async (transactionId: string) => {
  let lastTransactionData: {
    id: string
    status: string
    reference: string
    finalizedAt: string
    paymentMethodType: string
  } | null = null

  for (let attempt = 1; attempt <= WOMPI_APPROVAL_POLL_ATTEMPTS; attempt += 1) {
    const { data, error } = await actions.verifyWompiTransaction({ transactionId })

    if (error || !data) {
      throw new Error(error?.message ?? 'No fue posible verificar el pago en Wompi.')
    }

    lastTransactionData = data

    console.log('[Wompi Return] Verificacion de estado de pago desde formulario', {
      transactionId,
      attempt,
      maxAttempts: WOMPI_APPROVAL_POLL_ATTEMPTS,
      status: data.status
    })

    if (data.status === 'APPROVED') return data

    if (data.status === 'DECLINED' || data.status === 'ERROR' || data.status === 'VOIDED') {
      return data
    }

    if (attempt < WOMPI_APPROVAL_POLL_ATTEMPTS) {
      await wait(WOMPI_APPROVAL_POLL_DELAY_MS)
    }
  }

  return lastTransactionData
}

const getPlateValidationMessage = (plateValue: string, vehicleLabel: string) => {
  const plate = sanitizePlate(plateValue)
  const category = getVehicleCategory(vehicleLabel)

  if (!plate) return null
  if (!category) return null

  if (category === 'MOTOS') {
    if (plate.length < 5) return 'Para moto, la placa debe tener minimo 5 caracteres. Ejemplo: AAA44.'
    if (plate.length > 6) return 'La placa no puede superar los 6 caracteres, sin espacios.'
    if (!/^[A-Z]{3}\d{2}[A-Z]?$/.test(plate)) {
      return 'Para moto, la placa debe tener 3 letras y 2 numeros, o 3 letras, 2 numeros y 1 letra. Ejemplos: AAA44 o AAA44A.'
    }

    return null
  }

  if (plate.length !== 6) {
    return 'La placa debe tener exactamente 6 caracteres, sin espacios.'
  }
  
  if ((category === 'LIVIANOS' || category === 'PESADOS') && !/^[A-Z]{3}\d{3}$/.test(plate)) {
    return 'Para livianos y pesados, la placa debe tener 3 letras y 3 numeros. Ejemplo: AAA111.'
  }

  return null
}

const holidays = [
  new Date("2025-01-06"), // Día de los Reyes Magos
  new Date("2025-03-24"), // Día de San José
  new Date("2025-04-17"), // Jueves Santo
  new Date("2025-04-18"), // Viernes Santo
  new Date("2025-05-01"), // Día del Trabajo
  new Date("2025-06-02"), // Corpus Christi
  new Date("2025-06-23"), // Sagrado Corazón de Jesús
  new Date("2025-06-30"), // San Pedro y San Pablo
  new Date("2025-08-07"), // Batalla de Boyacá
  new Date("2025-08-18"), // Asunción de la Virgen
  new Date("2025-10-13"), // Día de la Raza
  new Date("2025-11-03"), // Día de Todos los Santos
  new Date("2025-11-17"), // Independencia de Cartagena
  new Date("2025-12-08"), // Inmaculada Concepción
  new Date("2025-12-25"), // Navidad
  new Date("2026-01-12"), // Día de los Reyes Magos
  new Date("2026-03-23"), // Día de San José
  new Date("2026-04-02"), // Jueves Santo
  new Date("2026-04-03"), // Viernes Santo
  new Date("2026-05-01"), // Día del Trabajo
  new Date("2026-05-18"), // Ascensión del Señor
  new Date("2026-06-08"), // Corpus Christi
  new Date("2026-06-15"), // Sagrado Corazón de Jesús
  new Date("2026-06-29"), // San Pedro y San Pablo
  new Date("2026-07-20"), // Día de la Independencia
  new Date("2026-08-07"), // Batalla de Boyacá
  new Date("2026-08-17"), // Asunción de la Virgen
  new Date("2026-10-12"), // Día de la Raza
  new Date("2026-11-02"), // Día de Todos los Santos
  new Date("2026-11-16"), // Independencia de Cartagena
  new Date("2026-12-08"), // Inmaculada Concepción
  new Date("2026-12-25")  // Navidad
]

const holidaysCali = [
  new Date("2025-01-06"), // Día de los Reyes Magos
  new Date("2025-03-24"), // Día de San José
  new Date("2025-04-17"), // Jueves Santo
  new Date("2025-04-18"), // Viernes Santo
  new Date("2025-05-01"), // Día del Trabajo
  new Date("2025-05-04"), // fecha especial
  new Date("2025-06-02"), // Corpus Christi
  new Date("2025-06-23"), // Sagrado Corazón de Jesús
  new Date("2025-06-30"), // San Pedro y San Pablo
  new Date("2025-07-20"), // Día de la Independencia
  new Date("2025-08-07"), // Batalla de Boyacá
  new Date("2025-08-18"), // Asunción de la Virgen
  new Date("2025-10-13"), // Día de la Raza
  new Date("2025-11-03"), // Día de Todos los Santos
  new Date("2025-11-17"), // Independencia de Cartagena
  new Date("2025-12-08"), // Inmaculada Concepción
  new Date("2025-12-25"), // Navidad
  new Date("2026-01-12"), // Día de los Reyes Magos
  new Date("2026-03-23"), // Día de San José
  new Date("2026-04-02"), // Jueves Santo
  new Date("2026-04-03"), // Viernes Santo
  new Date("2026-05-01"), // Día del Trabajo
  new Date("2026-05-03"), // fecha especial
  new Date("2026-05-18"), // Ascensión del Señor
  new Date("2026-06-08"), // Corpus Christi
  new Date("2026-06-15"), // Sagrado Corazón de Jesús
  new Date("2026-06-29"), // San Pedro y San Pablo
  new Date("2026-07-20"), // Día de la Independencia
  new Date("2026-08-07"), // Batalla de Boyacá
  new Date("2026-08-17"), // Asunción de la Virgen
  new Date("2026-10-12"), // Día de la Raza
  new Date("2026-11-02"), // Día de Todos los Santos
  new Date("2026-11-16"), // Independencia de Cartagena
  new Date("2026-12-08"), // Inmaculada Concepción
  new Date("2026-12-25")  // Navidad
]

function SchedulingForm () {
  const clearWompiPendingState = () => {
    if (typeof window === 'undefined') return

    window.localStorage.removeItem(PENDING_VOUCHER_KEY)

    const url = new URL(window.location.href)
    if (!url.searchParams.has('id')) return

    url.searchParams.delete('id')
    window.history.replaceState({}, '', url.toString())
  }

  const vehicleAgeOptions = [
    { label: '0 A 2', value: 0 },
    { label: '3 A 7', value: 3 },
    { label: '8 A 16', value: 8 },
    { label: '17 A MÁS', value: 17 }
  ]

  const form = useForm<z.infer<typeof schedulingSchema>>({
    resolver: zodResolver(schedulingSchema),
    mode: 'onBlur',
    reValidateMode: 'onChange',
    defaultValues: {
      name: '',
      vehicleRegistrationNumber: '',
      ownerID: '',
      email: '',
      cellPhoneNumber: '',
      vehicleAge: undefined,
      serviceType: '',
      hour: '',
      headquarters: '',
      typeOfVehicle: '',
      city: '',
      terms: false
    }
  })

  const [isSuccessfulScheduling, setIsSuccessfulScheduling] = useState(false)
  const [dataScheduling, setDataScheduling] = useState<any>({})
  const [cityOptions, setCityOptions] = useState<any>([])
  const [headquartersOptions, setHeadquartersOptions] = useState<any>([])
  const [scheduleOptions, setScheduleOptions] = useState<any>([])
  const [typeOfVehicleOptions, setTypeOfVehicleOptions] = useState<any>([])
  const [selectedDate, setSelectedDate] = useState('')
  const [selectedTypeOfVehicle, setSelectedTypeOfVehicle] = useState('')
  const [colombianHolidays, setColombianHolidays] = useState(holidays)
  const [isPaymentButtonEnabled, setIsPaymentButtonEnabled] = useState(false)
  const [showPaymentConfirmedModal, setShowPaymentConfirmedModal] = useState(false)
  const [confirmedPaymentModalData, setConfirmedPaymentModalData] = useState<ConfirmedPaymentModalData | null>(null)

  const city = useWatch({ name: 'city', control: form.control })
  const scheduleDate = useWatch({ name: 'schedulingDate', control: form.control })
  const headquartersValue = useWatch({ name: 'headquarters', control: form.control })
  const typeOfVehicleValue = useWatch({ name: 'typeOfVehicle', control: form.control })
  const formValues = useWatch({ control: form.control })

  const selectedHeadquarters = headquartersOptions.find((option: any) => option.value === headquartersValue)
  const selectedVehicleOption = typeOfVehicleOptions.find((option: any) => option.id?.toString() === typeOfVehicleValue?.toString())
  const selectedVehicleLabel = selectedVehicleOption?.type || selectedTypeOfVehicle || 'Pendiente por seleccionar'
  const selectedDateLabel = formValues?.schedulingDate ? format(formValues.schedulingDate, "d 'de' MMMM yyyy", { locale: es }) : 'Pendiente por seleccionar'
  const selectedHourLabel = formValues?.hour || 'Pendiente por seleccionar'
  const ownerNameLabel = formValues?.name?.trim() || 'Nombre del propietario'
  const ownerIdLabel = formValues?.ownerID?.trim() || 'Pendiente por seleccionar'
  const plateLabel = formValues?.vehicleRegistrationNumber?.trim()?.toUpperCase() || 'ABC123'
  const cityLabel = formValues?.city || 'Pendiente por seleccionar'
  const headquartersLabel = selectedHeadquarters?.name || 'Pendiente por seleccionar'
  const shouldLimitCaliNorteSchedule = isCaliNorteHeadquarters(selectedHeadquarters?.name)
  const emailLabel = formValues?.email?.trim() || 'correo@ejemplo.com'
  const phoneLabel = formValues?.cellPhoneNumber?.trim() || '3001234567'
  const selectedVehicleAgeOption = vehicleAgeOptions.find(option => option.value === formValues?.vehicleAge)
  const vehicleAge = typeof formValues?.vehicleAge === 'number' ? formValues.vehicleAge : null
  const vehicleAgeLabel = selectedVehicleAgeOption
    ? selectedVehicleAgeOption.label
    : 'Pendiente por seleccionar'
  const vehicleCategory = getVehicleCategory(selectedTypeOfVehicle)
  const shouldShowServiceType = vehicleCategory !== 'MOTOS'
  const selectedServiceType = formValues?.serviceType ?? ''
  const shouldShowPaymentCard = vehicleCategory === 'MOTOS' || (selectedServiceType === 'PARTICULAR' && vehicleCategory === 'LIVIANOS')
  const plateValidationMessage = getPlateValidationMessage(formValues?.vehicleRegistrationNumber ?? '', selectedVehicleLabel)
  const isSchedulingFormComplete = Boolean(
    formValues?.name?.trim() &&
    formValues?.vehicleRegistrationNumber?.trim() &&
    isValidOwnerId(formValues?.ownerID) &&
    isValidEmail(formValues?.email) &&
    isTenDigitPhone(formValues?.cellPhoneNumber) &&
    formValues?.city &&
    formValues?.headquarters &&
    formValues?.typeOfVehicle &&
    formValues?.schedulingDate &&
    formValues?.hour &&
    formValues?.terms &&
    typeof formValues?.vehicleAge === 'number' &&
    !Number.isNaN(formValues.vehicleAge) &&
    formValues.vehicleAge >= 0 &&
    (!shouldShowServiceType || formValues?.serviceType) &&
    !plateValidationMessage
  )

  useEffect(() => {
    const syncApprovedPayment = async () => {
      const transactionId = new URL(window.location.href).searchParams.get('id')

      if (!transactionId) return

      const successfulScheduling = window.sessionStorage.getItem(`${SUCCESSFUL_SCHEDULING_PREFIX}${transactionId}`)
      if (successfulScheduling) {
        try {
          const parsedScheduling = JSON.parse(successfulScheduling)
          setDataScheduling(parsedScheduling)
          if (parsedScheduling?.transaccion_id) {
            setConfirmedPaymentModalData({
              nombre: parsedScheduling.pagador_nombre || parsedScheduling.nombre,
              placa: parsedScheduling.placa,
              correoVoucher: parsedScheduling.recipient_email || parsedScheduling.pagador_correo || parsedScheduling.correo,
              total: parsedScheduling.total,
              fechaAgendada: parsedScheduling.fecha_agendamiento,
              horaAgendada: parsedScheduling.hora
            })
            setShowPaymentConfirmedModal(true)
          }
          setIsSuccessfulScheduling(true)
          clearWompiReturnQueryParam()
          return
        } catch {
          window.sessionStorage.removeItem(`${SUCCESSFUL_SCHEDULING_PREFIX}${transactionId}`)
        }
      }

      if (window.sessionStorage.getItem(`${SENT_VOUCHER_PREFIX}${transactionId}`) === 'true') {
        clearWompiReturnQueryParam()
        return
      }

      const storedPayload = window.localStorage.getItem(PENDING_VOUCHER_KEY)
      if (!storedPayload) {
        clearWompiReturnQueryParam()
        return
      }

      let pendingVoucher: PendingVoucherPayload
      try {
        pendingVoucher = JSON.parse(storedPayload) as PendingVoucherPayload
      } catch {
        window.localStorage.removeItem(PENDING_VOUCHER_KEY)
        clearWompiReturnQueryParam()
        return
      }

      try {
        toast.loading('Confirmando el pago con Wompi...', {
          id: `wompi-confirmation-${transactionId}`
        })

        const data = await waitForApprovedWompiTransaction(transactionId)

        if (!data || data.status !== 'APPROVED') {
          toast.dismiss(`wompi-confirmation-${transactionId}`)

          if (data?.status === 'DECLINED' || data?.status === 'ERROR' || data?.status === 'VOIDED') {
            window.localStorage.removeItem(PENDING_VOUCHER_KEY)
            toast.error('Wompi reporto que el pago no fue aprobado.')
            clearWompiReturnQueryParam()
            return
          }

          toast.error('El pago aun esta en confirmacion. Vuelve a esta pagina en unos segundos para validar el estado.')
          clearWompiReturnQueryParam()
          return
        }

        const finalizedPayload = {
          ...pendingVoucher,
          referencia_pago: data.reference || `WOMPI-${transactionId}`,
          metodo_pago: data.paymentMethodType,
          transaccion_id: data.id,
          fecha_pago: data.finalizedAt || new Date().toLocaleString('es-CO')
        }

        console.log('[Wompi Return] Pago aprobado detectado desde formulario', {
          transactionId,
          wompiData: data,
          finalizedPayload
        })

        const { data: schedulingData, error: schedulingError } = await actions.finalizePaidScheduling(finalizedPayload)

        if (schedulingError) {
          throw new Error(schedulingError.message ?? 'No fue posible registrar el agendamiento confirmado.')
        }

        finalizedPayload.numero_baucher = schedulingData?.baucherNumber || undefined

        setDataScheduling(finalizedPayload)
        setIsSuccessfulScheduling(true)
        toast.dismiss(`wompi-confirmation-${transactionId}`)
        toast.loading('Enviando voucher al correo del cliente...', {
          id: `voucher-email-${transactionId}`
        })

        const { error: voucherError } = await actions.sendPaymentVoucher(finalizedPayload)

        if (voucherError) {
          throw new Error(`VOUCHER_EMAIL_ERROR: ${voucherError.message ?? 'No fue posible enviar el voucher.'}`)
        }

        window.sessionStorage.setItem(`${SENT_VOUCHER_PREFIX}${transactionId}`, 'true')
        window.sessionStorage.setItem(`${SUCCESSFUL_SCHEDULING_PREFIX}${transactionId}`, JSON.stringify(finalizedPayload))
        window.localStorage.removeItem(PENDING_VOUCHER_KEY)
        toast.dismiss(`voucher-email-${transactionId}`)
        clearWompiReturnQueryParam()
        setConfirmedPaymentModalData({
          nombre: finalizedPayload.pagador_nombre || finalizedPayload.nombre,
          placa: finalizedPayload.placa,
          correoVoucher: finalizedPayload.correo,
          total: finalizedPayload.total,
          fechaAgendada: finalizedPayload.fecha_agendamiento,
          horaAgendada: finalizedPayload.hora
        })
        setShowPaymentConfirmedModal(true)
        toast.success('Pago confirmado y voucher enviado correctamente.')
      } catch (error) {
        console.error(error)
        toast.dismiss(`wompi-confirmation-${transactionId}`)
        toast.dismiss(`voucher-email-${transactionId}`)

        const message = error instanceof Error ? error.message : 'No fue posible confirmar el pago automaticamente.'

        if (message.includes('VOUCHER_EMAIL_ERROR')) {
          toast.error('El pago fue aprobado, pero no fue posible enviar el voucher por correo. Revisa la configuracion SMTP y recarga esta pagina para reintentar.')
          return
        }

        clearWompiReturnQueryParam()
        toast.error(message)
      }
    }

    void syncApprovedPayment()
  }, [])

  const getFirstMissingSchedulingField = () => {
    if (!formValues?.name?.trim()) return { name: 'name' as const, label: 'Nombre Propietario' }
    if (!formValues?.vehicleRegistrationNumber?.trim()) return { name: 'vehicleRegistrationNumber' as const, label: 'Placa del vehículo' }
    if (!formValues?.ownerID?.trim()) return { name: 'ownerID' as const, label: 'Identificación del propietario' }
    if (!formValues?.cellPhoneNumber?.trim()) return { name: 'cellPhoneNumber' as const, label: 'Número de Celular' }
    if (typeof formValues?.vehicleAge !== 'number' || Number.isNaN(formValues.vehicleAge) || formValues.vehicleAge < 0) {
      return { name: 'vehicleAge' as const, label: 'Años de antigüedad' }
    }
    if (shouldShowServiceType && !formValues?.serviceType) return { name: 'serviceType' as const, label: 'Tipo de servicio' }
    if (!formValues?.email?.trim()) return { name: 'email' as const, label: 'Correo electrónico' }
    if (!formValues?.city) return { name: 'city' as const, label: 'Ciudad de agendamiento' }
    if (!formValues?.headquarters) return { name: 'headquarters' as const, label: 'Sede' }
    if (!formValues?.typeOfVehicle) return { name: 'typeOfVehicle' as const, label: 'Tipo de Vehículo' }
    if (!formValues?.schedulingDate) return { name: 'schedulingDate' as const, label: 'Fecha de agendamiento' }
    if (!formValues?.hour) return { name: 'hour' as const, label: 'Hora de agendamiento' }
    if (!formValues?.terms) return { name: 'terms' as const, label: 'Términos y condiciones' }
    return null
  }

  const handleIncompleteSchedulingForm = async () => {
    const missingField = getFirstMissingSchedulingField()
    await form.trigger(undefined, { shouldFocus: true })

    if (missingField) {
      form.setFocus(missingField.name)
      toast.error(`Te falta llenar el campo: ${missingField.label}.`)
      return
    }

    toast.error('Completa los campos obligatorios del formulario para continuar.')
  }

  async function sendRequest (data: any) {
    const { error, data: schedulingData } = await actions.createLegacyScheduling(data)

    if (error) {
      throw new Error(error.message ?? 'No fue posible registrar el agendamiento.')
    }

    return schedulingData
  }

  const onSubmit = () => {
    const { name, vehicleRegistrationNumber, ownerID, email, cellPhoneNumber, hour, city, headquarters, typeOfVehicle, terms } = form.getValues()

    if (!terms) return

    if (plateValidationMessage) {
      form.setError('vehicleRegistrationNumber', { type: 'manual', message: plateValidationMessage })
      form.setFocus('vehicleRegistrationNumber')
      toast.error(plateValidationMessage)
      return
    }

    clearWompiPendingState()

    const raw = {
      nombre: name,
      placa: sanitizePlate(vehicleRegistrationNumber),
      identificacion: ownerID,
      telefono: cellPhoneNumber,
      correo: email,
      ciudad: city,
      sede: headquarters,
      tipo_vehiculo: typeOfVehicle,
      fecha_agendamiento: selectedDate,
      hora: hour
    }

    toast.promise(sendRequest(raw), {
      duration: 10000,
      closeButton: true,
      loading: 'Agendando...',
      success: () => {
        clearWompiPendingState()
        setIsSuccessfulScheduling(true)
        setDataScheduling(raw)
        return '¡El agendamiento de la renovación de tu revisión tecnomecánica ha sido realizado exitosamente!'
      },
      error: () => 'Lo sentimos, hubo un error al enviar el formulario.'
    })
  }

  useEffect(() => {
    let isCancelled = false

    const loadCities = async () => {
      const { data, error } = await actions.getLegacyCities()

      if (isCancelled) return

      if (!error && toArray(data).length > 0) {
        console.log('[Scheduling Form] Ciudades recibidas', data)
        setCityOptions(toArray(data))
        
        // Auto-seleccionar ciudad si viene en la URL
        const urlParams = new URLSearchParams(window.location.search)
        let cityFromUrl = urlParams.get('city')
        
        if (cityFromUrl) {
          // Convertir a mayúscula para búsqueda case-insensitive
          cityFromUrl = cityFromUrl.toUpperCase().trim()
          
          // Buscar la ciudad en las opciones (case-insensitive)
          const cityExists = toArray(data).some(
            (option: string) => option.toUpperCase() === cityFromUrl
          )
          
          if (cityExists) {
            console.log('[Scheduling Form] Seleccionando ciudad desde URL:', cityFromUrl)
            form.setValue('city', cityFromUrl)
          } else {
            console.warn('[Scheduling Form] Ciudad desde URL no encontrada en opciones:', cityFromUrl)
          }
        }
        return
      }

      try {
        console.warn('[Scheduling Form] Reintentando ciudades con fetch directo', error)
        const directCities = await fetchLegacyDirectArray(`${import.meta.env.PUBLIC_BASE_URL_VML}?getCities`)

        if (isCancelled) return

        if (directCities.length > 0) {
          setCityOptions(directCities)
          
          // Auto-seleccionar ciudad si viene en la URL
          const urlParams = new URLSearchParams(window.location.search)
          let cityFromUrl = urlParams.get('city')
          
          if (cityFromUrl) {
            // Convertir a mayúscula para búsqueda case-insensitive
            cityFromUrl = cityFromUrl.toUpperCase().trim()
            
            // Buscar la ciudad en las opciones (case-insensitive)
            const cityExists = directCities.some(
              (option: string) => option.toUpperCase() === cityFromUrl
            )
            
            if (cityExists) {
              console.log('[Scheduling Form] Seleccionando ciudad desde URL (reintento):', cityFromUrl)
              form.setValue('city', cityFromUrl)
            } else {
              console.warn('[Scheduling Form] Ciudad desde URL no encontrada en opciones (reintento):', cityFromUrl)
            }
          }
          return
        }
      } catch (directError) {
        console.error(directError)
      }

      toast.error('No fue posible cargar las ciudades. Intenta recargar la pagina.')
    }

    void loadCities()

    return () => {
      isCancelled = true
    }
  }, [form])

  useEffect(() => {
    if (!city) {
      setHeadquartersOptions([])
      return
    }

    let isCancelled = false

    const loadHeadquarters = async () => {
      const { data, error } = await actions.getLegacyHeadquarters({ city })

      if (isCancelled) return

      if (!error && toArray(data).length > 0) {
        console.log('[Scheduling Form] Sedes recibidas', data)
        const headquartersData = toArray(data)
        setHeadquartersOptions(headquartersData)
        
        // Auto-seleccionar sede si hay solo una disponible
        if (headquartersData.length === 1) {
          const singleHeadquarters = headquartersData[0]
          console.log('[Scheduling Form] Auto-seleccionando sede única:', singleHeadquarters.name)
          form.setValue('headquarters', singleHeadquarters.value)
        }
        return
      }

      try {
        console.warn('[Scheduling Form] Reintentando sedes con fetch directo', error)
        const directHeadquarters = await fetchLegacyDirectArray(`${import.meta.env.PUBLIC_BASE_URL_VML}?ciudad=${city}`)

        if (isCancelled) return

        if (directHeadquarters.length > 0) {
          setHeadquartersOptions(directHeadquarters)
          
          // Auto-seleccionar sede si hay solo una disponible
          if (directHeadquarters.length === 1) {
            const singleHeadquarters = directHeadquarters[0]
            console.log('[Scheduling Form] Auto-seleccionando sede única (reintento):', singleHeadquarters.name)
            form.setValue('headquarters', singleHeadquarters.value)
          }
          return
        }
      } catch (directError) {
        console.error(directError)
      }

      toast.error('No fue posible cargar las sedes. Intenta seleccionar la ciudad nuevamente.')
      setHeadquartersOptions([])
    }

    void loadHeadquarters()

    return () => {
      isCancelled = true
    }
  }, [city])

  useEffect(() => {
    form.setValue('headquarters', '')
    form.setValue('typeOfVehicle', '')
    form.setValue('serviceType', '')
    form.setValue('hour', '')
    setSelectedTypeOfVehicle('')
    setTypeOfVehicleOptions([])
    setScheduleOptions([])
  }, [city, form])

  useEffect(() => {
    const headquartersSelected: any = headquartersOptions.find((option: any) => option.value === headquartersValue)

    if (!headquartersSelected) {
      setTypeOfVehicleOptions([])
      return
    }

    const availableVehicles = Object.keys(headquartersSelected)
      .filter(key => headquartersSelected[key]?.available === 'TRUE')
      .map(key => ({
        type: headquartersSelected[key].name ?? key,
        id: headquartersSelected[key].id.toString()
      }))

    setTypeOfVehicleOptions(availableVehicles)
  }, [headquartersOptions, headquartersValue])

  useEffect(() => {
    if (!typeOfVehicleValue) {
      setSelectedTypeOfVehicle('')
      return
    }

    const selectedVehicle = typeOfVehicleOptions.find((option: any) => option.id.toString() === typeOfVehicleValue.toString())
    setSelectedTypeOfVehicle(selectedVehicle?.type ?? '')
  }, [typeOfVehicleOptions, typeOfVehicleValue])

  useEffect(() => {
    if (!formValues?.vehicleRegistrationNumber) {
      form.clearErrors('vehicleRegistrationNumber')
      return
    }

    const message = getPlateValidationMessage(formValues.vehicleRegistrationNumber, selectedVehicleLabel)

    if (message) {
      form.setError('vehicleRegistrationNumber', { type: 'manual', message })
      return
    }

    form.clearErrors('vehicleRegistrationNumber')
  }, [form, formValues?.vehicleRegistrationNumber, selectedVehicleLabel])

  useEffect(() => {
    if (!headquartersValue || !selectedDate) {
      setScheduleOptions([])
      return
    }

    let isCancelled = false

    const loadSchedule = async () => {
      setScheduleOptions([])
      form.setValue('hour', '')

      const { data, error } = await actions.getLegacySchedule({
        headquarters: headquartersValue,
        schedulingDate: selectedDate
      })

      if (isCancelled) return

      if (!error && toArray(data).length > 0) {
        const scheduleData = toArray(data)
        const filteredScheduleData = shouldLimitCaliNorteSchedule
          ? filterCaliNorteScheduleOptions(scheduleData)
          : scheduleData

        console.log('[Scheduling Form] Horarios recibidos', {
          headquarters: headquartersValue,
          headquartersLabel,
          original: scheduleData,
          filtered: filteredScheduleData
        })
        setScheduleOptions(filteredScheduleData)
        return
      }

      console.warn('[Scheduling Form] No fue posible cargar horarios desde el backend', error)
      toast.error('No fue posible cargar los horarios. Intenta seleccionar la fecha nuevamente.')
      setScheduleOptions([])
    }

    void loadSchedule()

    return () => {
      isCancelled = true
    }
  }, [headquartersValue, selectedDate])

  useEffect(() => {
    if (headquartersValue && scheduleDate) {
      const formatDate = (date: Date) => {
        const options: Intl.DateTimeFormatOptions = {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }
        const formattedDate = date.toLocaleDateString('es-ES', options)
        const [day, month, year] = formattedDate.split('/')
        return `${year}-${month}-${day}`
      }
      setSelectedDate(formatDate(scheduleDate))
      return
    }

    setSelectedDate('')
  }, [scheduleDate, headquartersValue])

  useEffect(() => {
    form.setValue('typeOfVehicle', '')
    form.setValue('serviceType', '')
    form.setValue('hour', '')
    setSelectedTypeOfVehicle('')
    setScheduleOptions([])
  }, [form, headquartersValue])

  useEffect(() => {
    form.setValue('hour', '')
  }, [form, selectedDate])

  useEffect(() => {
    if (!shouldLimitCaliNorteSchedule || !isSundayDate(scheduleDate)) return

    form.resetField('schedulingDate')
    form.setValue('hour', '')
    setSelectedDate('')
    setScheduleOptions([])
  }, [form, scheduleDate, shouldLimitCaliNorteSchedule])

  useEffect(() => {
    if (city === 'CALI') {
      setColombianHolidays(holidaysCali)
      return
    }

    setColombianHolidays(holidays)
  }, [city])

  useEffect(() => {
    if (!shouldShowPaymentCard) {
      setIsPaymentButtonEnabled(false)
    }
  }, [shouldShowPaymentCard])

  const handleReturnToForm = () => {
    setIsSuccessfulScheduling(false)
    setDataScheduling({})
    setShowPaymentConfirmedModal(false)
    setConfirmedPaymentModalData(null)
    form.reset()
    clearWompiPendingState()
  }

  return (
    <div>
      <Dialog open={showPaymentConfirmedModal} onOpenChange={setShowPaymentConfirmedModal}>
        <DialogContent className="max-w-md border-[#E8D9CF] bg-[#FFF8F2]">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold text-[#7A160F]">Pago confirmado</DialogTitle>
            <DialogDescription className="text-sm leading-6 text-[#5B4336]">
              Tu pago fue aprobado correctamente y el voucher ya fue enviado al correo registrado del pagador.
            </DialogDescription>
          </DialogHeader>

          <div className="rounded-2xl border border-[#F0D4C6] bg-white p-4">
            <p className="text-sm font-semibold text-[#3D2418]">{confirmedPaymentModalData?.nombre ?? 'Cliente Previcar'}</p>
            <div className="mt-3 space-y-2 text-sm text-[#5B4336]">
              <div className="flex items-center justify-between gap-3">
                <span>Placa</span>
                <span className="font-medium text-[#2F241D]">{confirmedPaymentModalData?.placa ?? 'Pendiente'}</span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span>Correo del voucher</span>
                <span className="text-right font-medium text-[#2F241D]">{confirmedPaymentModalData?.correoVoucher ?? 'Pendiente'}</span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span>Total pagado</span>
                <span className="font-semibold text-[#7A160F]">
                  {confirmedPaymentModalData?.total ? formatCOP(confirmedPaymentModalData.total) : 'Pendiente'}
                </span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span>Fecha agendada</span>
                <span className="text-right font-medium text-[#2F241D]">{confirmedPaymentModalData?.fechaAgendada ?? 'Pendiente'}</span>
              </div>
              <div className="flex items-center justify-between gap-3">
                <span>Hora de agendamiento</span>
                <span className="font-medium text-[#2F241D]">{confirmedPaymentModalData?.horaAgendada ?? 'Pendiente'}</span>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {!isSuccessfulScheduling
        ? (
          <div className={cn(
            'grid gap-8 lg:items-start lg:[&>*]:self-start',
            shouldShowPaymentCard
              ? 'lg:grid-cols-[minmax(0,0.86fr)_minmax(290px,0.48fr)]'
              : 'lg:grid-cols-[minmax(0,1fr)]'
          )}>
            {shouldShowPaymentCard && (
              <div className="order-first lg:order-2">
                <SchedulingPricingCard
                  isVisible={shouldShowPaymentCard}
                  isSchedulingFormComplete={isSchedulingFormComplete}
                  onIncompleteSchedulingForm={() => { void handleIncompleteSchedulingForm() }}
                  onPaymentButtonEnabledChange={setIsPaymentButtonEnabled}
                  termsChecked={Boolean(formValues?.terms)}
                  onTermsCheckedChange={(checked) => form.setValue('terms', checked, {
                    shouldDirty: true,
                    shouldTouch: true,
                    shouldValidate: true
                  })}
                  termsErrorMessage={form.formState.errors.terms?.message}
                  ownerNameLabel={ownerNameLabel}
                  plateLabel={plateLabel}
                  ownerIdLabel={ownerIdLabel}
                  cityLabel={cityLabel}
                  headquartersLabel={headquartersLabel}
                  headquartersValue={formValues?.headquarters ?? ''}
                  selectedVehicleLabel={selectedVehicleLabel}
                  selectedVehicleValue={formValues?.typeOfVehicle ?? ''}
                  serviceTypeLabel={shouldShowServiceType ? formValues?.serviceType || 'Pendiente por seleccionar' : 'MOTOS'}
                  vehicleAge={vehicleAge}
                  vehicleAgeLabel={vehicleAgeLabel}
                  selectedDateLabel={selectedDateLabel}
                  selectedDateValue={selectedDate}
                  selectedHourLabel={selectedHourLabel}
                  emailLabel={emailLabel}
                  phoneLabel={phoneLabel}
                />
              </div>
            )}
            <div className="lg:order-1">
              <div className="flex flex-col gap-6 mb-6">
                <h1 className="text-[2rem] font-semibold">Agendamiento <span className="text-primary">en línea</span>.</h1>
                <p className="font-normal">Diligencia estos datos para solicitar el agendamiento de tu RTM.</p>
                <p className="font-normal text-black underline">Antes de proceder con el agendamiento, valide que su vehículo cumple con las tipologías incluidas dentro del alcance autorizado del CDA para la prestación del servicio.</p>
              </div>
              {cityOptions.length > 0
                ? (<Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 w-full">
                      <div className="flex flex-col lg:flex-row w-full gap-[27px]">
                        <FormField
                          control={form.control}
                          name="ownerID"
                          render={({ field }) => (
                            <FormItem className="w-full">
                              <FormLabel className="text-[#7C7C7C]">Identificación del propietario</FormLabel>
                              <FormControl>
                                <Input
                                  type="tel"
                                  inputMode="numeric"
                                  maxLength={10}
                                  title="Ingresa el numero de identificacion del propietario."
                                  className="px-4 py-3 border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none"
                                  placeholder="Ingresa la identificacion del propietario"
                                  {...field}
                                  onChange={(event) => field.onChange(sanitizeDigits(event.target.value, 10))}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name="name"
                          render={({ field }) => (
                            <FormItem className="w-full">
                              <FormLabel className="text-[#7C7C7C]">Nombre Propietario</FormLabel>
                              <FormControl>
                                <Input
                                  type="text"
                                  maxLength={60}
                                  title="Ingresa el nombre completo del propietario."
                                  className="px-4 py-3 border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none"
                                  placeholder="Ingresa el nombre del propietario"
                                  {...field}
                                  onChange={(event) => field.onChange(sanitizeName(event.target.value))}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <div className="flex flex-col lg:flex-row w-full gap-[27px]">
                        <FormField
                          control={form.control}
                          name="cellPhoneNumber"
                          render={({ field }) => (
                            <FormItem className="w-full">
                              <FormLabel className="text-[#7C7C7C]">Número de Celular</FormLabel>
                              <FormControl>
                                <Input
                                  type="tel"
                                  inputMode="numeric"
                                  maxLength={10}
                                  title="Ingresa el numero de celular del propietario."
                                  className="px-4 py-3 border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none"
                                  placeholder="Ingresa el numero de celular"
                                  {...field}
                                  onChange={(event) => field.onChange(sanitizeDigits(event.target.value, 10))}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name="email"
                          render={({ field }) => (
                            <FormItem className="w-full">
                              <FormLabel className="text-[#7C7C7C]">Correo electrónico</FormLabel>
                              <FormControl>
                                <Input
                                  type="email"
                                  title="Ingresa el correo electronico del propietario."
                                  className="px-4 py-3 border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none"
                                  placeholder="Ingresa el correo electronico"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      <div className="flex flex-col xl:flex-row w-full items-center gap-[27px]">
                        <FormField
                          control={form.control}
                          name="vehicleRegistrationNumber"
                          render={({ field }) => (
                            <FormItem className="w-full">
                              <FormLabel className="text-[#7C7C7C]">Placa del vehículo</FormLabel>
                              <FormControl>
                                <Input
                                  type="text"
                                  maxLength={6}
                                  title="Ingresa la placa del vehiculo sin espacios."
                                  className="px-4 py-3 border-t-0 border-r-0 border-l-0 rounded-none border-b-[1px] border-b-primary outline-none"
                                  placeholder={vehicleCategory === 'MOTOS' ? 'Ejemplo: AAA44 o AAA44A' : 'Ejemplo: AAA111'}
                                  {...field}
                                  onChange={(event) => field.onChange(sanitizePlate(event.target.value))}
                                />
                              </FormControl>
                              {plateValidationMessage && (
                                <p className="text-sm font-medium text-destructive">{plateValidationMessage}</p>
                              )}
                              {!plateValidationMessage && <FormMessage />}
                            </FormItem>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name="city"
                          render={({ field }) => (
                            <div className="w-full flex flex-col gap-4">
                              <FormLabel className="text-[#7C7C7C]">Ciudad de agendamiento</FormLabel>
                              <Select onValueChange={field.onChange} value={field.value}>
                                <SelectTrigger className="w-full border-primary px-4 py-3">
                                  <SelectValue placeholder="Seleccionar" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectGroup>
                                    {cityOptions.length > 0
                                      ? cityOptions.map((option: any) => (
                                        <SelectItem key={option} value={option}>{option}</SelectItem>
                                      ))
                                      : <SelectItem value='default'>No hay ciudades disponibles</SelectItem>}
                                  </SelectGroup>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </div>
                          )} />
                      </div>

                      <div className="flex flex-col xl:flex-row w-full gap-[27px]">
                        <FormField
                          control={form.control}
                          name="headquarters"
                          render={({ field }) => (
                            <div className="w-full flex flex-col gap-4">
                              <FormLabel className="text-[#7C7C7C]">Sede</FormLabel>
                              <Select onValueChange={field.onChange} value={field.value}>
                                <SelectTrigger className="w-full border-primary px-4 py-3">
                                  <SelectValue placeholder="Seleccionar" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectGroup>
                                    {headquartersOptions.length > 0
                                      ? headquartersOptions.map((option: any) => (
                                        <SelectItem key={option.name} value={option.value}>{option.name}</SelectItem>
                                      ))
                                      : <SelectItem value='default'>No hay sedes disponibles</SelectItem>}
                                  </SelectGroup>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </div>
                          )} />
                        <FormField
                          control={form.control}
                          name="typeOfVehicle"
                          render={({ field }) => (
                            <div className='w-full flex flex-col gap-4'>
                              <FormLabel className="text-[#7C7C7C]">Tipo de Vehículo</FormLabel>
                              <Select onValueChange={field.onChange} value={field.value}>
                                <SelectTrigger className="w-full border-primary px-4 py-3">
                                  <SelectValue placeholder="Seleccionar">{selectedTypeOfVehicle}</SelectValue>
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectGroup>
                                    {typeOfVehicleOptions && typeOfVehicleOptions.length > 0
                                      ? typeOfVehicleOptions.map((option: any, index: number) => (
                                        <SelectItem key={index} value={option.id}>{option.type}</SelectItem>
                                      ))
                                      : <SelectItem value='default'>No hay vehículos disponibles</SelectItem>}
                                  </SelectGroup>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </div>
                          )}
                        />
                      </div>

                      <div className="flex flex-col lg:flex-row w-full gap-[27px]">
                        <FormField
                          control={form.control}
                          name="vehicleAge"
                          render={({ field }) => (
                            <div className="w-full flex flex-col gap-4">
                              <FormLabel className="text-[#7C7C7C]">Años de antigüedad</FormLabel>
                              <Select
                                onValueChange={(value) => field.onChange(Number(value))}
                                value={field.value != null ? String(field.value) : ''}
                              >
                                <SelectTrigger className="w-full border-primary px-4 py-3">
                                  <SelectValue placeholder="Seleccionar" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectGroup>
                                    {vehicleAgeOptions.map((option) => (
                                      <SelectItem key={option.value} value={String(option.value)}>
                                        {option.label}
                                      </SelectItem>
                                    ))}
                                  </SelectGroup>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </div>
                          )}
                        />
                        <FormField
                          control={form.control}
                          name="serviceType"
                          render={({ field }) => (
                            <div className="w-full flex flex-col gap-4">
                              <FormLabel className="text-[#7C7C7C]">Tipo de servicio</FormLabel>
                              <Select onValueChange={field.onChange} value={field.value} disabled={!shouldShowServiceType}>
                                <SelectTrigger className="w-full border-primary px-4 py-3">
                                  <SelectValue placeholder={shouldShowServiceType ? 'Seleccionar' : 'No aplica para motos'} />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectGroup>
                                    {serviceTypes.map((serviceType) => (
                                      <SelectItem key={serviceType} value={serviceType}>{serviceType}</SelectItem>
                                    ))}
                                  </SelectGroup>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </div>
                          )}
                        />
                      </div>

                      <div className='w-full flex flex-col gap-4'>
                        <FormLabel className="text-[#7C7C7C]">Fecha y hora de agendamiento</FormLabel>
                        <div className='flex gap-4 justify-between'>
                          <FormField
                            control={form.control}
                            name="schedulingDate"
                            render={({ field }) => (
                              <FormItem className="flex flex-col w-full border-primary">
                                <Popover>
                                  <PopoverTrigger asChild>
                                    <FormControl>
                                      <Button
                                        variant={'outline'}
                                        className={cn(
                                          'pl-3 text-left font-normal border-primary',
                                          !field.value && 'text-muted-foreground'
                                        )}
                                      >
                                        {field.value
                                          ? format(field.value, 'PPP', { locale: es })
                                          : <span>Seleccionar Fecha</span>}
                                        <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                                      </Button>
                                    </FormControl>
                                  </PopoverTrigger>
                                  <PopoverContent className="w-auto p-0" align="start">
                                    <Calendar
                                      locale={es}
                                      mode="single"
                                      selected={field.value}
                                      onSelect={field.onChange}
                                      fromDate={today}
                                      disabled={(date) => colombianHolidays.some(holiday =>
                                        holiday.toLocaleDateString('es-CO', { timeZone: 'UTC' }) ===
                                        date.toLocaleDateString('es-CO', { timeZone: 'UTC' })
                                      ) || (shouldLimitCaliNorteSchedule && isSundayDate(date))}
                                      initialFocus
                                    />
                                  </PopoverContent>
                                </Popover>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                          <FormField
                            control={form.control}
                            name="hour"
                            render={({ field }) => (
                              <div className="w-full flex flex-col gap-4">
                                <Select onValueChange={field.onChange} value={field.value}>
                                  <SelectTrigger className="w-full border-primary px-4 py-3">
                                    <SelectValue placeholder="Seleccionar" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectGroup>
                                      {scheduleOptions && scheduleOptions.length > 0
                                        ? scheduleOptions.map((option: any, index: number) => (
                                          <SelectItem key={index} value={option || '00:00'}>{option}</SelectItem>
                                        ))
                                        : <SelectItem value='default'>No hay horarios disponibles</SelectItem>}
                                    </SelectGroup>
                                  </SelectContent>
                                </Select>
                                <FormMessage />
                              </div>
                          )} />
                        </div>
                      </div>

                      {!shouldShowPaymentCard && (
                        <FormField
                          control={form.control}
                          name="terms"
                          render={({ field }) => (
                            <FormItem className="flex flex-row items-start space-x-3 space-y-0 ">
                              <FormControl>
                                <Checkbox
                                  checked={field.value}
                                  onCheckedChange={field.onChange}
                                />
                              </FormControl>
                              <div className="space-y-1 leading-none">
                                <FormLabel className="text-[#7C7C7C]">
                                  Al marcar esta casilla acepto todos los{' '}
                                  <a className="text-primary underline underline-offset-2" href="/assets/files/PD-DA-03-aviso-de-privacidad.pdf" target="_blank" rel="noreferrer">Términos y condiciones</a>
                                  {' '}y la{' '}
                                  <a className="text-primary underline underline-offset-2" href="/assets/files/PD-DA-01-politica-de-tratamiento-de-datos.pdf" target="_blank" rel="noreferrer">política de privacidad</a>
                                  , así como el{' '}
                                  <a className="text-primary underline underline-offset-2" href="/assets/files/PD-DA-02-consentimiento-web.pdf" target="_blank" rel="noreferrer">consentimiento web</a>.
                                </FormLabel>
                                <FormMessage />
                              </div>
                            </FormItem>
                          )}
                        />
                      )}
                      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
                        <Button id="boton-agendar" type="submit" disabled={isPaymentButtonEnabled}>
                          Agendar
                        </Button>
                        <a
                          href="https://wa.me/+15558420890"
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex items-center justify-center gap-2 rounded-md border border-[#25D366] bg-white px-4 py-2 text-sm font-semibold text-[#128C7E] transition hover:bg-[#F0FFF4]"
                        >
                          <svg aria-hidden="true" viewBox="0 0 24 24" className="h-4 w-4 fill-current">
                            <path d="M19.05 4.94A9.77 9.77 0 0 0 12.09 2C6.65 2 2.22 6.42 2.22 11.87c0 1.74.46 3.44 1.32 4.94L2 22l5.34-1.4a9.9 9.9 0 0 0 4.74 1.21h.01c5.44 0 9.87-4.43 9.87-9.88a9.8 9.8 0 0 0-2.91-6.99Zm-6.96 15.2h-.01a8.2 8.2 0 0 1-4.18-1.15l-.3-.18-3.17.83.85-3.1-.2-.32a8.16 8.16 0 0 1-1.27-4.35c0-4.53 3.69-8.22 8.24-8.22 2.2 0 4.27.85 5.82 2.4a8.16 8.16 0 0 1 2.4 5.83c0 4.53-3.69 8.22-8.18 8.22Zm4.5-6.14c-.25-.12-1.47-.72-1.7-.8-.22-.08-.38-.12-.55.12-.16.25-.63.8-.77.96-.14.16-.29.18-.53.06-.25-.12-1.04-.38-1.98-1.22-.73-.65-1.22-1.45-1.36-1.7-.14-.24-.01-.37.1-.49.11-.11.25-.29.37-.43.12-.14.16-.25.25-.41.08-.16.04-.31-.02-.43-.06-.12-.55-1.32-.75-1.81-.2-.47-.4-.41-.55-.42h-.47c-.16 0-.43.06-.65.31-.22.25-.85.83-.85 2.02s.87 2.34.99 2.5c.12.16 1.71 2.62 4.15 3.67.58.25 1.04.41 1.4.52.59.19 1.12.16 1.54.1.47-.07 1.47-.6 1.68-1.18.2-.58.2-1.08.14-1.18-.06-.1-.22-.16-.47-.29Z" />
                          </svg>
                          <span>Hablar con un asesor</span>
                        </a>
                      </div>
                    </form>
                  </Form>)
                : <h1>Cargando formulario...</h1>}
            </div>

          </div>
          )
        : dataScheduling && (
          <div className="space-y-6">
            <Button
              type="button"
              onClick={handleReturnToForm}
              className="inline-flex items-center gap-2 bg-primary text-white hover:bg-primary/90"
            >
              <ArrowLeft className="h-4 w-4" />
              Volver al formulario
            </Button>

            <h1 className="text-[2rem] font-semibold mb-10">Se ha programado <span className="text-primary">exitosamente</span> tu revisión tecnomecánica!</h1>
            <TableScheduling dataScheduling={dataScheduling} />
          </div>
          )}
      <Toaster richColors position="top-right" style={{ backgroundColor: 'white' }} />
    </div>
  )
}

export default SchedulingForm
