'use client';

import { useMemo } from 'react';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { ScrollableButtonGroup } from '@/components/atoms/ScrollableButtonGroup';
import { cn } from '@/lib/utils';

/** 분기 타입 */
export type Quarter = 'Q1' | 'Q2' | 'Q3' | 'Q4';

const QUARTER_OPTIONS = ['전체', 'Q1', 'Q2', 'Q3', 'Q4'] as const;

function quarterLabel(q: typeof QUARTER_OPTIONS[number]): string {
  return q === '전체' ? '전체' : `${q.replace('Q', '')}분기`;
}

interface YearQuarterFilterProps {
  /** 선택된 연도 */
  year: number;
  /** 선택된 분기 ('전체' 포함) */
  quarter: Quarter | '전체';
  /** 연도 변경 핸들러 */
  onYearChange: (year: number) => void;
  /** 분기 변경 핸들러 */
  onQuarterChange: (quarter: Quarter | '전체') => void;
  /** 연도 범위 [시작, 끝] (default: [현재-5, 현재]) */
  yearRange?: [number, number];
  /** '전체' 옵션 포함 여부 (default: true) */
  includeAll?: boolean;
  className?: string;
}

/**
 * 연도 Select + 분기 버튼 그룹 필터
 *
 * Controlled 컴포넌트. 연도/분기 state는 부모에서 관리.
 */
export function YearQuarterFilter({
  year,
  quarter,
  onYearChange,
  onQuarterChange,
  yearRange,
  includeAll = true,
  className,
}: YearQuarterFilterProps) {
  const currentYear = new Date().getFullYear();
  const [startYear, endYear] = yearRange ?? [currentYear - 5, currentYear];

  const yearOptions = useMemo(() => {
    const years: number[] = [];
    for (let y = endYear; y >= startYear; y--) {
      years.push(y);
    }
    return years;
  }, [startYear, endYear]);

  const quarters = includeAll ? QUARTER_OPTIONS : QUARTER_OPTIONS.slice(1);

  return (
    <div className={cn('flex items-center gap-2 flex-wrap min-w-0', className)}>
      <Select value={String(year)} onValueChange={(v) => onYearChange(Number(v))}>
        <SelectTrigger className="min-w-[100px] w-auto h-9 text-sm">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {yearOptions.map((y) => (
            <SelectItem key={y} value={String(y)}>
              {y}년
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <ScrollableButtonGroup>
        {quarters.map((q) => (
          <Button
            key={q}
            size="sm"
            variant={quarter === q ? 'default' : 'outline'}
            className="h-8 px-3 text-xs shrink-0"
            onClick={() => onQuarterChange(q)}
          >
            {quarterLabel(q)}
          </Button>
        ))}
      </ScrollableButtonGroup>
    </div>
  );
}
