'use client';

import { useState } from 'react';

// Types for dynamic filter data
export interface FilterOption {
  label: string;
  value: string;
}

export interface FilterField {
  slug: string;
  name: string;
  fieldType: string;
  options: FilterOption[];
}

// Dynamic filter state - keys are field slugs
export type FilterState = Record<string, string[]>;

interface FilterModalProps {
  isOpen: boolean;
  onClose: () => void;
  filters: FilterState;
  filterFields: FilterField[];
  onToggleFilter: (fieldSlug: string, optionValue: string) => void;
  onClearAll: () => void;
  onApply: () => void;
}

export function FilterModal({ isOpen, onClose, filters, filterFields, onToggleFilter, onClearAll, onApply }: FilterModalProps) {
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>(() => {
    // Initialize all sections as expanded
    const initial: Record<string, boolean> = {};
    filterFields.forEach(field => {
      initial[field.slug] = true;
    });
    return initial;
  });

  const toggleSection = (section: string) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/30" onClick={onClose} />

      {/* Modal */}
      <div className="relative bg-white rounded-[20px] w-full max-w-[720px] max-h-[85vh] overflow-hidden shadow-xl flex flex-col">
        {/* Header */}
        <div className="shrink-0 bg-white px-8 py-5 border-b border-[#d9d9d9] flex items-center justify-between">
          <h2 className="font-fractul font-bold text-[25px] text-[#00293d]">Filters</h2>
          <button onClick={onClose} className="text-[#00293d] hover:opacity-70">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        {/* Scrollable Content */}
        <div className="overflow-y-auto flex-1 px-8 py-6">
          {filterFields.map((field, index) => (
            <div key={field.slug}>
              <div className="mb-6">
                <button
                  onClick={() => toggleSection(field.slug)}
                  className="w-full flex items-center justify-between gap-2 font-fractul text-[20px] text-[#00293d] mb-4 text-left"
                >
                  <span className="flex-1 min-w-0">{field.name}</span>
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" className={`flex-shrink-0 transition-transform ${expandedSections[field.slug] ? 'rotate-180' : ''}`}>
                    <path d="M2 4L6 8L10 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
                {expandedSections[field.slug] && (
                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-4 md:gap-x-6 gap-y-3">
                    {field.options.map((option) => (
                      <label key={option.value} className="flex items-start gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={(filters[field.slug] || []).includes(option.value)}
                          onChange={() => onToggleFilter(field.slug, option.value)}
                          className="flex-shrink-0 w-[17px] h-[17px] mt-[3px] rounded-[5px] border-2 border-[#00293d]/30 appearance-none cursor-pointer checked:bg-[#e58625] checked:border-[#e58625] checked:bg-[url('data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2016%2016%22%20fill%3D%22white%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M12.207%204.793a1%201%200%20010%201.414l-5%205a1%201%200%2001-1.414%200l-2-2a1%201%200%20011.414-1.414L6.5%209.086l4.293-4.293a1%201%200%20011.414%200z%22%2F%3E%3C%2Fsvg%3E')] checked:bg-center checked:bg-no-repeat focus:ring-2 focus:ring-[#e58625]/50"
                        />
                        <span className="font-serif text-[15px] text-[#00293d] leading-[1.4]">{option.label}</span>
                      </label>
                    ))}
                  </div>
                )}
              </div>
              {index < filterFields.length - 1 && <div className="border-t border-[#d9d9d9] my-4" />}
            </div>
          ))}

          {filterFields.length === 0 && (
            <div className="text-center py-8">
              <p className="font-serif text-[15px] text-[#00293d]/60">Loading filters...</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="shrink-0 bg-white px-4 sm:px-8 py-4 sm:py-5 border-t border-[#d9d9d9] flex items-center gap-3">
          <button
            onClick={onClearAll}
            className="flex-1 sm:flex-initial px-4 sm:px-6 py-3 rounded-[15px] border border-[#00293d] font-fractul font-bold text-[14px] text-[#00293d] hover:bg-[#00293d]/5 transition-colors whitespace-nowrap"
          >
            Clear all Filters
          </button>
          <button
            onClick={onApply}
            className="flex-1 sm:flex-initial px-4 sm:px-8 py-3 rounded-[15px] bg-[#e58625] hover:bg-[#d47720] font-fractul font-bold text-[14px] text-[#00293d] transition-colors whitespace-nowrap sm:ml-auto"
          >
            Apply Filters
          </button>
        </div>
      </div>
    </div>
  );
}
