'use client';

import { useState, useEffect } from 'react';
import { carmodooApi, CarmodooMaker, CarmodooModel, CarmodooSearchResult } from '@/lib/api';

export interface CarmodooSearchParams {
  maker_code: string;
  model_code: string;
  grade?: string;
  year_min: number;
  year_max: number;
  fuel?: string;
  displacement_min?: number;
  displacement_max?: number;
  mileage_min?: number;
  mileage_max?: number;
}

interface CarmodooSearchFiltersProps {
  onSearchStart?: () => void;
  onSearchComplete?: (results: CarmodooSearchResult[], params: CarmodooSearchParams) => void;
  onSearchError?: (error: any) => void;
  disabled?: boolean;
}

// Fuel type options
const fuelOptions = [
  { value: '휘발유', label: '휘발유 (가솔린)' },
  { value: '경유', label: '경유 (디젤)' },
  { value: 'LPG', label: 'LPG' },
  { value: '하이브리드', label: '하이브리드' },
  { value: '전기', label: '전기' },
];

// Displacement options (cc)
const displacementOptions = [1000, 1500, 2000, 2500, 3000, 3500, 4000, 5000];

// Mileage options (만km)
const mileageOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20];

export default function CarmodooSearchFilters({
  onSearchStart,
  onSearchComplete,
  onSearchError,
  disabled = false,
}: CarmodooSearchFiltersProps) {
  // Data states
  const [makers, setMakers] = useState<CarmodooMaker[]>([]);
  const [models, setModels] = useState<CarmodooModel[]>([]);
  const [grades, setGrades] = useState<{ code: string; name: string }[]>([]);

  // Filter states
  const [selectedMaker, setSelectedMaker] = useState('');
  const [selectedModel, setSelectedModel] = useState('');
  const [selectedGrade, setSelectedGrade] = useState('');
  const [yearFrom, setYearFrom] = useState('');
  const [yearTo, setYearTo] = useState('');
  const [selectedFuel, setSelectedFuel] = useState('');
  const [displacementMin, setDisplacementMin] = useState('');
  const [displacementMax, setDisplacementMax] = useState('');
  const [mileageMin, setMileageMin] = useState('');
  const [mileageMax, setMileageMax] = useState('');

  // Loading states
  const [loadingMakers, setLoadingMakers] = useState(false);
  const [loadingModels, setLoadingModels] = useState(false);
  const [loadingGrades, setLoadingGrades] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [searchProgress, setSearchProgress] = useState(0);

  // Year options
  const currentYear = new Date().getFullYear();
  const yearOptions = Array.from({ length: currentYear - 2009 }, (_, i) => currentYear - i);

  // Load makers on mount
  useEffect(() => {
    loadMakers();
  }, []);

  // Load models when maker changes
  useEffect(() => {
    if (selectedMaker) {
      setLoadingModels(true);
      setSelectedModel('');
      setSelectedGrade('');
      setModels([]);
      setGrades([]);
      carmodooApi.getModels(selectedMaker)
        .then(setModels)
        .catch(console.error)
        .finally(() => setLoadingModels(false));
    }
  }, [selectedMaker]);

  // Load grades when model changes
  useEffect(() => {
    if (selectedMaker && selectedModel) {
      setLoadingGrades(true);
      setSelectedGrade('');
      setGrades([]);
      carmodooApi.getGrades(selectedMaker, selectedModel)
        .then(setGrades)
        .catch(() => setGrades([]))
        .finally(() => setLoadingGrades(false));
    }
  }, [selectedMaker, selectedModel]);

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

  const handleSearch = async () => {
    if (!selectedMaker || !selectedModel || !yearFrom || !yearTo) {
      alert('제조사, 모델, 연식을 선택해주세요.');
      return;
    }

    setIsSearching(true);
    setSearchProgress(0);
    onSearchStart?.();

    // Progress animation
    let progressInterval: NodeJS.Timeout | null = null;
    let currentProgress = 0;

    progressInterval = setInterval(() => {
      if (currentProgress < 90) {
        currentProgress += (90 - currentProgress) * 0.05;
        setSearchProgress(currentProgress);
      }
    }, 100);

    try {
      const params: any = {
        maker_code: selectedMaker,
        model_code: selectedModel,
        year_min: parseInt(yearFrom),
        year_max: parseInt(yearTo),
        page_size: 50,
      };
      if (selectedGrade) params.grade = selectedGrade;
      if (selectedFuel) params.fuel = selectedFuel;
      if (displacementMin) params.displacement_min = parseInt(displacementMin);
      if (displacementMax) params.displacement_max = parseInt(displacementMax);
      if (mileageMin) params.mileage_min = parseInt(mileageMin) * 10000;
      if (mileageMax) params.mileage_max = parseInt(mileageMax) * 10000;

      const result = await carmodooApi.requestSearch(params);

      if (progressInterval) clearInterval(progressInterval);
      setSearchProgress(100);

      onSearchComplete?.(result.cars || [], params as CarmodooSearchParams);
    } catch (error) {
      console.error('Failed to search cars:', error);
      onSearchError?.(error);
      alert('검색에 실패했습니다. 다시 시도해주세요.');
    } finally {
      if (progressInterval) clearInterval(progressInterval);
      setSearchProgress(100);
      setTimeout(() => {
        setIsSearching(false);
        setSearchProgress(0);
      }, 500);
    }
  };

  const handleReset = () => {
    setSelectedMaker('');
    setSelectedModel('');
    setSelectedGrade('');
    setYearFrom('');
    setYearTo('');
    setSelectedFuel('');
    setDisplacementMin('');
    setDisplacementMax('');
    setMileageMin('');
    setMileageMax('');
    setModels([]);
    setGrades([]);
  };

  const isDisabled = disabled || isSearching;

  return (
    <div className="bg-gray-50 border border-gray-200 rounded-lg p-6">
      {/* Row 1: Maker, Model, Grade, Year, Search Button */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-4">
        {/* Maker */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">제조사 *</label>
          <select
            value={selectedMaker}
            onChange={(e) => setSelectedMaker(e.target.value)}
            disabled={loadingMakers || isDisabled}
            className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
          >
            <option value="">{loadingMakers ? '로딩...' : '선택'}</option>
            {makers.map((maker) => (
              <option key={maker.code} value={maker.code}>{maker.name}</option>
            ))}
          </select>
        </div>

        {/* Model */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">모델 *</label>
          <select
            value={selectedModel}
            onChange={(e) => setSelectedModel(e.target.value)}
            disabled={!selectedMaker || loadingModels || isDisabled}
            className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
          >
            <option value="">{loadingModels ? '로딩...' : '선택'}</option>
            {models.map((model) => (
              <option key={model.code} value={model.code}>{model.name}</option>
            ))}
          </select>
        </div>

        {/* Grade */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">등급</label>
          <select
            value={selectedGrade}
            onChange={(e) => setSelectedGrade(e.target.value)}
            disabled={!selectedModel || loadingGrades || isDisabled}
            className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
          >
            <option value="">{loadingGrades ? '로딩...' : '전체'}</option>
            {grades.map((grade) => (
              <option key={grade.code} value={grade.code}>{grade.name}</option>
            ))}
          </select>
        </div>

        {/* Year Range */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">연식 *</label>
          <div className="flex gap-1 items-center">
            <select
              value={yearFrom}
              onChange={(e) => setYearFrom(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">시작</option>
              {yearOptions.map((year) => (
                <option key={year} value={year}>{year}</option>
              ))}
            </select>
            <span className="text-gray-500">~</span>
            <select
              value={yearTo}
              onChange={(e) => setYearTo(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">종료</option>
              {yearOptions.map((year) => (
                <option key={year} value={year}>{year}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Search Button */}
        <div className="flex items-end gap-2">
          <button
            onClick={handleSearch}
            disabled={isDisabled || !selectedMaker || !selectedModel || !yearFrom || !yearTo}
            className="flex-1 bg-primary-600 text-white py-2 rounded-md hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium transition-colors"
          >
            {isSearching ? '검색중...' : '검색'}
          </button>
          <button
            onClick={handleReset}
            disabled={isDisabled}
            className="px-3 py-2 border border-gray-300 rounded-md text-gray-600 hover:bg-gray-100 disabled:opacity-50 text-sm transition-colors"
            title="초기화"
          >
            ↻
          </button>
        </div>
      </div>

      {/* Row 2: Fuel, Displacement, Mileage */}
      <div className="grid grid-cols-3 gap-4">
        {/* Fuel */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">연료</label>
          <select
            value={selectedFuel}
            onChange={(e) => setSelectedFuel(e.target.value)}
            disabled={isDisabled}
            className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
          >
            <option value="">전체</option>
            {fuelOptions.map((fuel) => (
              <option key={fuel.value} value={fuel.value}>{fuel.label}</option>
            ))}
          </select>
        </div>

        {/* Displacement */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">배기량 (cc)</label>
          <div className="flex gap-1 items-center">
            <select
              value={displacementMin}
              onChange={(e) => setDisplacementMin(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">최소</option>
              {displacementOptions.map((d) => (
                <option key={d} value={d}>{d.toLocaleString()}</option>
              ))}
            </select>
            <span className="text-gray-500">~</span>
            <select
              value={displacementMax}
              onChange={(e) => setDisplacementMax(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">최대</option>
              {displacementOptions.map((d) => (
                <option key={d} value={d}>{d.toLocaleString()}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Mileage */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">주행거리 (만km)</label>
          <div className="flex gap-1 items-center">
            <select
              value={mileageMin}
              onChange={(e) => setMileageMin(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">최소</option>
              {mileageOptions.map((m) => (
                <option key={m} value={m}>{m}</option>
              ))}
            </select>
            <span className="text-gray-500">~</span>
            <select
              value={mileageMax}
              onChange={(e) => setMileageMax(e.target.value)}
              disabled={isDisabled}
              className="flex-1 border border-gray-300 rounded-md px-2 py-2 text-sm focus:ring-primary-500 focus:border-primary-500 disabled:bg-gray-100"
            >
              <option value="">최대</option>
              {mileageOptions.map((m) => (
                <option key={m} value={m}>{m}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      {isSearching && (
        <div className="mt-4">
          <div className="flex justify-between text-sm text-gray-600 mb-1">
            <span>Carmodoo에서 검색 중...</span>
            <span>{Math.round(searchProgress)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div
              className="bg-primary-600 h-2 rounded-full transition-all duration-200"
              style={{ width: `${searchProgress}%` }}
            />
          </div>
        </div>
      )}
    </div>
  );
}
