import { useEffect, useState } from 'react';
import { Calendar } from 'lucide-react';
import api from '../api';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

export interface CycleOption {
  year: number;
  month: number;
  label: string;
  count: number;
  total: number;
}

interface Props {
  value: { year: number; month: number } | null;
  onChange: (cycle: { year: number; month: number } | null) => void;
}

export default function BillingCycleSelector({ value, onChange }: Props) {
  const [cycles, setCycles] = useState<CycleOption[]>([]);

  useEffect(() => {
    api.get('/transactions/cycles').then((r) => setCycles(r.data));
  }, []);

  const selectedKey = value ? `${value.year}-${value.month}` : 'all';

  return (
    <div className="flex items-center gap-2">
      <Calendar className="w-4 h-4 text-muted-foreground" />
      <Select
        value={selectedKey}
        onValueChange={(val) => {
          if (val === 'all') {
            onChange(null);
          } else {
            const [y, m] = val.split('-').map(Number);
            onChange({ year: y, month: m });
          }
        }}
      >
        <SelectTrigger className="w-[180px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All time</SelectItem>
          {cycles.map((c) => (
            <SelectItem key={`${c.year}-${c.month}`} value={`${c.year}-${c.month}`}>
              {c.label} ({c.count})
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
}
