'use client';

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

interface FilterBarProps {
  filters: Filters;
  isHero?: boolean;
}

export function FilterBar({ filters, isHero }: FilterBarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();
  const inputRef = useRef<HTMLInputElement>(null);

  const currentSearch = searchParams.get('search') || '';
  const currentPostcode = searchParams.get('postcode') || '';
  const currentRadius = searchParams.get('radius') || '1';
  const initialOmniValue = currentPostcode || currentSearch;

  const [omniValue, setOmniValue] = useState(initialOmniValue);

  const currentLA = searchParams.get('local_authority') || '';
  const currentType = searchParams.get('school_type') || '';

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Focus search on '/' or Ctrl+K, but not when typing in an input
      if ((e.key === '/' || (e.key === 'k' && (e.ctrlKey || e.metaKey))) &&
          document.activeElement?.tagName !== 'INPUT' &&
          document.activeElement?.tagName !== 'TEXTAREA' &&
          document.activeElement?.tagName !== 'SELECT') {
        e.preventDefault();
        inputRef.current?.focus();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  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);
      }
    });

    params.delete('page');

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

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!omniValue.trim()) {
      updateURL({ search: '', postcode: '', radius: '' });
      return;
    }

    if (isValidPostcode(omniValue)) {
      updateURL({ postcode: omniValue.trim().toUpperCase(), radius: currentRadius || '1', search: '' });
    } else {
      updateURL({ search: omniValue.trim(), postcode: '', radius: '' });
    }
  };

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

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

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

  return (
    <div className={`${styles.filterBar} ${isPending ? styles.isLoading : ''} ${isHero ? styles.heroMode : ''}`}>
      <form onSubmit={handleSearchSubmit} className={styles.searchSection}>
        <div className={styles.omniBoxContainer}>
          <input
            ref={inputRef}
            type="search"
            value={omniValue}
            onChange={(e) => setOmniValue(e.target.value)}
            placeholder="Search by school name or postcode (e.g., SW1A 1AA)..."
            className={styles.omniInput}
          />
          <button type="submit" className={`btn btn-primary ${styles.searchButton}`} disabled={isPending}>
            {isPending ? <div className={styles.spinner}></div> : 'Search'}
          </button>
        </div>
        {currentPostcode && (
          <div className={styles.radiusWrapper}>
            <label className={styles.radiusLabel}>Within:</label>
            <select
              value={currentRadius}
              onChange={e => updateURL({ radius: e.target.value })}
              className={styles.radiusSelect}
              disabled={isPending}
            >
              <option value="0.5">0.5 miles</option>
              <option value="1">1 mile</option>
              <option value="3">3 miles</option>
              <option value="5">5 miles</option>
              <option value="10">10 miles</option>
            </select>
          </div>
        )}
      </form>

      <div className={styles.filters}>
        <select
          value={currentLA}
          onChange={(e) => handleFilterChange('local_authority', e.target.value)}
          className={styles.filterSelect}
          disabled={isPending}
        >
          <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}
          disabled={isPending}
        >
          <option value="">All School Types</option>
          {filters.school_types.map((type) => (
            <option key={type} value={type}>
              {type}
            </option>
          ))}
        </select>

        {hasActiveFilters && (
          <button onClick={handleClearFilters} className={`btn btn-tertiary ${styles.clearButton}`} type="button" disabled={isPending}>
            Clear Filters
          </button>
        )}
      </div>
    </div>
  );
}
