'use client'

import React, { useState } from 'react'
import TextInput from './ui/TextInput'
import Link from 'next/link'

export default function AddressSelector() {
  const [fromAddress, setFromAddress] = useState('')
  const [toAddress, setToAddress] = useState('')

  const formatAddress = (address: string) => {
    return address
      .toLowerCase()
      .trim()
      .replace(/[^a-zа-я0-9\s-]/gi, '')
      .replace(/\s+/g, '-')
  }

  const getSearchUrl = (category: 'mover' | 'customer') => {
    if (!fromAddress || !toAddress) return `/search/${category}`

    const from = formatAddress(fromAddress)
    const to = formatAddress(toAddress)
    return `/search/${category}/${from}-${to}`
  }

  return (
    <div className="my-2 w-full rounded-xl bg-white p-4 shadow-lg sm:my-4 sm:p-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:gap-3">
        <div className="w-full min-w-0 sm:flex-[3] sm:px-1">
          <TextInput
            placeholder="Минск, Беларусь"
            tooltip="Укажите пункт (Город/Страна), откуда необходимо забрать посылку."
            label="Забрать посылку из"
            value={fromAddress}
            handleChange={e => setFromAddress(e.target.value)}
            name="fromAddress"
            style="main"
          />
        </div>
        <div className="w-full min-w-0 sm:flex-[3] sm:px-1">
          <TextInput
            placeholder="Москва, Россия"
            label="Доставить посылку в"
            tooltip="Укажите пункт (Город/Страна), куда необходимо доставить посылку."
            value={toAddress}
            handleChange={e => setToAddress(e.target.value)}
            name="toAddress"
            style="main"
          />
        </div>
        <Link
          href={getSearchUrl('mover')}
          className="bg-orange hover:bg-orange/80 w-full rounded-2xl p-4 text-center whitespace-nowrap text-white sm:w-auto sm:flex-1"
        >
          Найти перевозчика
        </Link>
        <Link
          href={getSearchUrl('customer')}
          className="w-full rounded-2xl bg-gray-100 p-4 text-center whitespace-nowrap text-gray-800 hover:bg-gray-200 sm:w-auto sm:flex-1"
        >
          Найти посылку
        </Link>
      </div>
    </div>
  )
}
