'use client';

import { useState } from 'react';
import Modal from '@/components/ui/Modal';
import { SortOption } from '@/features/search/types';
import { SearchHotelsResponse } from '@/services/search/types';
import DynamicCheckboxFilter from './filters/DynamicCheckboxFilter';
import { PriceRangeFilter } from './filters/PricingPerNightFilter';
import BudgetFilter from './filters/BudgetFilter';

interface DynamicFiltersState {
  priceRange?: PriceRangeFilter;
  freeCancellation?: boolean;
  [key: string]: string[] | PriceRangeFilter | boolean | undefined;
}

interface DynamicMobileFilterModalProps {
  isOpen: boolean;
  onClose: () => void;
  availableFilters: SearchHotelsResponse['availableFilters'];
  appliedFilters: DynamicFiltersState;
  sortBy: SortOption;
  onFilterChange: (filterKey: string, values: string[] | PriceRangeFilter | boolean | undefined) => void;
  onSortChange: (sort: SortOption) => void;
  onClearFilters: () => void;
}

// Map filter keys to user-friendly titles
const FILTER_TITLES: Record<string, string> = {
  freeCancellation: 'Free Cancellation',
  // LEIS-993 added these two filters to search-service for the travel-policy
  // "Default filters" setting. Without a title here the sidebar falls back to
  // the raw key, so a pre-applied filter rendered as a chip reading
  // "hotelsOnly" — the enum name, in the traveller's face.
  breakfast: 'Breakfast Included',
  hotelsOnly: 'Hotels Only',
  starRating: 'Star Rating',
  chains: 'Hotel Chains',
  amenities: 'Amenities',
  propertyType: 'Property Type',
  userRating: 'User Rating',
  mealOptions: 'Meal Options',
  locality: 'Locality',
  touristAttractions: 'Tourist Attractions',
  airports: 'Airports',
  roomViews: 'Room Views',
  roomAmenities: 'Room Amenities',
  houseRules: 'House Rules',
};

