'use client';

import { useState, useEffect } from 'react';
import { CarMaker, CarModel, SearchFilters } from '@/types';
import { carsApi } from '@/lib/api';
import { useTranslation } from '@/lib/i18n';
import { useExchangeRateStore } from '@/lib/exchangeRateStore';

interface SearchFiltersProps {
  onSearch: (filters: SearchFilters) => void;
}

export default function SearchFiltersComponent({ onSearch }: SearchFiltersProps) {
  const { t, language } = useTranslation();
  const [makers, setMakers] = useState<CarMaker[]>([]);
  const [models, setModels] = useState<CarModel[]>([]);
  const [filters, setFilters] = useState<SearchFilters>({});

  useEffect(() => {
    loadMakers();
  }, []);

  useEffect(() => {
    if (filters.maker_id) {
      loadModels(filters.maker_id);
    } else {
      setModels([]);
    }
  }, [filters.maker_id]);

  const loadMakers = async () => {
    try {
      const data = await carsApi.getMakers();
      setMakers(data);
    } catch (error) {
      console.error('Failed to load makers:', error);
    }
  };

  const loadModels = async (makerId: number) => {
    try {
      const data = await carsApi.getModels(makerId);
      setModels(data);
    } catch (error) {
      console.error('Failed to load models:', error);
    }
  };

  const handleChange = (field: keyof SearchFilters, value: any) => {
    const newFilters = { ...filters, [field]: value || undefined };
    if (field === 'maker_id') {
      newFilters.model_id = undefined;
    }
    setFilters(newFilters);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSearch(filters);
  };

  const handleReset = () => {
    setFilters({});
    onSearch({});
  };

  // Format price options with USD - using dynamic exchange rate
  const formatPriceOption = (krw: number) => {
    const usdRate = useExchangeRateStore.getState().rates.USD?.rate || 1483;
    const usd = Math.round(krw / usdRate);
    return `${usd.toLocaleString()} USD`;
  };

  return (
    <form onSubmit={handleSubmit} className="bg-white p-6 rounded-lg shadow-md">
      <h2 className="text-xl font-semibold mb-4">{t.filter}</h2>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {/* Maker */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.maker}
          </label>
          <select
            value={filters.maker_id || ''}
            onChange={(e) => handleChange('maker_id', e.target.value ? Number(e.target.value) : undefined)}
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
          >
            <option value="">{t.allMakers}</option>
            {makers.map((maker) => (
              <option key={maker.id} value={maker.id}>
                {maker.name}
              </option>
            ))}
          </select>
        </div>

        {/* Model */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.model}
          </label>
          <select
            value={filters.model_id || ''}
            onChange={(e) => handleChange('model_id', e.target.value ? Number(e.target.value) : undefined)}
            disabled={!filters.maker_id}
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
          >
            <option value="">{t.allModels}</option>
            {models.map((model) => (
              <option key={model.id} value={model.id}>
                {model.name}
              </option>
            ))}
          </select>
        </div>

        {/* Year Range */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.minYear}
          </label>
          <input
            type="number"
            value={filters.year_min || ''}
            onChange={(e) => handleChange('year_min', e.target.value ? Number(e.target.value) : undefined)}
            placeholder="2015"
            min="2000"
            max="2025"
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
          />
        </div>

        {/* Price Range (USD) */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.price} Max (USD)
          </label>
          <select
            value={filters.price_max || ''}
            onChange={(e) => handleChange('price_max', e.target.value ? Number(e.target.value) : undefined)}
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
          >
            <option value="">No Limit</option>
            <option value="13333333">{formatPriceOption(13333333)}</option>
            <option value="26666666">{formatPriceOption(26666666)}</option>
            <option value="40000000">{formatPriceOption(40000000)}</option>
            <option value="66666666">{formatPriceOption(66666666)}</option>
            <option value="133333333">{formatPriceOption(133333333)}</option>
          </select>
        </div>

        {/* Mileage */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.maxMileage} (km)
          </label>
          <select
            value={filters.mileage_max || ''}
            onChange={(e) => handleChange('mileage_max', e.target.value ? Number(e.target.value) : undefined)}
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
          >
            <option value="">No Limit</option>
            <option value="50000">50,000 km</option>
            <option value="100000">100,000 km</option>
            <option value="150000">150,000 km</option>
            <option value="200000">200,000 km</option>
          </select>
        </div>

        {/* Fuel */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {t.fuel}
          </label>
          <select
            value={filters.fuel || ''}
            onChange={(e) => handleChange('fuel', e.target.value || undefined)}
            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
          >
            <option value="">{t.allFuelTypes}</option>
            <option value="가솔린">{t.gasoline}</option>
            <option value="디젤">{t.diesel}</option>
            <option value="LPG">{t.lpg}</option>
            <option value="하이브리드">{t.hybrid}</option>
            <option value="전기">{t.electric}</option>
          </select>
        </div>
      </div>

      {/* Buttons */}
      <div className="mt-6 flex justify-end space-x-4">
        <button
          type="button"
          onClick={handleReset}
          className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition"
        >
          {t.reset}
        </button>
        <button
          type="submit"
          className="px-6 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition"
        >
          {t.search}
        </button>
      </div>
    </form>
  );
}
