'use client';

import { Button } from '@/components/ui/Button';
import { Checkbox } from '@/components/ui/Checkbox';
import { RadioButton } from '@/components/ui/RadioButton';
import { Heading } from '@/components/ui/Typography';
import { useEffect, useRef, useState } from 'react';
import { SortDropdown } from './client/SortDropdown';

interface FilterSidebarProps {
  isOpen: boolean;
  onClose: () => void;
  onApplyFilters: (filters: string[]) => void;
  activeFilters: string[];
}

interface FilterCategory {
  name: string;
  type?: 'checkbox' | 'radio' | 'dropdown';
  options: string[];
}

const FILTER_CATEGORIES: FilterCategory[] = [
  {
    name: 'Filter One',
    type: 'checkbox',
    options: ['Test One', 'Test Two', 'Test Three', 'Test Four', 'Test Five']
  },
  {
    name: 'Filter Two',
    type: 'radio',
    options: ['All', 'Option One', 'Option Two', 'Option Three', 'Option Four', 'Option Five']
  },
  {
    name: 'Filter Six',
    type: 'dropdown',
    options: ['Select 1', 'Select 2', 'Select 3']
  }
];

// Helper function to create a unique filter key
const getFilterKey = (category: string, option: string) => {
  return `${category}:${option}`;
};

// Helper function to extract the option from a filter key
const getOptionFromKey = (filterKey: string) => {
  const parts = filterKey.split(':');
  return parts.length > 1 ? parts[1] : filterKey;
};

// Helper function to extract the category from a filter key
const getCategoryFromKey = (filterKey: string) => {
  const parts = filterKey.split(':');
  return parts.length > 1 ? parts[0] : '';
};

