import useSWR from 'swr';
import { getRecords, createRecord, updateRecord, deleteRecord } from '../lib/api';

export function useRecords(month, type = 'all') {
  const key = month ? ['records', month, type] : null;

  const { data, error, isLoading, mutate } = useSWR(
    key,
    () => getRecords(month, type),
    {
      revalidateOnFocus: false,
      dedupingInterval: 5000,
    }
  );

  // 乐观更新：添加记录
  const addRecord = async (recordData) => {
    const newRecord = await createRecord(recordData);
    mutate(
      (current) => (current ? [...current, newRecord] : [newRecord]),
      { revalidate: false }
    );
    return newRecord;
  };

  // 乐观更新：更新记录
  const editRecord = async (id, recordData) => {
    await updateRecord(id, recordData);
    mutate(
      (current) =>
        current?.map((r) => (r.id === id ? { ...r, ...recordData } : r)),
      { revalidate: false }
    );
  };

  // 乐观更新：删除记录
  const removeRecord = async (id) => {
    await deleteRecord(id);
    mutate(
      (current) => current?.filter((r) => r.id !== id),
      { revalidate: false }
    );
  };

  return {
    records: data || [],
    isLoading,
    error,
    mutate,
    addRecord,
    editRecord,
    removeRecord,
  };
}