export default function DynamicMobileFilterModal({
  isOpen,
  onClose,
  availableFilters,
  appliedFilters,
  sortBy,
  onFilterChange,
  onSortChange,
  onClearFilters,
}: DynamicMobileFilterModalProps) {
  const [activeTab, setActiveTab] = useState<'sort' | 'filter'>('sort');

  const hasAppliedFilters = Object.values(appliedFilters).some(
    value => {
      if (!value) return false;
      return Array.isArray(value) ? value.length > 0 : true;
    }
  );

  // Helper function to get display value (name for chains, raw value otherwise)
  const getDisplayValue = (filterKey: string, value: string): string => {
    if (filterKey === 'chains' && availableFilters?.[filterKey]?.values) {
      const chainOption = availableFilters?.[filterKey]?.values?.find(
        (option) => option.code === value
      );
      return chainOption?.name || value;
    }
    if (filterKey === 'starRating') {
      return `${value} Star`;
    }
    return value;
  };

  const handleSortClick = (option: SortOption) => {
    onSortChange(option);
  };

  const handleFilterChange = (filterKey: string, values: string[] | PriceRangeFilter | boolean | undefined) => {
    onFilterChange(filterKey, values);
  };

  const handleClearFilters = () => {
    onClearFilters();
  };

  const sortOptions: { value: SortOption; label: string }[] = [
    { value: 'default', label: 'Popularity' },
    { value: 'price-low', label: 'Price (Low to High)' },
    { value: 'price-high', label: 'Price (High to Low)' },
  ];

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      size="fullscreen"
      scrollable={true}
      showCloseButton={false}
      className="mobile-filter-modal"
      closeButtonText='Close'
      footer={
        <>
          <button
            type="button"
            className="btn btn-secondary bgColor-second btn-sm border-0"
            onClick={onClose}
          >
            Close
          </button>
          <button
            type="button"
            className="btn btn-primary bgColor-first-same btn-sm border-0"
            onClick={onClose}
          >
            Apply Filters
          </button>
        </>
      }
    >
      {/* Custom Header with Tabs */}
      <div id='filterModal' className="modal-header-tabs rounded-top-3 mb-3 d-flex align-items-center justify-content-between border-bottom pb-2 px-3">
        <ul className="nav nav-pills" role="tablist">
          <li className="nav-item" role="presentation">
            <button
              className={`nav-link ${activeTab === 'sort' ? 'active' : ''}`}
              type="button"
              onClick={() => setActiveTab('sort')}
            >
              Sort
            </button>
          </li>
          <li className="nav-item" role="presentation">
            <button
              className={`nav-link ${activeTab === 'filter' ? 'active' : ''}`}
              type="button"
              onClick={() => setActiveTab('filter')}
            >
              Filter
            </button>
          </li>
        </ul>
        <button
          type="button"
          className="btn-close rounded-circle"
          onClick={onClose}
        />
      </div>

      {/* Tab Content */}
      <div className="tab-content px-3">
        {/* Sort Tab */}
        {activeTab === 'sort' && (
          <div className="tab-pane fade active show">
            <div className="sorting-filter filter-accordion">
              {sortOptions.map((option, index) => (
                <div key={option.value} className="form-check p-0 mb-1">
                  <label htmlFor={`sorting-filter-${index + 1}`} className="mb-0 small-line-height w-100">
                    <div className="row g-0 align-items-center">
                      <div className="col-1 d-flex justify-content-center">
                        <input
                          className="form-check-input ms-0 mt-0"
                          type="radio"
                          name="sortOption"
                          value={option.value}
                          id={`sorting-filter-${index + 1}`}
                          checked={sortBy === option.value}
                          onChange={() => handleSortClick(option.value)}
                        />
                      </div>
                      <div className="col-11 ps-2">
                        <small className="mb-0 fw-normal text-limit-1">{option.label}</small>
                      </div>
                    </div>
                  </label>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Filter Tab */}
        {activeTab === 'filter' && (
          <div className="tab-pane fade active show">
            {/* Applied Filters */}
            {hasAppliedFilters && (
              <div className="mb-3">
                {/* Header */}
                <div className="d-flex justify-content-between align-items-center mb-3">
                  <h6 className="mb-0 fw-bold" style={{ color: "#052c65" }}>Applied Filters</h6>
                  <button
                    type="button"
                    className="btn btn-link p-0 text-decoration-none fw-semibold font-14"
                    onClick={handleClearFilters}
                    style={{ color: '#f45d6b' }}
                  >
                    CLEAR
                  </button>
                </div>

                {/* Filter Tags */}
                <div className="d-flex flex-column gap-2 mb-3">
                  {appliedFilters.priceRange && (
                    <div
                      key="priceRange"
                      className="d-flex align-items-center justify-content-between p-2 px-3 rounded-3 border"
                      style={{
                        borderColor: '#f45d6b',
                        backgroundColor: '#f8f9fa'
                      }}
                    >
                      <span className="text-truncate font-14">
                        {`Price: $${appliedFilters.priceRange.from}-$${appliedFilters.priceRange.to}`}
                      </span>
                      <button
                        type="button"
                        className="btn-close"
                        style={{
                          fontSize: '10px',
                          width: '18px',
                          height: '18px',
                          opacity: 0.5,
                          flexShrink: 0,
                          marginLeft: '8px'
                        }}
                        onClick={() => handleFilterChange('priceRange', undefined)}
                        aria-label="Remove filter"
                      />
                    </div>
                  )}

                  {Object.entries(appliedFilters).map(([filterKey, value]) => {
                    if (filterKey === 'priceRange') return null;
                    if (value === true) {
                      return (
                        <div
                          key={filterKey}
                          className="d-flex align-items-center justify-content-between p-2 px-3 rounded-3 border"
                          style={{ borderColor: '#f45d6b', backgroundColor: '#f8f9fa' }}
                        >
                          <span className="text-truncate font-14">{FILTER_TITLES[filterKey] || filterKey}</span>
                          <button
                            type="button"
                            className="btn-close"
                            style={{ fontSize: '10px', width: '18px', height: '18px', opacity: 0.5, flexShrink: 0, marginLeft: '8px' }}
                            onClick={() => handleFilterChange(filterKey, undefined)}
                            aria-label="Remove filter"
                          />
                        </div>
                      );
                    }
                    if (!value || !Array.isArray(value) || value.length === 0) return null;
                    const values = value;
                    return values.map((val) => (
                      <div
                        key={`${filterKey}-${val}`}
                        className="d-flex align-items-center justify-content-between p-2 px-3 rounded-3 border"
                        style={{
                          borderColor: '#f45d6b',
                          backgroundColor: '#f8f9fa'
                        }}
                      >
                        <span className="text-truncate font-14">
                          {getDisplayValue(filterKey, val)}
                        </span>
                        <button
                          type="button"
                          className="btn-close"
                          style={{
                            fontSize: '10px',
                            width: '18px',
                            height: '18px',
                            opacity: 0.5,
                            flexShrink: 0,
                            marginLeft: '8px'
                          }}
                          onClick={() => {
                            const updatedValues = values.filter(v => v !== val);
                            handleFilterChange(filterKey, updatedValues);
                          }}
                          aria-label="Remove filter"
                        />
                      </div>
                    ));
                  })}
                </div>
              </div>
            )}

            <div className="mobile-filter">
              {!availableFilters && (
                <p className="text-center text-muted">Loading filters...</p>
              )}

              <BudgetFilter
                min={appliedFilters?.priceRange?.from}
                max={appliedFilters?.priceRange?.to}
                onChange={(min, max) => handleFilterChange('priceRange', { from: min, to: max })}
              />

              {availableFilters && Object.entries(availableFilters).map(([filterKey, filterConfig]) => {
                if (!filterConfig) return null;

                if (filterConfig.type === 'toggle') {
                  return (
                    <div className="accordion border-top filter-accordion" key={filterKey} id={`${filterKey}FilterAccordion`}>
                      <div className="accordion-item bg-transparent border-0 mb-3">
                        <div className="accordion-header">
                          <button
                            className="accordion-button shadow-none bg-transparent px-0 fs-6 fw-semibold collapsed"
                            type="button"
                            data-bs-toggle="collapse"
                            data-bs-target={`#collapse${filterKey}`}
                          >
                            {FILTER_TITLES[filterKey] || filterKey}
                          </button>
                        </div>
                        <div id={`collapse${filterKey}`} className="collapse" data-bs-parent={`#${filterKey}FilterAccordion`}>
                          <div className="card border-0 bg-transparent">
                            <div className="card-body p-0">
                              <div className="form-check p-0 mb-3">
                                <label htmlFor={`toggle-${filterKey}`} className="mb-0 small-line-height w-100">
                                  <div className="row g-0 align-items-center">
                                    <div className="col-xxl-1 col-xl-1 col-lg-1 col-md-1 col-1 d-flex justify-content-center">
                                      <input
                                        className="form-check-input ms-0 mt-0"
                                        type="checkbox"
                                        id={`toggle-${filterKey}`}
                                        checked={appliedFilters[filterKey] === true}
                                        onChange={(e) => handleFilterChange(filterKey, e.target.checked)}
                                      />
                                    </div>
                                    <div className="col-xxl-9 col-xl-9 col-lg-9 col-md-9 col-9 ps-2">
                                      <label htmlFor={`toggle-${filterKey}`} className="mb-0 fw-normal text-limit-1">
                                        {FILTER_TITLES[filterKey] || filterKey}
                                      </label>
                                    </div>
                                  </div>
                                </label>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                }

                if (!filterConfig || filterConfig.type !== 'checkbox' || !filterConfig.values || filterConfig?.values?.length === 0) return null;

                const title = FILTER_TITLES[filterKey] || filterKey;
                const selectedValues = Array.isArray(appliedFilters[filterKey]) ? appliedFilters[filterKey] : [];

                return (
                  <DynamicCheckboxFilter
                    key={filterKey}
                    filterKey={filterKey}
                    title={title}
                    values={filterConfig.values}
                    selectedValues={selectedValues}
                    onChange={handleFilterChange}
                    defaultOpen={false}
                  />
                );
              })}

              {/* Back to Top Button */}
              {availableFilters && Object.keys(availableFilters).length > 0 && (
                <button
                  type="button"
                  className="text-center bgColor-first color-text-white fw-semibold rounded-3 border outline-none shadow-sm d-flex justify-content-center align-items-center font-14 w-100 p-2 m-0 mt-3"
                  onClick={() => {
                    const modalContent = document.querySelector('.modal-body');
                    if (modalContent) {
                      modalContent.scrollTo({ top: 0, behavior: 'smooth' });
                    }
                  }}
                >
                  BACK TO TOP
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}
