import { useState, useEffect } from "react";
import { BarcodeLabelMaster, GetBarcodeLabelsParams } from "@/types/barcode";
import { barcodeApi } from "@/lib/api/barcodeApi";
import { useToast } from "@/hooks/use-toast";

export function useBarcodeList() {
  const [labels, setLabels] = useState<BarcodeLabelMaster[]>([]);
  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 fetchLabels = async () => {
    setIsLoading(true);
    try {
      const params: GetBarcodeLabelsParams = {
        page,
        limit,
        searchText,
        useYn: "Y",
        sortBy: "created_at",
        sortOrder: "DESC",
      };

      const response = await barcodeApi.getLabels(params);

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

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

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

  return {
    labels,
    total,
    page,
    limit,
    isLoading,
    refetch: fetchLabels,
    setPage,
    handleSearch,
  };
}
