import { useEffect, useState } from 'react';
import axios from 'axios';

export const useEntityTypes = (baseUrl) => {
  const [entities, setEntities] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch JSON:API resources on component mount
    fetchEntities().catch((err) => {
      console.error('Unexpected error fetching entity types:', err);
    });
  }, []);

  const fetchEntities = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await axios.get(baseUrl);
      if (response.data.links) {
        const entityTypes = extractEntityBundlesFromJsonapi(response.data);

        console.log('Setting entities state with:', entityTypes.length, 'entity types');
        setEntities(entityTypes);
      } else {
        console.error('Invalid JSON:API response format - missing links property');
        setError('Invalid JSON:API response format');
      }
    } catch (err) {
      console.error('Error fetching JSON:API resources:', err);
      setError(`Error fetching JSON:API resources: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const extractEntityBundlesFromJsonapi = (data) => {
    const links = data.links || {};
    const entities = {};

    for (const key in links) {
      if (!links[key] || typeof links[key] !== 'object') {
        console.warn(`Invalid link structure for ${key}, skipping`);
        continue;
      }

      const match = key.match(/^([a-z0-9_]+)--([a-z0-9_]+)$/);
      if (!match) continue;
      const [, entityType, bundle] = match;

      const href = links[key].href;
      if (!href) {
        console.warn(`Missing href for ${key}, skipping`);
        continue;
      }

      if (!entities[entityType]) entities[entityType] = [];
      entities[entityType].push({
        name: bundle,
        href: href
      });
    }

    // Convert to array format
    return Object.entries(entities).map(([name, bundles]) => ({
      name,
      bundles
    }));

  }

  return {
    entities,
    loading,
    error,
    fetchEntities
  };
};
