'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import DynamicCheckboxFilter from '../filters/DynamicCheckboxFilter';
import { PriceRangeFilter } from '../filters/PricingPerNightFilter';
import { SearchHotelsResponse } from '@/services/search/types';
import BudgetFilter from '../filters/BudgetFilter';
import LazySidebarMapPreview from '../LazySidebarMapPreview';

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

interface DynamicFilterSidebarProps {
  availableFilters: SearchHotelsResponse['availableFilters'];
  appliedFilters: DynamicFiltersState;
  onFilterChange: (filterKey: string, values: string[] | PriceRangeFilter | boolean | undefined) => void;
  onSearch?: (query: string) => void;
  onClearFilters: () => void;
  onExploreMap?: () => void;
  mapCenter?: { lat: number; lng: number };
  isLoading: boolean;
  isMapLoading: boolean;
}

// 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',
  topLocations: 'Top Locations',
};

// Skeleton component for loading state
export const FilterSkeleton = () => {
  const widths = ['75%', '65%', '80%'];

  return (
    <div className="accordion border-top filter-accordion">
      <div className="accordion-item bg-transparent border-0 mb-3">
        <div className="accordion-header">
          <div className="py-2">
            <div className="skeleton-box" style={{ width: '120px', height: '20px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
          </div>
        </div>
        <div className="card border-0 bg-transparent mt-2">
          <div className="card-body p-0">
            {widths.map((width, idx) => (
              <div className="form-check p-0 mb-3" key={idx}>
                <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">
                    <div className="skeleton-box" style={{ width: '16px', height: '16px', backgroundColor: '#dee2e6', borderRadius: '2px' }}></div>
                  </div>
                  <div className="col-xxl-9 col-xl-9 col-lg-9 col-md-9 col-9 ps-2">
                    <div className="skeleton-box" style={{ width: width, height: '14px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
                  </div>
                  <div className="col-xxl-2 col-xl-2 col-lg-2 col-md-2 col-2 d-flex justify-content-end">
                    <div className="skeleton-box" style={{ width: '30px', height: '14px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default function DynamicFilterSidebarV3({
  availableFilters,
  appliedFilters,
  onFilterChange,
  onClearFilters,
  onExploreMap,
  mapCenter = { lat: 25.2048, lng: 55.2708 }, // Default: Dubai
  isLoading,
  isMapLoading
}: DynamicFilterSidebarProps) {
  const isV3 = process.env.NEXT_PUBLIC_DESIGN_VERSION === 'v3';
  
  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 === 'topLocations' && 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 handleFilterChange = useCallback((filterKey: string, values: string[] | PriceRangeFilter | boolean | undefined) => {
    onFilterChange(filterKey, values);
  }, [onFilterChange]);

  const mainPanelRef = useRef<HTMLDivElement>(null);
  const [isSidebarVisible, setIsSidebarVisible] = useState(true);

  useEffect(() => {
    const el = mainPanelRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => setIsSidebarVisible(entry.isIntersecting),
      { threshold: 0.35 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  if (!isLoading && !availableFilters) return null;

  // Free Cancellation filter (if returned by API)
  const freeCancelFilter = availableFilters?.freeCancellation;
  const selectedFreeCancel = Array.isArray(appliedFilters.freeCancellation) ? appliedFilters.freeCancellation : [];

  return (
    <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-12 col-12 filterDetails mb-3 mb-lg-0">
      <div ref={mainPanelRef} className="bgColor-white shadow-sm rounded-3 p-2 p-md-3 mb-0">
        {/* Map View Block */}
        {isMapLoading ? <div className="map-view-block position-relative overflow-hidden mb-3" style={{ height: '160px', borderRadius: 12, backgroundColor: '#e9ecef' }}>
          <div className="placeholder-glow w-100 h-100">
            <span className="placeholder w-100 h-100" style={{ backgroundColor: '#dee2e6' }}></span>
          </div>
        </div> : <div className="map-view-block position-relative mb-3">
          <LazySidebarMapPreview center={mapCenter} />
          <button className="view-map-btn py-1 px-3 px-xl-4" onClick={onExploreMap} type="button">
            EXPLORE ON MAP
            <svg className="ms-1 fill-first iconSize-15" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M8.00004 7.66667C7.55801 7.66667 7.13409 7.49107 6.82153 7.17851C6.50897 6.86595 6.33337 6.44203 6.33337 6C6.33337 5.55797 6.50897 5.13405 6.82153 4.82149C7.13409 4.50893 7.55801 4.33333 8.00004 4.33333C8.44207 4.33333 8.86599 4.50893 9.17855 4.82149C9.49111 5.13405 9.66671 5.55797 9.66671 6C9.66671 6.21887 9.6236 6.4356 9.53984 6.6378C9.45608 6.84001 9.33332 7.02375 9.17855 7.17851C9.02379 7.33327 8.84006 7.45604 8.63785 7.5398C8.43564 7.62356 8.21891 7.66667 8.00004 7.66667ZM8.00004 1.33333C6.76236 1.33333 5.57538 1.825 4.70021 2.70017C3.82504 3.57534 3.33337 4.76232 3.33337 6C3.33337 9.5 8.00004 14.6667 8.00004 14.6667C8.00004 14.6667 12.6667 9.5 12.6667 6C12.6667 4.76232 12.175 3.57534 11.2999 2.70017C10.4247 1.825 9.23772 1.33333 8.00004 1.33333Z" />
            </svg>
          </button>
        </div>}

        {/* Search Filter */}
        {/* <div className="d-flex align-items-center gap-2 bgColor-white border rounded-3 p-2 mb-md-3">
          <svg className="iconSize-20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <g clipPath="url(#clip0_6000_138)">
              <path d="M8.04937 16.0923C9.837 16.0923 11.5735 15.4959 12.9838 14.3974L18.3044 19.7181C18.7019 20.1019 19.3353 20.0909 19.7191 19.6934C20.0936 19.3057 20.0936 18.691 19.7191 18.3034L14.3985 12.9827C17.1242 9.47394 16.4895 4.41986 12.9807 1.6941C9.47194 -1.03165 4.41791 -0.396918 1.69215 3.11187C-1.03361 6.62065 -0.398871 11.6747 3.10991 14.4005C4.52252 15.4979 6.26057 16.0932 8.04937 16.0923ZM3.77429 3.77316C6.13538 1.41203 9.96346 1.41199 12.3246 3.77308C14.6857 6.13417 14.6858 9.96225 12.3247 12.3234C9.96359 14.6845 6.13551 14.6846 3.77438 12.3235C3.77433 12.3234 3.77433 12.3234 3.77429 12.3234C1.4132 9.97949 1.39929 6.16537 3.74317 3.80428C3.75353 3.79388 3.76389 3.78352 3.77429 3.77316Z" fill="#B6B6B6" />
            </g>
            <defs>
              <clipPath id="clip0_6000_138">
                <rect width="20" height="20" fill="white" />
              </clipPath>
            </defs>
          </svg>
          <input
            type="text"
            className="w-100 no-bg-btn"
            id="search-filter"
            placeholder="Search"
            onChange={(e) => handleSearch(e.target.value)}
            autoComplete="off"
          />
        </div> */}

        {/* 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={onClearFilters}
                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={() => {
                      onFilterChange('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={() => onFilterChange(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);
                        onFilterChange(filterKey, updatedValues);
                      }}
                      aria-label="Remove filter"
                    />
                  </div>
                ));
              })}
            </div>
          </div>
        )}

        {/* Dynamic Filters */}
        <div className="web-filter d-lg-block d-none">

          {/* <PricingPerNightFilter
            selected={appliedFilters.priceRange}
            onChange={(priceRange) => handleFilterChange('priceRange', priceRange)}
            defaultOpen={true}
          /> */}

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

          {availableFilters && Object.entries(availableFilters).sort(([keyA], [keyB]) => {
              if (keyA === 'topLocations') return -1;
              if (keyB === 'topLocations') return 1;
              return 0;
            }).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"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target={`#collapse${filterKey}`}
                      >
                        {FILTER_TITLES[filterKey] || filterKey}
                      </button>
                    </div>
                    <div id={`collapse${filterKey}`} className="collapse show" 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.type === 'tile') {
              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"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target={`#collapse${filterKey}`}
                      >
                        {FILTER_TITLES[filterKey] || filterKey}
                      </button>
                    </div>
                    <div id={`collapse${filterKey}`} className="suggestion-card-check collapse show" data-bs-parent={`#${filterKey}FilterAccordion`}>
                      <div className="card border-0 shadow-sm bg-transparent">
                        <div className="card-body p-0">
                          <div className="row g-2">
                            {
                              filterConfig.values?.map((option) => {
                                const isChecked = Array.isArray(appliedFilters[filterKey]) && appliedFilters[filterKey].includes(option.code as string);
                                return (
                                  <div className="col-4" key={option.code}>
                                    <div className="form-check h-100 p-0 mb-3">
                                      <input className="form-check-input d-none" type="checkbox"
                                        value={option.code}
                                        id={`${filterKey}-${option.code}`}
                                        checked={isChecked}
                                        onChange={() => {
                                          const updatedValues = isChecked
                                            ? (Array.isArray(appliedFilters[filterKey]) ? appliedFilters[filterKey].filter((v): v is string => typeof v === 'string' && v !== option.code) : [])
                                            : [...(Array.isArray(appliedFilters[filterKey]) ? appliedFilters[filterKey].filter((v): v is string => typeof v === 'string') : []), option.code];
                                          handleFilterChange(filterKey, updatedValues as string[]);
                                        }} />
                                      <label htmlFor={`${filterKey}-${option.code}`} className="suggestion-check-label small-line-height w-100 h-100 mb-0">
                                        <img
                                          className="w-100 h-48 rounded-2 img-cover"
                                          src={option.image || 'assets/img/hotels/hotel-room-1.webp'}
                                          alt={option.name}
                                        />
                                        <small className="d-block text-xs fw-semibold pt-1 mb-1">
                                          {option.name}
                                        </small>
                                      </label>
                                    </div>
                                  </div>
                                );
                              })
                            }
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              );
            }

            if (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] : [];
            const mappedValues = filterConfig.values.map(v => ({
              ...v,
              name: FILTER_TITLES[v.name] || v.name,
            }));

            return (
              <DynamicCheckboxFilter
                key={filterKey}
                filterKey={filterKey}
                title={title}
                values={mappedValues}
                selectedValues={selectedValues}
                onChange={handleFilterChange}
                defaultOpen={true}
              />
            );
          })}

          {isLoading && !availableFilters && (
            <>
              <FilterSkeleton />
              <FilterSkeleton />
              <FilterSkeleton />
              <FilterSkeleton />
              <FilterSkeleton />
            </>
          )}

          {/* Back to Top Button */}
          <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"
            id="backToTopButton"
            onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
          >
            BACK TO TOP
          </button>
        </div>
      </div>

      {/* Sticky mini filter — visible on desktop only after the main panel scrolls out of view */}
      {!isSidebarVisible && (
        <div
          className="d-lg-block d-none"
          style={{ position: 'sticky', top: isV3 ? 80 : 210, zIndex: 99, paddingTop: '12px' }}
        >
          <div className="bgColor-white shadow-sm rounded-3 p-2 p-md-3">
            {/* Map section */}
            {isMapLoading ? (
              <div
                className="map-view-block position-relative overflow-hidden mb-3"
                style={{ height: '160px', borderRadius: 12, backgroundColor: '#e9ecef' }}
              >
                <div className="placeholder-glow w-100 h-100">
                  <span className="placeholder w-100 h-100" style={{ backgroundColor: '#dee2e6' }} />
                </div>
              </div>
            ) : (
              <div className="map-view-block position-relative mb-3">
                <LazySidebarMapPreview center={mapCenter} />
                <button className="view-map-btn py-1 px-3 px-xl-4" onClick={onExploreMap} type="button">
                  EXPLORE ON MAP
                  <svg className="ms-1 fill-first iconSize-15" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8.00004 7.66667C7.55801 7.66667 7.13409 7.49107 6.82153 7.17851C6.50897 6.86595 6.33337 6.44203 6.33337 6C6.33337 5.55797 6.50897 5.13405 6.82153 4.82149C7.13409 4.50893 7.55801 4.33333 8.00004 4.33333C8.44207 4.33333 8.86599 4.50893 9.17855 4.82149C9.49111 5.13405 9.66671 5.55797 9.66671 6C9.66671 6.21887 9.6236 6.4356 9.53984 6.6378C9.45608 6.84001 9.33332 7.02375 9.17855 7.17851C9.02379 7.33327 8.84006 7.45604 8.63785 7.5398C8.43564 7.62356 8.21891 7.66667 8.00004 7.66667ZM8.00004 1.33333C6.76236 1.33333 5.57538 1.825 4.70021 2.70017C3.82504 3.57534 3.33337 4.76232 3.33337 6C3.33337 9.5 8.00004 14.6667 8.00004 14.6667C8.00004 14.6667 12.6667 9.5 12.6667 6C12.6667 4.76232 12.175 3.57534 11.2999 2.70017C10.4247 1.825 9.23772 1.33333 8.00004 1.33333Z" />
                  </svg>
                </button>
              </div>
            )}

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

            {/* Free Cancellation filter (only if API returns it) */}
            {freeCancelFilter && freeCancelFilter.type === 'toggle' && (
              <div className="accordion border-top filter-accordion" id="freeCancellationFilterAccordionSticky">
                <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"
                      type="button"
                      data-bs-toggle="collapse"
                      data-bs-target="#collapsefreeCancellationSticky"
                    >
                      {FILTER_TITLES['freeCancellation'] || 'Free Cancellation'}
                    </button>
                  </div>
                  <div id="collapsefreeCancellationSticky" className="collapse show" data-bs-parent="#freeCancellationFilterAccordionSticky">
                    <div className="card border-0 bg-transparent">
                      <div className="card-body p-0">
                        <div className="form-check p-0 mb-3">
                          <label htmlFor="toggle-freeCancellation-sticky" 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-freeCancellation-sticky"
                                  checked={appliedFilters.freeCancellation === true}
                                  onChange={(e) => handleFilterChange('freeCancellation', 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-freeCancellation-sticky" className="mb-0 fw-normal text-limit-1">
                                  {FILTER_TITLES['freeCancellation'] || 'Free Cancellation'}
                                </label>
                              </div>
                            </div>
                          </label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
            {freeCancelFilter && freeCancelFilter.type === 'checkbox' && (freeCancelFilter.values?.length ?? 0) > 0 && (
              <DynamicCheckboxFilter
                filterKey="freeCancellation"
                title={FILTER_TITLES['freeCancellation'] || 'Free Cancellation'}
                values={freeCancelFilter.values ?? []}
                selectedValues={selectedFreeCancel}
                onChange={handleFilterChange}
                defaultOpen
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
