/**
 * FilterBar Component
 * Search and filter controls for schools
 */

'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
import { debounce, isValidPostcode } from '@/lib/utils';
import type { Filters } from '@/lib/types';
import styles from './FilterBar.module.css';

interface FilterBarProps {
  filters: Filters;
  showLocationSearch?: boolean;
  heroTitle?: string;
  heroDescription?: string;
}

export function FilterBar({ filters, showLocationSearch = true, heroTitle, heroDescription }: FilterBarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [searchMode, setSearchMode] = useState<'name' | 'location'>(
    searchParams.get('postcode') ? 'location' : 'name'
  );

  const currentSearch = searchParams.get('search') || '';
  const currentLA = searchParams.get('local_authority') || '';
  const currentType = searchParams.get('school_type') || '';
  const currentPostcode = searchParams.get('postcode') || '';
  const currentRadiusKm = searchParams.get('radius') || '0.8';
  // Convert km back to miles for display
  const currentRadiusMiles = (parseFloat(currentRadiusKm) / 1.60934).toFixed(1);

  const updateURL = useCallback((updates: Record<string, string>) => {
    const params = new URLSearchParams(searchParams);

    Object.entries(updates).forEach(([key, value]) => {
      if (value && value !== '') {
        params.set(key, value);
      } else {
        params.delete(key);
      }
    });

    // Reset to page 1 when filters change
    params.delete('page');

    router.push(`${pathname}?${params.toString()}`);
  }, [searchParams, pathname, router]);

  // Debounced search handler
  const debouncedSearch = useMemo(
    () => debounce((value: string) => {
      updateURL({ search: value, postcode: '', radius: '' });
    }, 300),
    [updateURL]
  );

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    debouncedSearch(e.target.value);
  };

  const handleFilterChange = (key: string, value: string) => {
    updateURL({ [key]: value });
  };

  const handleSearchModeToggle = (mode: 'name' | 'location') => {
    setSearchMode(mode);
    if (mode === 'name') {
      updateURL({ postcode: '', radius: '' });
    } else {
      updateURL({ search: '' });
    }
  };

  const handleLocationSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    const postcode = formData.get('postcode') as string;
    const radiusMiles = formData.get('radius') as string;

    if (!postcode.trim()) {
      alert('Please enter a postcode');
      return;
    }

    if (!isValidPostcode(postcode)) {
      alert('Please enter a valid UK postcode');
      return;
    }

    // Convert miles to km for API (backend expects km)
    const radiusKm = (parseFloat(radiusMiles) * 1.60934).toFixed(1);

    updateURL({ postcode, radius: radiusKm, search: '' });
  };

  const handleClearFilters = () => {
    router.push(pathname);
  };

  const hasActiveFilters = currentSearch || currentLA || currentType || currentPostcode;

  return (
    <div className={`${styles.filterBar} ${heroTitle ? styles.withHero : ''}`}>
      {heroTitle && (
        <div className={styles.heroSection}>
          <h1 className={styles.heroTitle}>{heroTitle}</h1>
          {heroDescription && <p className={styles.heroDescription}>{heroDescription}</p>}
        </div>
      )}

      {showLocationSearch && (
        <div className={styles.searchModeToggle}>
          <button
            className={searchMode === 'name' ? styles.active : ''}
            onClick={() => handleSearchModeToggle('name')}
          >
            Search by Name
          </button>
          <button
            className={searchMode === 'location' ? styles.active : ''}
            onClick={() => handleSearchModeToggle('location')}
          >
            Search by Location
          </button>
        </div>
      )}

      {searchMode === 'name' ? (
        <div className={styles.searchSection}>
          <input
            type="search"
            name="search"
            placeholder="Search schools by name..."
            defaultValue={currentSearch}
            onChange={handleSearchChange}
            className={styles.searchInput}
          />
        </div>
      ) : (
        <form onSubmit={handleLocationSearch} className={styles.locationForm}>
          <input
            type="text"
            name="postcode"
            placeholder="Enter postcode (e.g., SW1A 1AA)"
            defaultValue={currentPostcode}
            className={styles.postcodeInput}
            required
          />
          <select name="radius" defaultValue={currentRadiusMiles} className={styles.radiusSelect}>
            <option value="0.5">0.5 miles</option>
            <option value="1">1 mile</option>
            <option value="2">2 miles</option>
          </select>
          <button type="submit" className={styles.searchButton}>
            Search
          </button>
        </form>
      )}

      <div className={styles.filters}>
        <select
          value={currentLA}
          onChange={(e) => handleFilterChange('local_authority', e.target.value)}
          className={styles.filterSelect}
        >
          <option value="">All Local Authorities</option>
          {filters.local_authorities.map((la) => (
            <option key={la} value={la}>
              {la}
            </option>
          ))}
        </select>

        <select
          value={currentType}
          onChange={(e) => handleFilterChange('school_type', e.target.value)}
          className={styles.filterSelect}
        >
          <option value="">All School Types</option>
          {filters.school_types.map((type) => (
            <option key={type} value={type}>
              {type}
            </option>
          ))}
        </select>

        {hasActiveFilters && (
          <button onClick={handleClearFilters} className={styles.clearButton}>
            Clear Filters
          </button>
        )}
      </div>
    </div>
  );
}
