import { useState, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
  SearchFilter,
  DEFAULT_SEARCH_FILTER,
  getDateRangeFromPeriod,
  getFilterDisplayText
} from '@/types/filter';

interface UseSearchFilterOptions {
  initialFilter?: SearchFilter;
  storageKey?: string; // 로컬 스토리지에 저장할 키
  onFilterChange?: (filter: SearchFilter) => void;
}

interface UseSearchFilterReturn {
  filter: SearchFilter;
  setFilter: (filter: SearchFilter) => void;
  resetFilter: () => void;
  isModalOpen: boolean;
  openModal: () => void;
  closeModal: () => void;
  handleFilterConfirm: (newFilter: SearchFilter) => void;
  getDisplayText: () => string;
  isFilterActive: boolean; // 기본값과 다른지 확인
}

export const useSearchFilter = (options: UseSearchFilterOptions = {}): UseSearchFilterReturn => {
  const { t } = useTranslation();
  const {
    initialFilter = DEFAULT_SEARCH_FILTER,
    storageKey,
    onFilterChange
  } = options;
  
  const isInitialMount = useRef(true);

  // 로컬 스토리지에서 저장된 필터 로드
  const loadStoredFilter = useCallback((): SearchFilter => {
    if (!storageKey) return initialFilter;
    
    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        const parsedFilter = JSON.parse(stored);
        // Date 객체 복원
        if (parsedFilter.dateRange) {
          parsedFilter.dateRange = {
            startDate: new Date(parsedFilter.dateRange.startDate),
            endDate: new Date(parsedFilter.dateRange.endDate)
          };
        }
        return { ...initialFilter, ...parsedFilter };
      }
    } catch (error) {
      console.warn('Failed to load stored filter:', error);
    }
    
    return initialFilter;
  }, [initialFilter, storageKey]);

  const [filter, setFilterState] = useState<SearchFilter>(loadStoredFilter);
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 필터 저장
  const saveFilter = useCallback((newFilter: SearchFilter) => {
    if (storageKey) {
      try {
        localStorage.setItem(storageKey, JSON.stringify(newFilter));
      } catch (error) {
        console.warn('Failed to save filter to storage:', error);
      }
    }
  }, [storageKey]);

  // 필터 설정
  const setFilter = useCallback((newFilter: SearchFilter) => {
    // 날짜 범위가 없고 period가 custom이 아닌 경우 자동 계산
    const finalFilter = {
      ...newFilter,
      dateRange: newFilter.dateRange || getDateRangeFromPeriod(newFilter.period)
    };

    //setFilterState(finalFilter);
    //saveFilter(finalFilter);
    //onFilterChange?.(finalFilter);
  }, [saveFilter, onFilterChange]);

  // 필터 초기화
  const resetFilter = useCallback(() => {
    setFilter(initialFilter);
  }, [initialFilter, setFilter]);

  // 모달 제어
  const openModal = useCallback(() => {
    setIsModalOpen(true);
  }, []);

  const closeModal = useCallback(() => {
    setIsModalOpen(false);
  }, []);

  // 모달에서 확인 버튼 클릭 시
  const handleFilterConfirm = useCallback((newFilter: SearchFilter) => {
    setFilter(newFilter);
    closeModal();
  }, [setFilter, closeModal]);

  // 표시 텍스트 가져오기
  const getDisplayText = useCallback(() => {
    return getFilterDisplayText(filter, t);
  }, [filter, t]);

  // 기본값과 다른지 확인
  const isFilterActive = useCallback(() => {
    return JSON.stringify(filter) !== JSON.stringify(DEFAULT_SEARCH_FILTER);
  }, [filter])();

  // 초기 로드 시 필터 변경 콜백 호출
  useEffect(() => {
    if (isInitialMount.current && onFilterChange) {
      onFilterChange(filter);
      isInitialMount.current = false;
    }
  }, [filter, onFilterChange]);

  return {
    filter,
    setFilter,
    resetFilter,
    isModalOpen,
    openModal,
    closeModal,
    handleFilterConfirm,
    getDisplayText,
    isFilterActive
  };
};