'use client'

import { customFetch } from '@/lib/utils/apiClient'
import { CustomBreadcrumb } from '@/components/ui/breadcrumb'
import { useCurrentLocale, useI18n } from '@/locales/client'
import { Car } from '@/payload-types'
import { BookingContentBlock } from './BookingContentBlock'
import { BadgeEuro, CirclePlus, ClipboardList, FileText, MapPin, UserRound } from 'lucide-react'
import ImageLoader from '@/lib/utils/ImageLoader'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { InformationCircleIcon } from '@/components/icons/common'
import { cn } from '@/lib/utils/cn'
import { Checkbox } from '@/components/ui/checkbox'
import { useState, useEffect } from 'react'

import { useForm, FormProvider, Controller } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'

import { CustomInput } from '@/components/ui/CustomInput'
import CalendarWithTrigger from '@/components/ui/CalendarWithTrigger'
import { TimeInput } from '@/components/ui/TimeSelect'
import { Textarea } from '@/components/ui/textarea'
import { FileUploader } from '@/components/ui/fileUploader'
import { ListItemRadio, RadioGroup } from '@/components/ui/listItemRadio'
import { useErrorModalContent, useGetCongratsModal } from './BookingModals'
import { useSearchParams } from 'next/navigation'
import { CustomSelect } from '@/components/ui/select'
import { Vehicle } from '@/lib/types/api/vehicle'

const bookingSchema = z.object({
  departure: z.string().min(1, 'Please select a departure point'),
  returnLocation: z.string().min(1, 'Please select a return point'),
  pickUpDate: z.date(),
  pickUpTime: z.date(),
  returnDate: z.date(),
  returnTime: z.date() ,
  childSeat: z.boolean(),
  terms: z.literal(true, {
    errorMap: () => ({ message: 'You must agree to the terms' }),
  }),
  transfer: z.boolean(),
  withDriver: z.boolean(),
  paymentMethod: z.enum(['Card', 'Bank transfer', 'Electronic money', 'Cash'], {
    required_error: 'Please select a payment method',
  }),
  name: z.string().min(2, 'Please enter your name').max(50, 'Name must be at most 50 characters'),
  lastName: z
    .string()
    .min(2, 'Please enter your last name')
    .max(50, 'Last name must be at most 50 characters'),
  phone: z.string().regex(/^\+?[0-9]{6,15}$/, {
    message: 'Phone number must contain 6–15 digits and may start with "+"',
  }),
  email: z.string().min(1, 'Please enter your email').email('Invalid email format'),
  additional: z.string().max(300, 'Additional requests must be at most 300 characters').optional(),
  documents: z.array(z.instanceof(File)).min(1, 'Please upload at least one document'),
})
.refine((data) => {
  return data.returnTime > data.pickUpTime
}, {
  message: 'Return time cannot be before or equal pick-up time',
  path: ['returnTime'],
})


type BookingForm = z.infer<typeof bookingSchema>

const formatLocalDateTime = (date: Date, time: Date) => {
  const dateStr = date.toLocaleDateString('en-CA') // YYYY-MM-DD
  const timeStr = time.toTimeString().split(' ')[0] // HH:mm:ss
  return `${dateStr} ${timeStr}`
}

interface BookingDate {
  from: string // лучше string, т.к. у тебя API отдаёт строки
  to: string
}

interface BookingInfo {
  status: 'success' | 'error' // можно сузить или оставить string
  dates: []
}

interface BookingProps extends Vehicle {
  booking?: BookingInfo
}


