'use client';

import { useTranslations } from 'next-intl';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import { PROPERTY_TYPES, TRANSACTION_TYPES } from '@/lib/validations/listings';

export interface SearchFilters {
  transactionType: string;
  propertyType: string;
  city: string;
  district: string;
  minPrice: string;
  maxPrice: string;
  minArea: string;
  maxArea: string;
  bedrooms: string;
  sort: string;
}

const CITIES = [
  'Hồ Chí Minh',
  'Hà Nội',
  'Đà Nẵng',
  'Nha Trang',
  'Cần Thơ',
  'Hải Phòng',
  'Bình Dương',
  'Đồng Nai',
  'Long An',
  'Bà Rịa - Vũng Tàu',
];

const PRICE_RANGE_KEYS = ['under1b', '1to3b', '3to5b', '5to10b', '10to20b', 'over20b'] as const;

const PRICE_RANGE_VALUES = [
  { min: '0', max: '1000000000' },
  { min: '1000000000', max: '3000000000' },
  { min: '3000000000', max: '5000000000' },
  { min: '5000000000', max: '10000000000' },
  { min: '10000000000', max: '20000000000' },
  { min: '20000000000', max: '' },
];

interface FilterBarProps {
  filters: SearchFilters;
  onChange: (filters: SearchFilters) => void;
  onSearch: () => void;
  layout?: 'horizontal' | 'sidebar';
}

export function FilterBar({ filters, onChange, onSearch, layout = 'horizontal' }: FilterBarProps) {
  const t = useTranslations('search');

  const update = (key: keyof SearchFilters, value: string) => {
    onChange({ ...filters, [key]: value });
  };

  const handlePriceRange = (value: string) => {
    if (!value) {
      onChange({ ...filters, minPrice: '', maxPrice: '' });
      return;
    }
    const range = PRICE_RANGE_VALUES[Number(value)];
    if (range) {
      onChange({ ...filters, minPrice: range.min, maxPrice: range.max });
    }
  };

  const currentPriceIdx = PRICE_RANGE_VALUES.findIndex(
    (r) => r.min === filters.minPrice && r.max === filters.maxPrice,
  );

  const isSidebar = layout === 'sidebar';

  return (
    <div className={isSidebar ? 'space-y-4' : 'space-y-3'} role="search" aria-label={t('filters')}>
      {isSidebar && <h3 className="font-semibold">{t('filters')}</h3>}

      <div className={isSidebar ? 'space-y-3' : 'flex flex-wrap gap-3'}>
        <Select
          value={filters.transactionType}
          onChange={(e) => update('transactionType', e.target.value)}
          className={isSidebar ? 'w-full' : 'w-full sm:w-40'}
          aria-label={t('allTransactions')}
        >
          <option value="">{t('allTransactions')}</option>
          {TRANSACTION_TYPES.map((type) => (
            <option key={type.value} value={type.value}>
              {type.label}
            </option>
          ))}
        </Select>

        <Select
          value={filters.propertyType}
          onChange={(e) => update('propertyType', e.target.value)}
          className={isSidebar ? 'w-full' : 'w-full sm:w-44'}
          aria-label={t('allPropertyTypes')}
        >
          <option value="">{t('allPropertyTypes')}</option>
          {PROPERTY_TYPES.map((type) => (
            <option key={type.value} value={type.value}>
              {type.label}
            </option>
          ))}
        </Select>

        <Select
          value={filters.city}
          onChange={(e) => update('city', e.target.value)}
          className={isSidebar ? 'w-full' : 'w-full sm:w-44'}
          aria-label={t('allAreas')}
        >
          <option value="">{t('allAreas')}</option>
          {CITIES.map((c) => (
            <option key={c} value={c}>
              {c}
            </option>
          ))}
        </Select>

        <Select
          value={currentPriceIdx >= 0 ? String(currentPriceIdx) : ''}
          onChange={(e) => handlePriceRange(e.target.value)}
          className={isSidebar ? 'w-full' : 'w-full sm:w-40'}
          aria-label={t('allPrices')}
        >
          <option value="">{t('allPrices')}</option>
          {PRICE_RANGE_KEYS.map((key, i) => (
            <option key={key} value={String(i)}>
              {t(`priceRanges.${key}`)}
            </option>
          ))}
        </Select>

        {isSidebar && (
          <>
            <div>
              <label className="mb-1 block text-sm text-muted-foreground">{t('areaLabel')}</label>
              <div className="flex gap-2">
                <Input
                  type="number"
                  placeholder={t('areaFrom')}
                  value={filters.minArea}
                  onChange={(e) => update('minArea', e.target.value)}
                  className="w-full"
                  aria-label={`${t('areaLabel')} ${t('areaFrom')}`}
                />
                <Input
                  type="number"
                  placeholder={t('areaTo')}
                  value={filters.maxArea}
                  onChange={(e) => update('maxArea', e.target.value)}
                  className="w-full"
                  aria-label={`${t('areaLabel')} ${t('areaTo')}`}
                />
              </div>
            </div>

            <Select
              value={filters.bedrooms}
              onChange={(e) => update('bedrooms', e.target.value)}
              className="w-full"
              aria-label={t('bedrooms')}
            >
              <option value="">{t('bedrooms')}</option>
              {[1, 2, 3, 4, 5].map((n) => (
                <option key={n} value={String(n)}>
                  {t('bedroomsCount', { count: n })}
                </option>
              ))}
            </Select>

            <Input
              placeholder={t('district')}
              value={filters.district}
              onChange={(e) => update('district', e.target.value)}
              className="w-full"
              aria-label={t('district')}
            />
          </>
        )}

        {!isSidebar && (
          <Select
            value={filters.bedrooms}
            onChange={(e) => update('bedrooms', e.target.value)}
            className="w-full sm:w-36"
            aria-label={t('bedrooms')}
          >
            <option value="">{t('bedrooms')}</option>
            {[1, 2, 3, 4, 5].map((n) => (
              <option key={n} value={String(n)}>
                {t('bedroomsCount', { count: n })}
              </option>
            ))}
          </Select>
        )}
      </div>

      {isSidebar && (
        <Button onClick={onSearch} className="w-full">
          {t('searchButton')}
        </Button>
      )}
    </div>
  );
}
