import { useState, useEffect } from "react";
import { ReportMaster, GetReportsParams } from "@/types/report";
import { reportApi } from "@/lib/api/reportApi";
import { useToast } from "@/hooks/use-toast";

export function useReportList() {
  const [reports, setReports] = useState<ReportMaster[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit] = useState(20);
  const [isLoading, setIsLoading] = useState(false);
  const [searchText, setSearchText] = useState("");
  const { toast } = useToast();

  const fetchReports = async () => {
    setIsLoading(true);
    try {
      const params: GetReportsParams = {
        page,
        limit,
        searchText,
        useYn: "Y",
        sortBy: "created_at",
        sortOrder: "DESC",
      };

      const response = await reportApi.getReports(params);

      if (response.success && response.data) {
        setReports(response.data.items);
        setTotal(response.data.total);
      }
    } catch (error: any) {
      console.error("리포트 목록 조회 에러:", error);
      toast({
        title: "오류",
        description: error.message || "리포트 목록을 불러오는데 실패했습니다.",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchReports();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, searchText]);

  const handleSearch = (text: string) => {
    setSearchText(text);
    setPage(1);
  };

  return {
    reports,
    total,
    page,
    limit,
    isLoading,
    refetch: fetchReports,
    setPage,
    handleSearch,
  };
}