export const BookingContent = ({
  id,
  brand,
  mark,
  price,
  currency,
  thumbnail,
  locations,
  booking, // теперь доступен
}: BookingProps) => {
  const carName = `${brand} ${mark}`

  // --- Функция отправки данных и файла в Telegram ---
  async function sendBooking(data: BookingForm) {
    try {
      // Calculate total price before creating booking data
      const daysPrice = countOfDays * price
      const optionsPricePerDay =
        (data.childSeat ? 5 : 0) + (data.transfer ? 10 : 0) + (data.withDriver ? 10 : 0)
      const optionsTotal = optionsPricePerDay * countOfDays
      const totalPrice = daysPrice + optionsTotal

      const formBooking = new FormData()
      formBooking.append('vehicle_id', id.toString())
      formBooking.append('pickup_location', data.departure.toString())
      formBooking.append('return_location', data.returnLocation.toString())
      formBooking.append('date_from', formatLocalDateTime(data.pickUpDate, data.pickUpTime))
      formBooking.append('date_to', formatLocalDateTime(data.returnDate, data.returnTime))


      // 1. Создание заказа (Order Create)
      const createResp = await customFetch(
        'https://api.rentsyst.com/v2/order/create',
        true,
        'POST',
        {
          body: formBooking,
        },
      )


      if (!createResp.ok) throw new Error('Error creating order')
      const createData = await createResp.json()

      if (createData.status === 'error') throw new Error(createData.message)
      const orderId = createData.order_id
      if (!orderId) throw new Error('Order ID not returned')


      // 2. Обновление заказа — добавление страховки и опций (Order Update)
      // Нужно достать ID страховки и опций из createData.options (пример)
      const insuranceId = createData.insurances?.[0]?.id || null
      if (!insuranceId) {
        throw new Error('No insurance available')
      } // либо автоматически подобрать из createData.options, если есть

      const extras: Record<string, number> = {}
      createData.options.forEach((opt: any) => {
        if (
          (data.childSeat && opt.title.toLowerCase().includes('child seat')) ||
          (data.transfer && opt.title.toLowerCase().includes('transfer')) ||
          (data.withDriver && opt.title.toLowerCase().includes('driver'))
        ) {
          extras[opt.id] = 1
        }
      })

      const updateResp = await customFetch(
        `https://api.rentsyst.com/v2/order/update/${orderId}`,
        true,
        'POST',
        {
          body: {
            insurance: insuranceId,
            extras,
          },
        },
      )

      if (!updateResp.ok) throw new Error('Error updating order')
      const updateData = await updateResp.json()


      const uploadedFiles: string[] = []

      for (const file of data.documents) {
        const fileFormData = new FormData()
        fileFormData.append('file', file)

        const fileResp = await customFetch(
          'https://api.rentsyst.com/v2/file/upload',
          true,
          'POST',
          { body: fileFormData },
        )

        if (!fileResp.ok) throw new Error('Error uploading file: ' + file.name)

        const fileData = await fileResp.json()

        // Учитываем оба варианта ответа: объект или массив
        if (Array.isArray(fileData)) {
          uploadedFiles.push(fileData[0].id)
        } else if (fileData && fileData.id) {
          uploadedFiles.push(fileData.id)
        }
      }


      // 3. Подтверждение заказа — добавление данных клиента и способа оплаты (Order Confirm)
      const confirmResp = await customFetch(
        `https://api.rentsyst.com/v2/order/confirm/${orderId}`,
        true,
        'POST',
        {
          body: {
            drivers: [
              {
                first_name: data.name,
                last_name: data.lastName,
                email: data.email,
                phone: data.phone,
                // country: data.country,
                // zip: data.zip,
                // state: data.state,
                // city: data.city,
                // address: data.address,
                // building: data.building,
                // birthday: data.birthday,
                notes: data.additional,
                license_num: "123321",
                license_from: "2010-05-17",
                license_to: "2030-05-17",
                license_photo: uploadedFiles,
              },
            ],
            payment_method: 'Bank transfer',
          },
        },
      )
      if (!confirmResp.ok) throw new Error('Error confirming order')
      const confirmData = await confirmResp.json()
      console.log('Confirm request success:', confirmData)
      // Возвращаем ссылку на оплату или другие данные
      return confirmData

    } catch (error) {
      console.error('Booking error:', error)
      throw error
    }
  }

  const roundToNext30Min = (date: Date) => {
    const newDate = new Date(date)
    const minutes = newDate.getMinutes()
    const roundedMinutes = minutes < 30 ? 30 : 0
    if (roundedMinutes === 0) {
      newDate.setHours(newDate.getHours() + 1)
    }
    newDate.setMinutes(roundedMinutes, 0, 0)
    return newDate
  }

  const locale = useCurrentLocale()
  const [countOfDays, setCountOfDays] = useState(0)
  const [isTooltipOpen, setIsTooltipOpen] = useState(false)
  const searchParams = useSearchParams()

  const dep = searchParams.get('departure')
  const ret = searchParams.get('returnLocation')
  const pu = searchParams.get('pickUpDate')
  const re = searchParams.get('returnDate')
  const withDriverQuery = searchParams.get('withDriver') === 'true'
  const withoutDriver = searchParams.get('withoutDriver') === 'true'

  const defaultValues: Partial<BookingForm> = {
    pickUpDate: pu ? new Date(pu) : undefined,
    pickUpTime: pu ? roundToNext30Min(new Date(pu)) : undefined,
    returnDate: re ? new Date(re) : undefined,
    returnTime: re ? roundToNext30Min(new Date(re)) : undefined,
    childSeat: false,
    transfer: false,
    withDriver: withDriverQuery || !withoutDriver,
    terms: undefined,
    paymentMethod: 'Bank transfer',
    name: '',
    lastName: '',
    phone: '',
    email: '',
    additional: '',
    departure: dep || '',
    returnLocation: ret || '',
    documents: [],
  }

  const form = useForm<BookingForm>({
    resolver: zodResolver(bookingSchema),
    mode: 'onChange',
    defaultValues,
  })

  const pickUpDate = form.watch('pickUpDate')
  const returnDate = form.watch('returnDate')
  const childSeat = form.watch('childSeat')
  const transfer = form.watch('transfer')
  const withDriver = form.watch('withDriver')

  useEffect(() => {
    if (pickUpDate && returnDate) {
      const msPerDay = 1000 * 60 * 60 * 24
      const diff = returnDate.getTime() - pickUpDate.getTime()
      setCountOfDays(Math.max(0, Math.ceil(diff / msPerDay)))
    }
  }, [pickUpDate, returnDate])

  const daysPrice = countOfDays * price
  const optionsPricePerDay = (childSeat ? 5 : 0) + (transfer ? 10 : 0) + (withDriver ? 10 : 0)
  const optionsTotal = optionsPricePerDay * countOfDays
  const totalPrice = daysPrice + optionsTotal

  const successModal = useGetCongratsModal()
  const errorModal = useErrorModalContent()

  const t = useI18n()

  
  

  return (
    <FormProvider {...form}>
      <form
        onSubmit={form.handleSubmit(async (data) => {
          try {
            await sendBooking(data)
            successModal.setModalOpen(true)
            form.reset()
            // onSubmit(data)
          } catch (e) {
            errorModal.setModalOpen(true)
          }
        })}
      >
        <div className="pt-20">
          <CustomBreadcrumb
            pages={[
              { pageName: t('navigation.catalog'), href: `/${locale}` },
              { pageName: t('navigation.booking'), href: `${locale}/booking`, isActive: true },
            ]}
          />
          <h2 className="h2 mt-17 mb-12 text-base-white">{t('booking.title')}</h2>
          <div className="flex flex-col xxl:flex-row items-center xxl:items-start justify-between relative gap-y-6">
            <div className="w-full lg:w-[684px] flex flex-col gap-6">
              <BookingContentBlock
                title={t('booking.bookingDetails')}
                icon={<ClipboardList size={24} className="text-base-white" />}
              >
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2 mt-6">
                  <Controller
                    name="departure"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomSelect
                        {...field}
                        onValueChange={field.onChange}
                        hideDefaultIcon
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        iconLeft={<MapPin size={20} className="stroke-grey-200" />}
                        label={t('booking.labels.departure')}
                        options={[...new Set(locations?.map((car) => car.name) || [])].map(
                          (city) => ({
                            label: city,
                            value: city,
                          }),
                        )}
                        placeholder={t('booking.placeholders.departure')}
                      />
                    )}
                  />

                  <Controller
                    name="returnLocation"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomSelect
                        {...field}
                        onValueChange={field.onChange}
                        hideDefaultIcon
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        iconLeft={<MapPin size={20} className="stroke-grey-200" />}
                        label={t('booking.labels.returnLocation')}
                        options={[...new Set(locations?.map((car) => car.name) || [])].map(
                          (city) => ({
                            label: city,
                            value: city,
                          }),
                        )}
                        placeholder={t('booking.placeholders.departure')}
                      />
                    )}
                  />

                  <Controller
                    name="pickUpDate"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CalendarWithTrigger
                        {...field}
                        hideTime
                        className="w-full"
                        label={t('booking.labels.pickUpDate')}
                        placeholder={t('booking.placeholders.pickUpDate')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        bookedDates={booking?.dates}
                      />
                    )}
                  />

                  <Controller
                    name="pickUpTime"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <TimeInput
                        value={field.value}
                        onChange={field.onChange}
                        label={t('booking.labels.pickUpTime')}
                        placeholder={t('booking.placeholders.selectTime')}
                        selectedDate={form.watch('pickUpDate')}
                        className="w-full"
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                      />
                    )}
                  />

                  <Controller
                    name="returnDate"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CalendarWithTrigger
                        {...field}
                        hideTime
                        className="w-full"
                        label={t('booking.labels.returnDate')}
                        placeholder={t('booking.placeholders.returnDate')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        bookedDates={booking?.dates}
                      />
                    )}
                  />

                  <Controller
                    name="returnTime"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <TimeInput
                        value={field.value}
                        onChange={field.onChange}
                        label={t('booking.labels.returnTime')}
                        placeholder={t('booking.placeholders.selectTime')}
                        className="w-full"
                        selectedDate={form.watch('returnDate')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                      />
                    )}
                  />
                </div>
              </BookingContentBlock>

              <BookingContentBlock
                title={t('booking.additional.title')}
                icon={<CirclePlus size={24} className="text-base-white" />}
              >
                <div className="mt-6 flex flex-col gap-4">
                  <div
                    className={cn(
                      'rounded-lg p-4 transition-all duration-200',
                      form.watch('childSeat')
                        ? 'border border-[#d39e7f] bg-[rgba(252,252,252,0.08)]'
                        : 'border border-transparent bg-transparent',
                    )}
                  >
                    <Controller
                      name="childSeat"
                      control={form.control}
                      render={({ field }) => (
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                          onBlur={field.onBlur}
                          label={t('booking.additional.childSeat')}
                        />
                      )}
                    />
                  </div>
                  <div
                    className={cn(
                      'rounded-lg p-4 transition-all duration-200',
                      form.watch('transfer')
                        ? 'border border-[#d39e7f] bg-[rgba(252,252,252,0.08)]'
                        : 'border border-transparent bg-transparent',
                    )}
                  >
                    <Controller
                      name="transfer"
                      control={form.control}
                      render={({ field }) => (
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                          onBlur={field.onBlur}
                          label={t('booking.additional.transfer')}
                        />
                      )}
                    />
                  </div>
                  <div
                    className={cn(
                      'rounded-lg p-4 transition-all duration-200',
                      form.watch('withDriver')
                        ? 'border border-[#d39e7f] bg-[rgba(252,252,252,0.08)]'
                        : 'border border-transparent bg-transparent',
                    )}
                  >
                    <Controller
                      name="withDriver"
                      control={form.control}
                      render={({ field }) => (
                        <Checkbox
                          checked={field.value}
                          onCheckedChange={field.onChange}
                          onBlur={field.onBlur}
                          label={t('booking.additional.withDriver')}
                        />
                      )}
                    />
                  </div>
                </div>
              </BookingContentBlock>
              <BookingContentBlock
                title={t('booking.personalInformation.title')}
                icon={<UserRound size={24} className="text-base-white" />}
              >
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2 mt-6">
                  <Controller
                    name="name"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomInput
                        {...field}
                        className="w-full"
                        label={t('booking.personalInformation.labels.name')}
                        placeholder={t('booking.personalInformation.labels.name')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        onChange={(e) => {
                          const raw = e.target.value

                          // Удаляем все неразрешённые символы
                          let filtered = raw
                            .split('')
                            .filter((ch) => /[a-zA-Zа-яА-Я'-]/.test(ch))
                            .join('')

                          // Удаляем начальные символы, если это не буква
                          while (filtered.length && !/^[a-zA-Zа-яА-Я]$/.test(filtered[0])) {
                            filtered = filtered.slice(1)
                          }

                          field.onChange(filtered)
                        }}
                        onKeyDown={(e) => {
                          // Разрешаем: буквы, апостроф, дефис, Backspace и стрелки
                          const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Tab']
                          const isAllowedChar = /^[a-zA-Zа-яА-Я'-]$/.test(e.key)

                          if (
                            e.key.length === 1 && // только символы
                            !isAllowedChar &&
                            !allowedKeys.includes(e.key)
                          ) {
                            e.preventDefault()
                          }

                          // Блокируем первый символ, если он не буква
                          const isFirstChar = e.currentTarget.selectionStart === 0
                          const isLetter = /^[a-zA-Zа-яА-Я]$/.test(e.key)
                          if (isFirstChar && !isLetter && !allowedKeys.includes(e.key)) {
                            e.preventDefault()
                          }
                        }}
                      />
                    )}
                  />

                  <Controller
                    name="lastName"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomInput
                        {...field}
                        className="w-full"
                        label={t('booking.personalInformation.labels.lastName')}
                        placeholder={t('booking.personalInformation.labels.lastName')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        onChange={(e) => {
                          const raw = e.target.value

                          // Удаляем все неразрешённые символы
                          let filtered = raw
                            .split('')
                            .filter((ch) => /[a-zA-Zа-яА-Я'-]/.test(ch))
                            .join('')

                          // Удаляем начальные символы, если это не буква
                          while (filtered.length && !/^[a-zA-Zа-яА-Я]$/.test(filtered[0])) {
                            filtered = filtered.slice(1)
                          }

                          field.onChange(filtered)
                        }}
                        onKeyDown={(e) => {
                          // Разрешаем: буквы, апостроф, дефис, Backspace и стрелки
                          const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Tab']
                          const isAllowedChar = /^[a-zA-Zа-яА-Я'-]$/.test(e.key)

                          if (
                            e.key.length === 1 && // только символы
                            !isAllowedChar &&
                            !allowedKeys.includes(e.key)
                          ) {
                            e.preventDefault()
                          }

                          // Блокируем первый символ, если он не буква
                          const isFirstChar = e.currentTarget.selectionStart === 0
                          const isLetter = /^[a-zA-Zа-яА-Я]$/.test(e.key)
                          if (isFirstChar && !isLetter && !allowedKeys.includes(e.key)) {
                            e.preventDefault()
                          }
                        }}
                      />
                    )}
                  />

                  <Controller
                    name="phone"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomInput
                        {...field}
                        className="w-full"
                        label={t('booking.personalInformation.labels.phone')}
                        placeholder={t('booking.personalInformation.labels.phone')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        onChange={(e) => {
                          const raw = e.target.value
                          const cleaned = raw
                            .replace(/[^0-9+]/g, '') // удаляем всё кроме цифр и +
                            .replace(/(?!^)\+/g, '') // удаляем все "+" кроме первого символа
                          field.onChange(cleaned)
                        }}
                      />
                    )}
                  />
                  <Controller
                    name="email"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <CustomInput
                        {...field}
                        className="w-full"
                        label={t('booking.personalInformation.labels.email')}
                        placeholder={t('booking.personalInformation.labels.email')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                        onChange={(e) => {
                          const raw = e.target.value

                          // Разрешаем только латиницу, цифры, @, точку, дефис и подчёркивание
                          const cleaned = raw.replace(/[^a-zA-Z0-9@._\-]/g, '')
                          field.onChange(cleaned)
                        }}
                        onKeyDown={(e) => {
                          // Блокируем пробел и кириллицу/символы
                          const forbiddenChars = /[^a-zA-Z0-9@._\-]/
                          if (forbiddenChars.test(e.key)) {
                            e.preventDefault()
                          }
                        }}
                      />
                    )}
                  />
                </div>

                <div className="mt-6">
                  <Controller
                    name="additional"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <Textarea
                        {...field}
                        label={t('booking.personalInformation.labels.additional')}
                        placeholder={t('booking.personalInformation.labels.additional')}
                        className="min-h-[140px] resize-none"
                        maxLength={300}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                      />
                    )}
                  />
                </div>
              </BookingContentBlock>
              <BookingContentBlock
                isFileUploaderForm={true}
                title={t('booking.documents.title')}
                icon={<FileText size={24} className="text-base-white" />}
                isTooltipOpen={isTooltipOpen}
                onTooltipOpenChange={setIsTooltipOpen}
              >
                <div className="mt-6">
                  <Controller
                    name="documents"
                    control={form.control}
                    render={({ field, fieldState }) => (
                      <FileUploader
                        value={field.value}
                        onChange={(newFiles) => {
                          field.onChange(newFiles)
                          if (newFiles.length > field.value.length) {
                            setIsTooltipOpen(true)
                            setTimeout(() => setIsTooltipOpen(false), 3000)
                          }
                        }}
                        underText={t('booking.documents.underText')}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                      />
                    )}
                  />
                </div>
              </BookingContentBlock>
              <BookingContentBlock
                title={t('booking.payment.title')}
                icon={<BadgeEuro size={24} className="text-base-white" />}
              >
                <div className="mt-6">
                  <Controller
                    control={form.control}
                    name="paymentMethod"
                    render={({ field, fieldState }) => (
                      <RadioGroup
                        value={field.value}
                        onValueChange={field.onChange}
                        hasError={!!fieldState.error}
                        errorMessage={fieldState.error?.message}
                      >
                        <ListItemRadio label={t('booking.payment.labels.card')} id="card" value="Card" />
                        <ListItemRadio label={t('booking.payment.labels.transfer')} id="transfer" value="Bank transfer" />
                        <ListItemRadio label={t('booking.payment.labels.payPal')} id="payPal" value="Electronic money" />
                        <ListItemRadio label={t('booking.payment.labels.cash')} id="cash" value="Cash" />
                      </RadioGroup>
                    )}
                  />
                </div>
              </BookingContentBlock>
            </div>

            <div className="w-full lg:w-[484px] sticky top-20">
              <BookingContentBlock>
                <ImageLoader
                  media={thumbnail}
                  width={436}
                  height={226}
                  className="w-[436px] h-[226px] object-cover"
                />
                <div className="mt-6 mb-8 flex items-center justify-between">
                  <div className="subheadline-semibold text-grey-50">{brand} {mark}</div>
                  <Link href={`/${locale}/catalog`}>
                    <Button variant="secondary">{t('booking.carCard.changeCar')}</Button>
                  </Link>
                </div>
                {countOfDays > 0 && (
                  <CalculatorLine
                    title={`${price} € Х ${countOfDays} ${countOfDays === 1 ? 'day' : 'days'}`}
                    value={`${daysPrice.toFixed(2)}€`}
                  />
                )}
                {countOfDays > 0 && childSeat && (
                  <CalculatorLine title={t('booking.carCard.childSeat')} value={`${countOfDays * 5}€`} />
                )}
                {countOfDays > 0 && transfer && (
                  <CalculatorLine title={t('booking.carCard.transfer')} value={`${countOfDays * 10}€`} />
                )}
                {countOfDays > 0 && withDriver && (
                  <CalculatorLine
                    title={t('booking.carCard.withDriver')}
                    value={`${countOfDays * 10}€`}
                  />
                )}
                {countOfDays > 0 && (
                  <CalculatorLine
                    title={t('booking.carCard.total')}
                    titleClassname="subheadline-medium"
                    valueClassname="subheadline-medium text-grey-50"
                    value={`${totalPrice.toFixed(2)} €`}
                    hideBorder
                  />
                )}
                <div className="flex items-center gap-2 text-grey-50 mt-10">
                  <InformationCircleIcon className="size-4 " />
                  <div className="label-medium-regular">
                    {t('booking.carCard.deposit')}
                  </div>
                </div>
                <Button
                  disabled={totalPrice <= 0 || form.formState.isSubmitting}
                  className="my-4 w-full justify-center"
                  variant="secondary"
                >
                  {form.formState.isSubmitting ? t('booking.carCard.loading') : t('booking.carCard.bookCar')}
                </Button>
                <Controller
                  name="terms"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={field.onChange}
                      onBlur={field.onBlur}
                      hasError={!!fieldState.error}
                      errorMessage={fieldState.error?.message}
                      label={t('booking.carCard.terms')}
                    />
                  )}
                />
              </BookingContentBlock>
            </div>
          </div>
        </div>
        {successModal.modalComponent}
        {errorModal.modalComponent}
      </form>
    </FormProvider>
  )
}

