import React, {
  Dispatch,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react'
import { FastboatRoute, SingleRoute } from '@/lib/types/fastboat'
import { hideCartButton } from '@/lib/features/cart/floatingButtonSlice'
import { Search, SearchX } from 'lucide-react'
import { useAppDispatch, useAppSelector } from '@/lib/redux-hooks'
import { SearchParams } from './types'
import RouteListLoadingSkeleton from '../skeletons/RouteListLoadingSkeleton'

interface SelectRouteProps {
  selectedDeparture: SingleRoute
  selectedArrival: SingleRoute
  errors: Partial<SearchParams>
  setSelectedDeparture: Dispatch<SetStateAction<SingleRoute>>
  setSelectedArrival: Dispatch<SetStateAction<SingleRoute>>
}

async function filterUniqueAreas(fastboatRoutes: FastboatRoute[]) {
  const key: { departures: Set<string>; arrivals: Set<string> } = {
    departures: new Set<string>(),
    arrivals: new Set<string>(),
  }
  const area: {
    departures: SingleRoute[]
    arrivals: SingleRoute[]
  } = {
    departures: [],
    arrivals: [],
  }

  for (const route of fastboatRoutes) {
    const departureKey = `${route.departure_island?.toLowerCase()}|${route.departure_harbor?.toLowerCase()}`
    const arrivalKey = `${route.arrival_island?.toLowerCase()}|${route.arrival_harbor?.toLowerCase()}`

    if (!key.departures.has(departureKey)) {
      key.departures.add(departureKey)

      area.departures.push({
        island: route.departure_island,
        harbor: route.departure_harbor,
        type: route.type,
      })
    }

    if (!key.arrivals.has(arrivalKey)) {
      key.arrivals.add(arrivalKey)

      area.arrivals.push({
        island: route.arrival_island,
        harbor: route.arrival_harbor,
        type: route.type,
      })
    }
  }

  return area
}

const SelectRoute: React.FC<SelectRouteProps> = (props) => {
  const merchant = useAppSelector((state) => state.merchant)
  const dispatch = useAppDispatch()
  const [isLoading, setIsLoading] = useState(true)

  const departureDropdownRef = useRef(null)
  const departureInputRef = useRef(null)
  const arrivalDropdownRef = useRef(null)
  const arrivalInputRef = useRef(null)
  const [searchDeparture, setSearchDeparture] = useState('')
  const [searchArrival, setSearchArrival] = useState('')
  const [showDepartureDropdown, setShowDepartureDropdown] = useState(false)
  const [showArrivalDropdown, setShowArrivalDropdown] = useState(false)
  const [departures, setDepartures] = useState<Array<SingleRoute>>()
  const [arrivals, setArrivals] = useState<Array<SingleRoute>>()
  const [filteredDepartures, setFilteredDepartures] =
    useState<Array<SingleRoute>>()
  const [filteredArrivals, setFilteredArrivals] = useState<Array<SingleRoute>>()

  function handleSearchDeparture(e: React.ChangeEvent<HTMLInputElement>) {
    setSearchDeparture(e.target.value)

    setFilteredDepartures(
      departures?.filter(
        (departure) =>
          departure.harbor
            .toLowerCase()
            .includes(e.target.value.toLowerCase()) ||
          departure.island.toLowerCase().includes(e.target.value.toLowerCase()),
      ),
    )
  }

  function handleSearchArrival(e: React.ChangeEvent<HTMLInputElement>) {
    setSearchArrival(e.target.value)

    setFilteredArrivals(
      arrivals?.filter(
        (arrival) =>
          arrival.harbor.toLowerCase().includes(e.target.value.toLowerCase()) ||
          arrival.island.toLowerCase().includes(e.target.value.toLowerCase()),
      ),
    )
  }

  // Filter Unique Routes
  useEffect(() => {
    if (merchant?.id) {
      setIsLoading(true)

      fetch(`/api/fastboat-routes?merchant_id=${merchant.id}`)
        .then((res) => res.json())
        .then((data) => {
          filterUniqueAreas(data).then((area) => {
            setIsLoading(false)

            setDepartures(area.departures)
            setArrivals(area.arrivals)

            // handle the initial state of the filtered areas
            setFilteredDepartures(area.departures)
            setFilteredArrivals(area.arrivals)
          })
        })
        .catch((_) => {
          setIsLoading(false)
        })
    }
  }, [merchant])

  // Close modal when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        departureDropdownRef.current &&
        !departureDropdownRef.current.contains(event.target)
      ) {
        setShowDepartureDropdown(false)
      }

      if (
        arrivalDropdownRef.current &&
        !arrivalDropdownRef.current.contains(event.target)
      ) {
        setShowArrivalDropdown(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  function handleSelectDeparture(departure: SingleRoute) {
    props.setSelectedDeparture(departure)

    // Reset the search input
    setFilteredDepartures(departures)

    // Reset arrival if the departure is same
    if (
      props.selectedArrival &&
      props.selectedArrival.harbor === departure.harbor
    ) {
      props.setSelectedArrival(null)
    }

    setShowDepartureDropdown(false)
  }

  function handleSelectArrival(arrival: SingleRoute) {
    props.setSelectedArrival(arrival)

    // Reset the search input
    setFilteredArrivals(arrivals)

    // Reset departure if the arrival is same
    if (
      props.selectedDeparture &&
      props.selectedDeparture.harbor === arrival.harbor
    ) {
      props.setSelectedDeparture(null)
    }

    setShowArrivalDropdown(false)
  }

  function handleOpenArrivalDropdown() {
    setShowArrivalDropdown(true)
    setShowDepartureDropdown(false)
    arrivalInputRef.current.focus()
    dispatch(hideCartButton())
  }

  function handleOpenDepartureDropdown() {
    setShowDepartureDropdown(true)
    setShowArrivalDropdown(false)
    departureInputRef.current.focus()
    dispatch(hideCartButton())
  }

  return (
    <div className="gap-6 mt-2 lg:mt-0 w-full md:flex-row flex-col flex items-start col-span-12 lg:col-span-5">
      {/* Depart From */}
      <div className="relative w-full" ref={departureDropdownRef}>
        <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1">
          Depart From
        </label>
        <input
          type="text"
          readOnly
          value={props.selectedDeparture?.harbor || ''}
          placeholder="Depart From"
          onFocus={handleOpenDepartureDropdown}
          onClick={handleOpenDepartureDropdown}
          required
          className="flex items-center space-x-1 border border-gray-200 hover:bg-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-800 focus:border-transparent transition-colors duration-200 lg:mr-4 h-10 sm:h-12 w-full focus:outline-none text-sm sm:text-base cursor-pointer"
        />
        {props.errors?.departure && (
          <span className="text-sm absolute text-red-500">
            {props.errors?.departure}
          </span>
        )}

        <div
          className={`absolute z-20 transition-all duration-100 w-full ease-out top-20 ${showDepartureDropdown ? 'opacity-100' : 'opacity-0 invisible'}`}
        >
          <div className="bg-white rounded-xl shadow-xl w-full max-h-[32rem] overflow-hidden">
            {/* Modal Header */}
            <div className="p-4 border-b border-gray-200">
              {/* Search Input */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search Departure..."
                  value={searchDeparture}
                  ref={departureInputRef}
                  onChange={handleSearchDeparture}
                  className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring focus:ring-blue-800 focus:border-blue-800 hover:border-blue-800 text-sm"
                />
              </div>
            </div>

            {/* Departure List */}
            <div className="overflow-y-auto max-h-96">
              {isLoading ? (
                <RouteListLoadingSkeleton />
              ) : filteredDepartures?.length ? (
                filteredDepartures.map((departure, index) => (
                  <button
                    key={index}
                    type="button"
                    onClick={() => handleSelectDeparture(departure)}
                    className={`w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 focus:outline-none focus:bg-blue-50 ${props.selectedDeparture?.harbor === departure.harbor ? 'bg-blue-50' : ''} ${index !== departures.length - 1 ? 'border-b border-gray-100' : ''}`}
                  >
                    <div className="flex flex-col items-start">
                      <span className="text-sm font-medium text-gray-900">
                        {departure.harbor}
                      </span>
                      <span className="text-sm text-gray-500">
                        {departure.island}
                      </span>
                    </div>
                    {props.selectedDeparture?.harbor === departure.harbor && (
                      <div className="w-2 h-2 rounded-full bg-blue-500" />
                    )}
                  </button>
                ))
              ) : (
                <NoResultsFound />
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Arrive At */}
      <div className="relative w-full" ref={arrivalDropdownRef}>
        <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1">
          Arrive At
        </label>
        <input
          type="text"
          value={props.selectedArrival?.harbor || ''}
          placeholder="Arrive At"
          readOnly
          required
          onFocus={handleOpenArrivalDropdown}
          onClick={handleOpenArrivalDropdown}
          className="flex items-center space-x-1 border border-gray-200 hover:bg-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-800 focus:border-transparent transition-colors duration-200 lg:mr-4 h-10 sm:h-12 w-full focus:outline-none text-sm sm:text-base cursor-pointer"
        />
        {props.errors?.arrival && (
          <span className="text-sm absolute text-red-500">
            {props.errors?.arrival}
          </span>
        )}

        <div
          className={`absolute z-20 transition-all duration-200 w-full ease-out ${showArrivalDropdown ? 'opacity-100' : 'opacity-0 invisible'}`}
        >
          <div className="bg-white rounded-xl shadow-xl w-full max-h-[32rem] overflow-hidden">
            {/* Modal Header */}
            <div className="p-4 border-b border-gray-200">
              {/* Search Input */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search Arrival..."
                  ref={arrivalInputRef}
                  value={searchArrival}
                  onChange={handleSearchArrival}
                  className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring focus:ring-blue-800 focus:border-blue-800 hover:border-blue-800 text-sm"
                />
              </div>
            </div>

            {/* Arrival List */}
            <div className="overflow-y-auto max-h-96">
              {isLoading ? (
                <RouteListLoadingSkeleton />
              ) : filteredArrivals?.length ? (
                filteredArrivals.map((arrival, index) => (
                  <button
                    key={index}
                    type="button"
                    onClick={() => handleSelectArrival(arrival)}
                    className={`w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50 focus:outline-none focus:bg-blue-50 ${props.selectedArrival?.harbor === arrival.harbor ? 'bg-blue-50' : ''} ${index !== arrivals.length - 1 ? 'border-b border-gray-100' : ''}`}
                  >
                    <div className="flex flex-col items-start">
                      <span className="text-sm font-medium text-gray-900">
                        {arrival.harbor}
                      </span>
                      <span className="text-sm text-gray-500">
                        {arrival.island}
                      </span>
                    </div>
                    {props.selectedArrival?.harbor === arrival.harbor && (
                      <div className="w-2 h-2 rounded-full bg-blue-500" />
                    )}
                  </button>
                ))
              ) : (
                <NoResultsFound />
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

function NoResultsFound() {
  return (
    <div className="flex flex-col items-center justify-center py-12 px-4 space-y-4 ">
      <div className="bg-gray-100 rounded-full p-3">
        <SearchX className="w-8 h-8 text-gray-400" />
      </div>
      <div className="text-center space-y-1">
        <p className="text-gray-800 font-medium">No routes found</p>
        <p className="text-gray-500 text-sm">
          Try searching with a different keyword
        </p>
      </div>
    </div>
  )
}

export default SelectRoute
