'use client'

import React, { useState } from 'react'
import Image from 'next/image'
import Button from '@/components/ui/Button'
import { SearchCardProps } from '@/app/types'
import noPhoto from '../../../../public/images/noPhoto.png'
import LeadPopup from '@/components/popups/LeadPopup'
import useUserStore from '@/app/store/userStore'
import { useRouter } from 'next/navigation'

const formatDateTime = (dateTimeString: string): string => {
  const date = new Date(dateTimeString)
  const formatter = new Intl.DateTimeFormat('ru-RU', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  })

  const timeFormatter = new Intl.DateTimeFormat('ru-RU', {
    hour: '2-digit',
    minute: '2-digit',
  })

  const dateStr = formatter.format(date).replace(' г.', '')
  const timeStr = timeFormatter.format(date)

  return `${dateStr}, ${timeStr}`
}

const SearchCard = ({
  id,
  username,
  owner_type,
  from_city_name,
  from_country_name,
  to_city_name,
  to_country_name,
  formatted_cargo_type,
  formatted_transport,
  type_transport,
  userImg,
  comment,
  formatted_departure,
  formatted_arrival,
  country_from_icon,
  country_to_icon,
}: SearchCardProps) => {
  const [isLeadPopupOpen, setIsLeadPopupOpen] = useState(false)
  const { isAuthenticated } = useUserStore()
  const router = useRouter()

  const handleLeadClick = () => {
    if (!isAuthenticated) {
      router.push('/login')
      return
    }
    setIsLeadPopupOpen(true)
  }

  const getUserRequestStyles = () => {
    if (owner_type === 'customer') {
      return 'text-[#065bff]'
    }
    return 'text-[#45c226]'
  }

  const setMovingTypeIcon = () => {
    if (type_transport === 'avia') {
      return '/images/airplane.png'
    }
    return '/images/car.png'
  }

  const userRequest = owner_type === 'customer' ? 'Нужен перевозчик' : 'Могу перевезти'

  return (
    <>
      {/* десктоп */}
      <div className="hidden sm:block">
        <div className="my-4 w-full rounded-xl bg-white p-6 shadow-lg">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-5">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gray-200">
                <Image
                  src={userImg || noPhoto}
                  alt={`User ${username}`}
                  width={52}
                  height={52}
                  className="aspect-square w-full rounded-full object-cover md:w-[84px]"
                />
              </div>
              <div className="flex items-center gap-3">
                <div className="text-base font-semibold">{username}</div>
                <div className="text-gray-500">|</div>
                <div className={`text-base font-semibold ${getUserRequestStyles()}`}>
                  {userRequest}
                </div>
                <div className="ml-1">
                  Тип посылки:{' '}
                  <span className="text-orange ml-1 font-semibold">{formatted_cargo_type}</span>
                </div>
              </div>
            </div>
            <Button
              text="Откликнуться"
              className="bg-orange hover:bg-orange/80 cursor-pointer px-10 py-3 text-base font-semibold text-white transition-colors"
              onClick={handleLeadClick}
            />
          </div>
          {comment && (
            <div className="rounded-lg bg-[#f8f8f8] p-5">
              <div className="flex items-baseline gap-2">
                <span className="text-gray-600">{comment}</span>
              </div>
            </div>
          )}

          <div className="flex justify-end pt-2 text-sm text-gray-500">Объявление № {id}</div>

          <div className="mt-6 flex items-center justify-between">
            <div className="flex flex-col">
              {userRequest === 'Нужен перевозчик' ? (
                <span className="text-gray-500">Забрать из:</span>
              ) : (
                <span className="text-gray-500">Выезжаю из:</span>
              )}
              <div className="flex flex-col">
                <div className="flex items-center">
                  <Image
                    src={country_from_icon}
                    width={26}
                    height={13}
                    alt={from_country_name.substring(0, 3)}
                  />
                  <span className="pr-2 pl-1 text-gray-400">
                    {from_country_name.substring(0, 3).toUpperCase()}
                  </span>
                  <span className="text-base font-semibold">
                    {from_city_name} / {from_country_name}
                  </span>
                </div>
                {userRequest === 'Могу перевезти' && (
                  <div className="mt-1 text-sm text-gray-500">
                    <span className="text-sm font-normal">Отправление:</span>{' '}
                    <span className="text-sm font-semibold">
                      {formatDateTime(formatted_departure)}
                    </span>
                  </div>
                )}
              </div>
            </div>

            <div className="text-center">
              <div className="flex items-center justify-center gap-2">
                <span className="text-base font-semibold">{formatted_transport}</span>
                <Image
                  src={setMovingTypeIcon()}
                  width={15}
                  height={15}
                  alt="route vector"
                  className="h-[15px] w-[15px] object-contain"
                />
              </div>
              <div className="mx-auto my-1 flex w-[500px] items-center justify-between">
                <Image
                  src="/images/vector.svg"
                  width={500}
                  height={6}
                  alt="route vector"
                  className="absolute"
                />
                <div className="relative z-10 h-5 w-5 rounded-full border-3 border-[#065bff] bg-white" />
                <div className="relative z-10 h-5 w-5 rounded-full border-3 border-[#45c226] bg-white" />
              </div>

              {userRequest === 'Нужен перевозчик' && (
                <div className="text-sm text-gray-500">
                  <span className="text-sm font-normal">Дата доставки:</span>{' '}
                  <span className="text-sm font-semibold">{formatDateTime(formatted_arrival)}</span>
                </div>
              )}
            </div>

            <div className="-mb-[14px] flex flex-col">
              {userRequest === 'Нужен перевозчик' ? (
                <div className="text-base text-gray-500">Доставить в:</div>
              ) : (
                <div className="text-base text-gray-500">Прибываю в:</div>
              )}

              <div className="flex flex-col">
                <div className="flex items-center">
                  <Image
                    src={country_to_icon}
                    width={26}
                    height={13}
                    alt={to_country_name.substring(0, 3)}
                  />
                  <span className="pr-2 pl-1 text-gray-400">
                    {to_country_name.substring(0, 3).toUpperCase()}
                  </span>
                  <span className="text-base font-semibold">
                    {to_city_name} / {to_country_name}
                  </span>
                </div>
                {userRequest === 'Могу перевезти' && (
                  <div className="text-sm text-gray-500">
                    <span className="text-sm font-normal">Прибытие:</span>{' '}
                    <span className="text-sm font-semibold">
                      {formatDateTime(formatted_arrival)}
                    </span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* мобилка */}
      <div className="block sm:hidden">
        <div className="my-4 w-full rounded-xl bg-white p-4 shadow-lg">
          <div className="flex items-center justify-between">
            <div className={`text-sm font-semibold ${getUserRequestStyles()}`}>{userRequest}</div>
            <div className="text-sm font-semibold">
              <span className="text-orange">{formatted_cargo_type}</span>
            </div>
          </div>
          <div className="mt-5 mb-2 flex flex-row items-center justify-between gap-3">
            <div className="flex h-16 w-16 min-w-[64px] shrink-0 items-center justify-center rounded-full bg-gray-200">
              <Image
                src={noPhoto}
                alt={`User ${username}`}
                width={52}
                height={52}
                className="aspect-square h-[52px] w-[52px] rounded-full object-cover"
              />
            </div>
            <div className="flex-1 rounded-lg bg-[#f8f8f8] p-4 text-sm font-normal">{comment}</div>
          </div>
          <div className="flex justify-end text-xs text-gray-500">Объявление № {id}</div>

          {userRequest === 'Нужен перевозчик' ? (
            <span className="pl-7 text-sm text-gray-500">Забрать из:</span>
          ) : (
            <span className="pl-7 text-sm text-gray-500">Выезжаю из:</span>
          )}
          <div className="mt-4 mb-2 flex flex-row items-stretch gap-4">
            <div className="relative flex h-[150px] flex-col items-center">
              <div className="relative flex h-full w-[10px] items-center justify-center">
                <Image
                  src="/images/vectormob.png"
                  width={6}
                  height={100}
                  alt="route vector"
                  className="absolute h-[150px] w-auto"
                />
                <div className="absolute -top-[10px] z-10 h-4 w-4 rounded-full border-3 border-[#065bff] bg-white" />
                <div className="absolute -bottom-[10px] z-10 h-4 w-4 rounded-full border-3 border-[#45c226] bg-white" />
              </div>
            </div>
            <div className="flex flex-1 flex-col justify-between">
              <div className="-mt-[14px] flex items-center">
                <Image
                  src={country_to_icon}
                  width={26}
                  height={13}
                  alt={from_country_name.substring(0, 3)}
                />
                <span className="pr-2 pl-1 text-sm text-gray-400">
                  {from_country_name.substring(0, 3).toUpperCase()}
                </span>
                <span className="text-base font-semibold">
                  {from_city_name} / {from_country_name}
                </span>
              </div>

              <div className="flex flex-col">
                <div className="flex items-center gap-4">
                  <span className="text-base">{formatted_transport}</span>
                  <Image
                    src={setMovingTypeIcon()}
                    width={15}
                    height={15}
                    alt="route vector"
                    className="h-[15px] w-[15px] object-contain"
                  />
                </div>
                <div className="my-2 h-[2px] w-[228px] bg-gray-200" />
                <div className="text-sm">Дата доставки: {formatDateTime(formatted_arrival)}</div>
              </div>

              <div className="-mb-[14px] flex flex-col">
                {userRequest === 'Нужен перевозчик' ? (
                  <div className="text-sm text-gray-500">Доставить в:</div>
                ) : (
                  <div className="text-sm text-gray-500">Прибываю в:</div>
                )}

                <div className="flex items-center">
                  <Image
                    src={country_to_icon}
                    width={26}
                    height={13}
                    alt={to_country_name.substring(0, 3)}
                  />
                  <span className="pr-2 pl-1 text-gray-400">
                    {to_country_name.substring(0, 3).toUpperCase()}
                  </span>
                  <span className="text-base font-semibold">
                    {to_city_name} / {to_country_name}
                  </span>
                </div>
              </div>
            </div>
          </div>
          {userRequest === 'Могу перевезти' && (
            <div className="mt-3 ml-7 text-sm text-gray-500">
              <span className="text-sm font-normal">Прибытие:</span>{' '}
              <span className="text-sm font-semibold">{formatDateTime(formatted_arrival)}</span>
            </div>
          )}
          <div className="mt-8">
            <Button
              text="Откликнуться"
              className="bg-orange hover:bg-orange/80 w-full cursor-pointer py-3 text-base font-semibold text-white transition-colors"
              onClick={handleLeadClick}
            />
          </div>
        </div>
      </div>

      <LeadPopup
        id={id}
        isOpen={isLeadPopupOpen}
        onClose={() => setIsLeadPopupOpen(false)}
        onSuccess={() => {
          setIsLeadPopupOpen(false)
        }}
      />
    </>
  )
}

export default SearchCard
