import { useState } from "react";
import {
  exportService,
  ExportUserDataResponse,
} from "../services/exportService";
import { toast } from "sonner";

export const useExportUserData = () => {
  const [isExporting, setIsExporting] = useState(false);
  const [isLoadingUnits, setIsLoadingUnits] = useState(false);
  const [units, setUnits] = useState<unknown[]>([]);

  const getUnits = async (organizationId: string) => {
    if (!organizationId) {
      toast.error("Organization ID is required");
      return;
    }

    setIsLoadingUnits(true);
    try {
      const result = await exportService.getUnitsList(organizationId);
      if (result.success) {
        setUnits(result.data?.items || []);
        return result.data?.items || [];
      } else {
        toast.error(result.message);
        return [];
      }
    } catch (error: unknown) {
      toast.error("Failed to fetch units");
      return [];
    } finally {
      setIsLoadingUnits(false);
    }
  };

  const exportUserData = async (
    unitId: string,
    format: "xlsx" | "csv" = "xlsx"
  ): Promise<ExportUserDataResponse> => {
    if (!unitId) {
      const error = {
        success: false,
        message: "Unit ID is required",
        data: null,
      };
      toast.error(error.message);
      return error;
    }

    setIsExporting(true);

    try {
      const result = await exportService.exportUserData(unitId, format);

      if (result.success) {
        toast.success(
          `User data exported successfully as ${format.toUpperCase()}!`
        );
      } else {
        toast.error(result.message);
      }

      return result;
    } catch (error: unknown) {
      const errorResult = {
        success: false,
        message: (error as any)?.message || "Export failed. Please try again.",
        data: null,
      };
      toast.error(errorResult.message);
      return errorResult;
    } finally {
      setIsExporting(false);
    }
  };

  return {
    exportUserData,
    getUnits,
    isExporting,
    isLoadingUnits,
    units,
  };
};
