import { BookingPackageItem } from '@qite/tide-client';
import React, { useContext } from 'react';
import { getTranslations } from '../../shared/utils/localization-util';
import SettingsContext from '../settings-context';
import { differenceInCalendarDays } from 'date-fns';
import { isEmpty } from 'lodash';

interface ListViewProps {
  searchResults: BookingPackageItem[];
  onSelect?: (selectedItem: BookingPackageItem) => void;
}

const ListView: React.FC<ListViewProps> = ({ searchResults, onSelect }) => {
  const { language, customTranslations } = useContext(SettingsContext);
  const translations = getTranslations(language, customTranslations);

  const formatDate = (dateString: string) => {
    return new Intl.DateTimeFormat(language).format(new Date(dateString));
  };

  const handleOptionChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedDate = event.target.value;
    const selectedItem = searchResults.find((item) => item.fromDate === selectedDate);
    if (selectedItem && onSelect) {
      onSelect(selectedItem);
    }
  };

  const getNightsAndDays = (result: BookingPackageItem) => {
    const nights = differenceInCalendarDays(new Date(result.toDate), new Date(result.fromDate));
    return `${nights} ${translations.PRODUCT.NIGHTS}, ${nights + 1} ${translations.PRODUCT.DAYS}`;
  };

  const getDayLongFormat = (dateString: string) => {
    const day = new Date(dateString).toLocaleDateString(language, { weekday: 'long' });
    return day.charAt(0).toUpperCase() + day.slice(1);
  };

  return (
    <div className="dropdown">
      <select name="selectDate" id="selectDate" onChange={handleOptionChange}>
        {!isEmpty(searchResults) &&
          searchResults.map((result, index) => (
            <option key={index} value={result.fromDate}>
              {getDayLongFormat(result.fromDate)} {formatDate(result.fromDate)} - {getDayLongFormat(result.toDate)} {formatDate(result.toDate)} ({' '}
              {getNightsAndDays(result)} ) - {result.price.toFixed(2)} {result.currencyCode}
            </option>
          ))}
      </select>
    </div>
  );
};

export default ListView;