export const CalculatorLine = ({
  title,
  value,
  titleClassname,
  valueClassname,
  hideBorder = false,
}: {
  title: string
  value?: string | number | null
  titleClassname?: string
  valueClassname?: string
  hideBorder?: boolean
}) => {
  const formattedValue = (() => {
    if (value === null) return 'N/A'
    if (typeof value === 'number') {
      if (title.toLowerCase().includes('price')) {
        return `${value} ${title.toLowerCase().includes('tariff') ? 'per day' : ''}`
      }
      return value.toString()
    }
    if (typeof value === 'string') {
      if (title.toLowerCase().includes('tariff')) {
        return `${value} per day`
      }
      return value
    }
    return value
  })()

  return (
    <div
      className={cn(
        'flex items-center justify-between py-3 border-b border-grey-700 min-h-fit',
        hideBorder && 'border-none',
      )}
    >
      <div className={cn('b2-regular text-grey-200', titleClassname)}>{title}</div>
      <div className={cn('b2-regular text-grey-200', valueClassname)}>
        {typeof formattedValue === 'string' && formattedValue.includes('per day') ? (
          <span>
            {formattedValue.replace(' per day', '')}
            <span className="text-grey-100"> per day</span>
          </span>
        ) : (
          formattedValue
        )}
      </div>
    </div>
  )
}
