'use client';

import { useEffect, useState } from 'react';
import { apiClient } from '@/utils/api';
import { usingBrowserDb } from '@/utils/env';
import { listUserDatasetEntries } from '@/utils/storage/datasetStorage';
import { useAuth } from '@/contexts/AuthContext';

export default function useDatasetList() {
  const [datasets, setDatasets] = useState<string[]>([]);
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const { status: authStatus } = useAuth();

  const refreshDatasets = () => {
    if (authStatus !== 'authenticated') {
      setDatasets([]);
      setStatus('idle');
      return;
    }
    setStatus('loading');
    if (usingBrowserDb) {
      const entries = listUserDatasetEntries();
      entries.sort((a, b) => a.name.localeCompare(b.name));
      setDatasets(entries.map(entry => entry.name));
      setStatus('success');
      return;
    }

    apiClient
      .get('/api/datasets/list')
      .then(res => res.data)
      .then(data => {
        console.log('Datasets:', data);
        data.sort((a: string, b: string) => a.localeCompare(b));
        setDatasets(data);
        setStatus('success');
      })
      .catch(error => {
        console.error('Error fetching datasets:', error);
        setStatus('error');
      });
  };
  useEffect(() => {
    if (authStatus !== 'authenticated') {
      setDatasets([]);
      setStatus('idle');
      return;
    }
    refreshDatasets();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authStatus]);

  return { datasets, setDatasets, status, refreshDatasets };
}
