'use client'

import CarCard from '@/components/shared/cards/CarCard'
import HeroForm from '@/components/shared/form/HeroForm'
import { Button } from '@/components/ui/button'
import { Section } from '@/components/ui/section'
import ImageLoader from '@/lib/utils/ImageLoader'
import { Car, Media } from '@/payload-types'
import { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { MultiSelect } from '@/components/ui/multiSelect'
import { CustomSelect } from '@/components/ui/select'
import { ChevronDown, X } from 'lucide-react'
import { FilterDrawer } from '@/components/shared/filterDrawer'
import { useCurrentLocale, useScopedI18n } from '@/locales/client'
import { Vehicle } from '@/lib/types/api/vehicle'
import { customFetch } from '@/lib/utils/apiClient'

function formatDateForRentsyst(dateStr: string) {
  const date = new Date(dateStr)
  const yyyy = date.getFullYear()
  const mm = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const min = String(date.getMinutes()).padStart(2, '0')
  // секунда всегда 00
  return `${yyyy}-${mm}-${dd} ${hh}:${min}:00`
}

export const CatalogContent = ({
  vehicles,
  bg,
  title,
}: {
  vehicles: Vehicle[]
  bg: Media
  title: string
}) => {
  const router = useRouter()
  const locale = useCurrentLocale()
  const [cars, setCars] = useState<Vehicle[]>(vehicles)
  // const [loading, setLoading] = useState(false)
  const [selectedModelValues, setSelectedModelValues] = useState<string[]>([])
  const [selectedSeatsValues, setSelectedSeatsValues] = useState<string[]>([])
  const [selectedColorValues, setSelectedColorValues] = useState<string[]>([])
  const [selectedPriceValues, setSelectedPriceValues] = useState<string[]>([])
  const [sortingType, setSortingType] = useState('default')
  const [actualParams, setActualParams] = useState('')
  const [filteredCars, setFilteredCars] = useState<Vehicle[]>(cars)
  const searchParams = useSearchParams()
  const [error, setError] = useState<string | null>(null);


  useEffect(() => {
    const fetchAvailableCars = async () => {
      let result = [...vehicles]

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

      // фильтрация по доступности через Rentsyst
      if (pu && re && dep && ret) {
        try {
          const dateFrom = formatDateForRentsyst(pu)
          const dateTo = formatDateForRentsyst(re)
      
          const url = `https://api.rentsyst.com/v2/booking/search?date_from=${encodeURIComponent(
            dateFrom,
          )}&date_to=${encodeURIComponent(dateTo)}&pickup_location=${encodeURIComponent(
            dep,
          )}&return_location=${encodeURIComponent(ret)}`
      
          const response = await customFetch(url, true, 'GET')
          const data = await response.json()
      
          if (data.status === 'error') {
            console.warn('Rentsyst API вернул ошибку:', data.message)
            // если ошибка, значит доступных машин нет
            result = []
          } else if (Array.isArray(data.vehicles)) {
            const availableIds = data.vehicles.map((car: any) => car.id)
            result = result.filter((car) => availableIds.includes(car.id))
          } else {
            // на всякий случай, если пришел неожиданный формат
            result = []
          }
        } catch (error) {
          console.error('Ошибка API Rentsyst:', error)
          result = []
        }
      }      

      // 2. фильтрация по остальным фильтрам
      if (selectedModelValues.length > 0) {
        result = result.filter((car) => selectedModelValues.includes(car.mark))
      }
      if (selectedSeatsValues.length > 0) {
        result = result.filter((car) => selectedSeatsValues.includes(String(car.number_seats)))
      }
      if (selectedColorValues.length > 0) {
        result = result.filter((car) => selectedColorValues.includes(car.color.title))
      }
      if (selectedPriceValues.length > 0) {
        result = result.filter((car) => {
          return selectedPriceValues.some((range) => {
            const price = car.price
            if (range === '0-50€') return price >= 0 && price <= 50
            if (range === '50-100€') return price > 50 && price <= 100
            if (range === '100-200€') return price > 100 && price <= 200
            if (range === '200€+') return price > 200
            return false
          })
        })
      }

      // сортировка
      if (sortingType === 'lowPrice') {
        result = result.sort((a, b) => a.price - b.price)
      } else if (sortingType === 'hightPrice') {
        result = result.sort((a, b) => b.price - a.price)
      }

      setFilteredCars(result)
    }

    fetchAvailableCars()
  }, [searchParams, vehicles, selectedModelValues, selectedSeatsValues, selectedColorValues, selectedPriceValues, sortingType])

  const t = useScopedI18n('catalog')
  return (
    <>
      <div className="relative w-full max-h-[460px]">
        {bg && <ImageLoader media={bg} className="w-full h-[460px] object-cover" />}
        <div className="absolute bottom-0 z-10 w-full translate-y-1/2">
          <Section sectionClass="z-20">
            <div className="h4 md:h1 text-base-white mb-8">{title}</div>
            <div className="relative rounded-xl p-[1px] bg-gradient-to-b from-[#3b3b3b] to-black">
              <div className="rounded-xl bg-black py-6 flex items-start md:items-center flex-col md:flex-row gap-y-4">
                <HeroForm className="mt-0" cars={cars} />
              </div>
            </div>
          </Section>
        </div>
        <div className="absolute h-[304px] w-full bottom-0  bg-[linear-gradient(180deg,rgba(0,0,0,0)_0%,#000_100%)]"></div>
      </div>
      <div className="pt-90 md:pt-60 pb-30">
        <div className="py-6 border-t border-b border-grey-600">
          <Section>
            <div className="flex justify-between">
              <div className="hidden lg:flex items-center gap-6">
                <MultiSelect
                  triggerLabel={t('labels.model')}
                  options={[...new Set(cars?.map((car) => car.mark) || [])].map((city) => ({
                    label: city,
                    value: city,
                  }))}
                  value={selectedModelValues}
                  onChange={(newValues) => setSelectedModelValues(newValues)}
                  placeholder={t('labels.model')}
                />
                <MultiSelect
                  triggerLabel={t('labels.numberOfSeats')}
                  options={[...new Set(cars?.map((car) => car.number_seats) || [])].map((city) => ({
                    label: String(city),
                    value: String(city),
                  }))}
                  value={selectedSeatsValues}
                  onChange={(newValues) => setSelectedSeatsValues(newValues)}
                  placeholder={t('labels.numberOfSeats')}
                />
                <MultiSelect
                  triggerLabel={t('labels.carColor')}
                  options={[...new Set(cars?.map((car) => car.color.title) || [])].map((city) => ({
                    label: city,
                    value: city,
                  }))}
                  value={selectedColorValues}
                  onChange={(newValues) => setSelectedColorValues(newValues)}
                  placeholder={t('labels.carColor')}
                />
                <MultiSelect
                  triggerLabel={t('labels.pricePerDay')}
                  options={[
                    { label: '0 - 50 €', value: '0-50€' },
                    { label: '50 - 100 €', value: '50-100€' },
                    { label: '100 - 200 €', value: '100-200€' },
                    { label: '200+ €', value: '200€+' },
                  ]}
                  value={selectedPriceValues}
                  onChange={(newValues) => setSelectedPriceValues(newValues)}
                  placeholder={t('labels.pricePerDay')}
                />
              </div>
              <div className="lg:hidden">
                <FilterDrawer
                  allModels={[...new Set(cars?.map((car) => car.mark) || [])].map((city) => ({
                    label: city,
                    value: city,
                  }))}
                  allSeats={[...new Set(cars?.map((car) => car.number_seats) || [])].map(
                    (city) => ({
                      label: String(city),
                      value: String(city),
                    }),
                  )}
                  allColors={[...new Set(cars?.map((car) => car.color.title) || [])].map(
                    (city) => ({
                      label: city,
                      value: city,
                    }),
                  )}
                  allPrices={[
                    { label: '0 - 50 €', value: '0-50€' },
                    { label: '50 - 100 €', value: '50-100€' },
                    { label: '100 - 200 €', value: '100-200€' },
                    { label: '200+ €', value: '200€+' },
                  ]}
                  models={selectedModelValues}
                  seats={selectedSeatsValues}
                  colors={selectedColorValues}
                  prices={selectedPriceValues}
                  setModels={setSelectedModelValues}
                  setSeats={setSelectedSeatsValues}
                  setColors={setSelectedColorValues}
                  setPrices={setSelectedPriceValues}
                />
              </div>
              <div className="flex items-center gap-3 relative">
                <div className="text-grey-300 label-large-regular">{t('labels.sorting')}:</div>
                <CustomSelect
                  value={sortingType}
                  onValueChange={(val) => setSortingType(val)}
                  hideDefaultIcon
                  options={[
                    { label: t('sortingType.default'), value: 'default' },
                    { label: t('sortingType.lowPrice'), value: 'lowPrice' },
                    { label: t('sortingType.hightPrice'), value: 'hightPrice' },
                  ]}
                  placeholder={t('placeholders.sorting')}
                  triggerClassName="bg-inherit border-0 text-base-white hover:text-beige-300 ring-0 focus-visible:ring-0 focus-visible:bg-inherit"
                />
                <div className="absolute -right-0.5 top-1/2 -translate-y-1/2">
                  <ChevronDown size={16} className="stroke-grey-50" />
                </div>
              </div>
            </div>
          </Section>
        </div>
        <Section>
          <div className="flex items-center justify-start flex-wrap gap-2 mt-6">
            {selectedModelValues.map((item, i) => (
              <div
                className="flex items-center gap-2 bg-grey-700 px-4 py-2 rounded-[40px] cursor-pointer hover:bg-grey-600"
                key={i}
              >
                <div className="text-grey-100 label-medium-regular">{item}</div>
                <X
                  onClick={() =>
                    setSelectedModelValues(selectedModelValues.filter((m) => m !== item))
                  }
                  size={16}
                  className="stroke-grey-100"
                />
              </div>
            ))}
            {selectedSeatsValues.map((item, i) => (
              <div
                className="flex items-center gap-2 bg-grey-700 px-4 py-2 rounded-[40px] cursor-pointer hover:bg-grey-600"
                key={i}
              >
                <div className="text-grey-100 label-medium-regular">{item}</div>
                <X
                  onClick={() =>
                    setSelectedSeatsValues(selectedSeatsValues.filter((m) => m !== item))
                  }
                  size={16}
                  className="stroke-grey-100"
                />
              </div>
            ))}
            {selectedColorValues.map((item, i) => (
              <div
                className="flex items-center gap-2 bg-grey-700 px-4 py-2 rounded-[40px] cursor-pointer hover:bg-grey-600"
                key={i}
              >
                <div className="text-grey-100 label-medium-regular">{item}</div>
                <X
                  onClick={() =>
                    setSelectedColorValues(selectedColorValues.filter((m) => m !== item))
                  }
                  size={16}
                  className="stroke-grey-100"
                />
              </div>
            ))}
            {selectedPriceValues.map((item, i) => (
              <div
                className="flex items-center gap-2 bg-grey-700 px-4 py-2 rounded-[40px] cursor-pointer hover:bg-grey-600"
                key={i}
              >
                <div className="text-grey-100 label-medium-regular">{item}</div>
                <X
                  onClick={() =>
                    setSelectedPriceValues(selectedPriceValues.filter((m) => m !== item))
                  }
                  size={16}
                  className="stroke-grey-100"
                />
              </div>
            ))}
            {[
              ...selectedModelValues,
              ...selectedSeatsValues,
              ...selectedColorValues,
              ...selectedPriceValues,
            ].length > 1 && (
              <div className="flex items-center gap-2  px-4 py-2 rounded-[40px] cursor-pointer hover:text-beige-300">
                <div className="text-grey-50 button-small-medium">{t('labels.clearAll')}</div>
                <X
                  onClick={() => {
                    setSelectedModelValues([])
                    setSelectedSeatsValues([])
                    setSelectedColorValues([])
                    setSelectedPriceValues([])
                    router.replace(`/${locale}/catalog`, { scroll: false })
                  }}
                  size={16}
                  className="stroke-grey-100"
                />
              </div>
            )}
          </div>
          <div className="flex w-full justify-center mt-6">
            <div className="inline-grid gap-4 mx-auto w-fit grid-cols-1 md:grid-cols-2 lg:grid-cols-4">
              {filteredCars.length > 0 ? (
                filteredCars.map((car) => (
                  <CarCard
                    href={actualParams ? `/${locale}/booking/${car.id}${actualParams}` : null}
                    key={car.id}
                    type={
                      car.brand.charAt(0).toUpperCase() +
                      car.brand.slice(1).toLowerCase() +
                      ' ' +
                      car.mark
                    }
                    price={car.price}
                    image={car.thumbnail}
                    carLabels={[car.color.title, `${car.number_seats} seats`].filter(Boolean)}
                    id={car.id}
                  />
                ))
              ) : (
                <div className="text-center text-grey-300 w-full">{t('labels.noCarsFound')}</div>
              )}
            </div>
          </div>
          {/* {hasNextPage && (
            <div className="mt-8 flex justify-center">
              <Button onClick={handleLoadMore} disabled={loading} variant="secondary">
                {loading ? 'Loading...' : 'Show more'}
              </Button>
            </div>
          )} */}
        </Section>
      </div>
    </>
  )
}

export default CatalogContent
