'use client';

import { useCallback } from 'react';
import DynamicCheckboxFilter from '@/components/search/filters/DynamicCheckboxFilter';
import BudgetFilter from '@/components/search/filters/BudgetFilter';
import { PriceRangeFilter } from '@/components/search/filters/PricingPerNightFilter';
import { AvailableFilters } from '@/services/search/types';
import { FilterSkeleton } from '../DynamicFilterSidebar';

export type MapFilterValue = string[] | PriceRangeFilter | undefined;
export type MapFiltersState = Record<string, MapFilterValue>;

const FILTER_TITLES: Record<string, string> = {
  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',
};

interface MapExploreFilterPanelProps {
  availableFilters?: AvailableFilters;
  appliedFilters: MapFiltersState;
  onFilterChange: (filterKey: string, values: MapFilterValue) => void;
  onClearFilters: () => void;
  isLoadingHotels: boolean;
  /** When provided a close (×) button is shown in the header — used in the mobile overlay. */
  onClose?: () => void;
  /** Stretch the panel to fill its container width instead of the fixed 280 px (used in mobile overlay). */
  fullWidth?: boolean;
}

export default function MapExploreFilterPanel({
  availableFilters,
  appliedFilters,
  onFilterChange,
  onClearFilters,
  isLoadingHotels,
  onClose,
  fullWidth = false,
}: MapExploreFilterPanelProps) {
  const hasAppliedFilters = Object.values(appliedFilters).some((value) => {
    if (!value) return false;
    return Array.isArray(value) ? value.length > 0 : true;
  });

  const getDisplayValue = (filterKey: string, value: string): string => {
    if (filterKey === 'chains' && availableFilters?.[filterKey]) {
      const chainOption = availableFilters?.[filterKey]?.values?.find(
        (o) => o.code === value
      );
      return chainOption?.name || value;
    }
    if (filterKey === 'amenities' && availableFilters?.[filterKey]) {
      const amenityOption = availableFilters?.[filterKey]?.values?.find(
        (o) => o.code === value
      );
      return amenityOption?.name || value;
    }
    if (filterKey === 'starRating') return `${value} Star`;
    return value;
  };

  const handleFilterChange = useCallback(
    (filterKey: string, values: MapFilterValue) => {
      onFilterChange(filterKey, values);
    },
    [onFilterChange]
  );

  return (
    <div
      style={{
        width: fullWidth ? '100%' : 280,
        minWidth: fullWidth ? 0 : 280,
        height: '100%',
        background: '#fff',
        boxShadow: fullWidth ? 'none' : '2px 0 8px rgba(0,0,0,0.12)',
        overflowY: 'auto',
        overflowX: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        flexShrink: 0,
        zIndex: 10,
      }}
    >
      {/* ── Sticky header ── */}
      <div
        style={{
          position: 'sticky',
          top: 0,
          zIndex: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '10px 14px',
          flexShrink: 0,
          background: '#fff',
          borderBottom: onClose ? '1px solid #e9ecef' : undefined,
        }}
      >
        <span
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 7,
            color: '#000',
            fontWeight: 700,
            fontSize: 20,
            letterSpacing: 0.3,
          }}
        >
          Filter by
        </span>
        {onClose && (
          <button
            type="button"
            aria-label="Close filters"
            onClick={onClose}
            style={{
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              padding: '4px 8px',
              fontSize: 26,
              lineHeight: 1,
              color: '#555',
            }}
          >
            ×
          </button>
        )}
      </div>

      <div style={{ padding: '12px 14px 24px', flex: 1 }}>

        {/* Applied filter tags */}
        {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 as PriceRangeFilter | undefined)?.from}-$${(appliedFilters.priceRange as PriceRangeFilter | undefined)?.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, values]) => {
                if (filterKey === 'priceRange' || !values || !Array.isArray(values) || values.length === 0) return null;

                return values.map((value) => (
                  <div
                    key={`${filterKey}-${value}`}
                    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, value)}
                    </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 !== value);
                        onFilterChange(filterKey, updatedValues);
                      }}
                      aria-label="Remove filter"
                    />
                  </div>
                ));
              })}
            </div>
          </div>
        )}

        {/* Budget / price range */}
        <BudgetFilter
          min={
            (appliedFilters.priceRange as PriceRangeFilter | undefined)?.from
          }
          max={
            (appliedFilters.priceRange as PriceRangeFilter | undefined)?.to
          }
          onChange={(min, max) =>
            handleFilterChange('priceRange', { from: min, to: max })
          }
        />

        {/* Checkbox filters */}
        {availableFilters &&
          Object.entries(availableFilters).map(([filterKey, filterConfig]) => {
            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] as string[])
              : [];
            return (
              <DynamicCheckboxFilter
                key={filterKey}
                filterKey={filterKey}
                title={title}
                values={filterConfig.values}
                selectedValues={selectedValues}
                onChange={(key, vals) => handleFilterChange(key, vals)}
                defaultOpen={false}
              />
            );
          })}

        {!availableFilters && !isLoadingHotels && (
          <p style={{ color: '#aaa', fontSize: 12, textAlign: 'center', marginTop: 24 }}>
            Filters load after the first hotel search.
          </p>
        )}

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

      </div>
    </div>
  );
}
