import type { AdminDatasetResult, AdminDatasetSummary } from "@xtablo/shared-types";
import { useEffect, useState } from "react";
import { adminApi } from "../lib/api";

function getErrorMessage(error: unknown, fallbackMessage: string) {
  if (typeof error === "object" && error !== null && "response" in error) {
    const response = error.response;
    if (
      typeof response === "object" &&
      response !== null &&
      "data" in response &&
      typeof response.data === "object" &&
      response.data !== null &&
      "error" in response.data &&
      typeof response.data.error === "string"
    ) {
      return response.data.error;
    }
  }

  return fallbackMessage;
}

export function useAdminDatasets() {
  const [datasets, setDatasets] = useState<AdminDatasetSummary[]>([]);
  const [selectedDatasetId, setSelectedDatasetId] = useState<string | null>(null);
  const [dataset, setDataset] = useState<AdminDatasetResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const loadDatasets = async () => {
      try {
        const response = await adminApi.get<{ datasets: AdminDatasetSummary[] }>("/admin/datasets");
        if (!isMounted) {
          return;
        }

        setDatasets(response.data.datasets);
        setSelectedDatasetId(
          (currentValue) => currentValue ?? response.data.datasets[0]?.id ?? null
        );
      } catch (error) {
        if (isMounted) {
          setError(getErrorMessage(error, "Failed to load admin datasets"));
          setIsLoading(false);
        }
      }
    };

    void loadDatasets();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    const loadDataset = async () => {
      if (!selectedDatasetId) {
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const response = await adminApi.get<AdminDatasetResult>(
          `/admin/datasets/${selectedDatasetId}`
        );

        if (!isMounted) {
          return;
        }

        setDataset(response.data);
      } catch (error) {
        if (isMounted) {
          setError(getErrorMessage(error, "Failed to load admin dataset"));
          setDataset(null);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    void loadDataset();

    return () => {
      isMounted = false;
    };
  }, [selectedDatasetId]);

  return {
    dataset,
    datasets,
    error,
    isLoading,
    selectedDatasetId,
    setSelectedDatasetId,
  };
}