export function FilterSidebar({ isOpen, onClose, onApplyFilters, activeFilters }: FilterSidebarProps) {
  const [minPrice, setMinPrice] = useState(5);
  const [maxPrice, setMaxPrice] = useState(100);
  const [localFilters, setLocalFilters] = useState<string[]>([]);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const rangeRef = useRef<HTMLDivElement>(null);
  
  // Update the range slider fill with primary color
  const updateRangeStyle = () => {
    if (rangeRef.current) {
      const percentage1 = Math.min((minPrice / 100) * 100, 100);
      const percentage2 = Math.min((maxPrice / 100) * 100, 100);
      rangeRef.current.style.background = `linear-gradient(to right, #e5e7eb ${percentage1}%, var(--primary-color, #D94D72) ${percentage1}%, var(--primary-color, #D94D72) ${percentage2}%, #e5e7eb ${percentage2}%)`;
    }
  };

  // Update range fill on mount and when prices change
  useEffect(() => {
    updateRangeStyle();
  }, [minPrice, maxPrice]);
  
  // Sync activeFilters with localFilters when sidebar opens
  useEffect(() => {
    if (isOpen) {
      setLocalFilters([...activeFilters]);
      
      // Check for price filter in active filters
      const priceFilter = activeFilters.find(filter => filter.startsWith('Cijena:'));
      if (priceFilter) {
        const priceMatch = priceFilter.match(/Cijena: (\d+)€ - (\d+)€/);
        if (priceMatch && priceMatch[1] && priceMatch[2]) {
          setMinPrice(parseInt(priceMatch[1]));
          setMaxPrice(parseInt(priceMatch[2]));
        }
      } else {
        // Reset to default values if no price filter
        setMinPrice(5);
        setMaxPrice(100);
      }
      
      // Reset scroll position when sidebar opens
      if (sidebarRef.current) {
        sidebarRef.current.scrollTop = 0;
      }
    }
  }, [isOpen, activeFilters]);

  // Lock body scroll when sidebar is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, [isOpen]);

  const toggleFilter = (category: string, option: string) => {
    const filterKey = getFilterKey(category, option);
    if (localFilters.includes(filterKey)) {
      setLocalFilters(localFilters.filter(f => f !== filterKey));
    } else {
      setLocalFilters([...localFilters, filterKey]);
    }
  };

  const clearFilters = () => {
    setLocalFilters([]);
    setMinPrice(5);
    setMaxPrice(100);
  };

  const clearFilterCategory = (category: string) => {
    setLocalFilters(localFilters.filter(f => !f.startsWith(`${category}:`)));
  };

  const clearPriceRange = () => {
    // Reset price values
    setMinPrice(5);
    setMaxPrice(100);
    
    // Remove any price filter tags
    setLocalFilters(localFilters.filter(f => !f.startsWith('Cijena:')));
  };

  const applyFilters = () => {
    // Create a copy of localFilters, removing any existing price filters
    let filtersToApply = localFilters.filter(f => !f.startsWith('Cijena:'));
    
    // Ensure min price doesn't exceed max price
    let finalMinPrice = minPrice;
    let finalMaxPrice = maxPrice;
    
    if (finalMinPrice > finalMaxPrice) {
      finalMinPrice = finalMaxPrice;
    }
    
    // Add price range as a filter tag
    if (finalMinPrice > 5 || finalMaxPrice !== 100) {
      filtersToApply.push(`Cijena: ${finalMinPrice}€ - ${finalMaxPrice}€`);
    }
    
    onApplyFilters(filtersToApply);
    onClose();
  };

  // Handle price range min input change
  const handleMinPriceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value);
    if (!isNaN(value) && value >= 0) {
      setMinPrice(value);
      // If min exceeds max, adjust max as well
      if (value > maxPrice) {
        setMaxPrice(value);
      }
    }
  };

  // Handle price range max input change
  const handleMaxPriceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value);
    if (!isNaN(value) && value >= 0) {
      setMaxPrice(value);
    }
  };

  // Extract filter option handlers for cleaner code
  const handleRadioChange = (category: string, option: string, categoryOptions: string[]) => {
    // Get all filter keys for this category
    const categoryFilterPrefix = `${category}:`;
    
    // Remove previous selections from this category
    const filtersWithoutCategory = localFilters.filter(f => !f.startsWith(categoryFilterPrefix));
    
    if (option === 'All') {
      // If 'All' is selected, don't add any new filter for this category
      setLocalFilters(filtersWithoutCategory);
    } else {
      // Add the new selected option with category prefix
      setLocalFilters([...filtersWithoutCategory, getFilterKey(category, option)]);
    }
  };

  const handleDropdownChange = (category: string, value: string) => {
    if (value) {
      // Get all filter keys for this category
      const categoryFilterPrefix = `${category}:`;
      
      // Remove previous selections from this category
      const filtersWithoutCategory = localFilters.filter(f => !f.startsWith(categoryFilterPrefix));
      
      // Add the new selected option with category prefix
      setLocalFilters([...filtersWithoutCategory, getFilterKey(category, value)]);
    }
  };

  return (
    <>
      {/* Overlay - adjusted to only cover the product grid area */}
      {isOpen && (
        <div 
          className="fixed inset-x-0 bottom-0 bg-black bg-opacity-50 z-30"
          onClick={onClose}
          style={{ 
            top: '0', // Same as sidebar top position
            bottom: '0',  // Allow footer to be visible
          }}
        />
      )}
      
      {/* Sidebar - positioned exactly below navbar */}
      <div 
        ref={sidebarRef}
        className={`fixed left-0 h-[calc(100vh-64px)] w-[350px] bg-white z-40 transform transition-transform duration-300 ease-in-out ${
          isOpen ? 'translate-x-0' : '-translate-x-full'
        } overflow-y-auto shadow-lg`}
        style={{ top: '64px', margin: 0, padding: 0 }} // Exactly at navbar bottom with no space
      >
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-4">
            <Heading level={4} className="font-semibold">Filteri</Heading>
            <button onClick={onClose} className="text-black">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-6 h-6">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
          <hr className="border-gray-200 mb-4" />
          
          {/* Filter sections */}
          <div className="space-y-4">
            {/* Checkbox Filter */}
            <div>
              <div className="flex justify-between items-center mb-3">
                <Heading level={4} className="font-medium">{FILTER_CATEGORIES[0]?.name}</Heading>
                <button 
                  onClick={() => clearFilterCategory(FILTER_CATEGORIES[0]?.name || '')}
                  className="text-sm text-gray-500 hover:text-black"
                >
                  Clear
                </button>
              </div>
              
              <div className="space-y-3">
                {FILTER_CATEGORIES[0]?.options.map((option) => (
                  <div key={option}>
                    <Checkbox
                      id={option}
                      checked={localFilters.includes(getFilterKey(FILTER_CATEGORIES[0]?.name || '', option))}
                      onChange={() => toggleFilter(FILTER_CATEGORIES[0]?.name || '', option)}
                      label={option}
                    />
                  </div>
                ))}
              </div>
            </div>
            
            <hr className="border-gray-200" />
            
            {/* Radio Filter */}
            <div>
              <div className="flex justify-between items-center mb-3">
                <Heading level={4} className="font-medium">{FILTER_CATEGORIES[1]?.name}</Heading>
                <button 
                  onClick={() => clearFilterCategory(FILTER_CATEGORIES[1]?.name || '')}
                  className="text-sm text-gray-500 hover:text-black"
                >
                  Clear
                </button>
              </div>
              
              <div className="space-y-3">
                {FILTER_CATEGORIES[1]?.options.map((option) => (
                  <div key={option}>
                    <RadioButton
                      id={`radio-${option}`}
                      name="filter-two"
                      value={option}
                      checked={
                        option === 'All' 
                          ? !localFilters.some(f => f.startsWith(`${FILTER_CATEGORIES[1]?.name}:`) && !f.endsWith(':All')) 
                          : localFilters.includes(getFilterKey(FILTER_CATEGORIES[1]?.name || '', option))
                      }
                      onChange={() => handleRadioChange(FILTER_CATEGORIES[1]?.name || '', option, FILTER_CATEGORIES[1]?.options || [])}
                      label={option}
                    />
                  </div>
                ))}
              </div>
            </div>
            
            <hr className="border-gray-200" />
            
            {/* Dropdown Filter */}
            <div>
              <div className="flex justify-between items-center mb-3">
                <Heading level={4} className="font-medium">{FILTER_CATEGORIES[2]?.name}</Heading>
                <button 
                  onClick={() => clearFilterCategory(FILTER_CATEGORIES[2]?.name || '')}
                  className="text-sm text-gray-500 hover:text-black"
                >
                  Clear
                </button>
              </div>
              
              <SortDropdown 
                value={localFilters.find(f => f.startsWith(`${FILTER_CATEGORIES[2]?.name}:`))?.split(':')[1] || ''}
                onChange={(value) => handleDropdownChange(FILTER_CATEGORIES[2]?.name || '', value)}
                label=""
              />
            </div>
            
            <hr className="border-gray-200" />
            
            {/* Price Range */}
            <div>
              <div className="flex justify-between items-center mb-3">
                <Heading level={4} className="font-medium">Cijena</Heading>
                <button 
                  onClick={clearPriceRange}
                  className="text-sm text-gray-500 hover:text-black"
                >
                  Clear
                </button>
              </div>
              
              {/* Min-Max Range Inputs */}
              <div className="flex space-x-4 mb-4">
                <div className="w-1/2">
                  <label htmlFor="min-price" className="text-sm block mb-1">Od</label>
                  <input
                    type="number"
                    id="min-price"
                    min="0"
                    value={minPrice}
                    onChange={handleMinPriceChange}
                    className="w-full border border-gray-300 rounded-md p-2"
                  />
                </div>
                <div className="w-1/2">
                  <label htmlFor="max-price" className="text-sm block mb-1">Do</label>
                  <input
                    type="number"
                    id="max-price"
                    min="0"
                    value={maxPrice}
                    onChange={handleMaxPriceChange}
                    className="w-full border border-gray-300 rounded-md p-2"
                  />
                </div>
              </div>
              
              {/* Dual Range Slider */}
              <div className="relative pt-5 pb-8">
                <div 
                  ref={rangeRef} 
                  className="w-full h-1 bg-gray-200 rounded absolute top-6"
                ></div>
                
                {/* Min range slider */}
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={Math.min(minPrice, 100)}
                  onChange={(e) => {
                    const value = parseInt(e.target.value);
                    if (value < maxPrice) {
                      setMinPrice(value);
                    }
                  }}
                  className="absolute top-4 w-full pointer-events-none appearance-none bg-transparent z-30"
                  style={{
                    WebkitAppearance: 'none',
                    appearance: 'none'
                  }}
                />
                
                {/* Max range slider */}
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={Math.min(maxPrice, 100)}
                  onChange={(e) => {
                    const value = parseInt(e.target.value);
                    if (value > minPrice) {
                      setMaxPrice(value);
                    }
                  }}
                  className="absolute top-4 w-full pointer-events-none appearance-none bg-transparent z-30"
                  style={{
                    WebkitAppearance: 'none',
                    appearance: 'none'
                  }}
                />
                
                <style jsx>{`
                  :root {
                    --primary-color: #D94D72;
                  }
                  input[type='range']::-webkit-slider-thumb {
                    -webkit-appearance: none;
                    pointer-events: all;
                    width: 16px;
                    height: 16px;
                    background-color: white;
                    border: 1px solid var(--primary-color, #D94D72);
                    border-radius: 50%;
                    cursor: pointer;
                  }
                  
                  input[type='range']::-moz-range-thumb {
                    pointer-events: all;
                    width: 16px;
                    height: 16px;
                    background-color: white;
                    border: 1px solid var(--primary-color, #D94D72);
                    border-radius: 50%;
                    cursor: pointer;
                  }
                `}</style>
              </div>
              
              <div className="flex justify-between mt-1">
                <span className="text-sm">{minPrice}€</span>
                <span className="text-sm">{maxPrice}€</span>
              </div>
            </div>
          </div>
          
          {/* Bottom Controls */}
          <div className="mt-8">
            <hr className="border-gray-200 mb-4" />
            <div className="flex justify-between items-center">
              <Button 
                onClick={clearFilters} 
                variant="outline"
                size="sm"
              >
                Obriši sve
              </Button>
              <Button 
                onClick={applyFilters}
                variant="primary"
                size="sm"
              >
                Filtriraj
              </Button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
} 