import { useState, useEffect } from 'react';

import { getFirstDatabase, getSecondDatabase, refreshDatabases } from 'src/db';
import { getData } from 'src/modules/map/regionData';
import { DbRegion } from './types';

const useRegionData = (regionId: number, dare: boolean = false) => {
  const [regionData, setRegionData] = useState<DbRegion | null>(null);
  const [avatars, setAvatars] = useState<string[] | null>(null);

  useEffect(() => {
    const fetchRegionData = async () => {
      const db = dare ? getSecondDatabase() : getFirstDatabase();
      const tableName = dare ? 'places' : 'regions';
      try {
        await getData(db, regionId, tableName, (data, avatars) => {
          setRegionData(data);
          setAvatars(avatars);
        });
      } catch (error) {
        console.error('Error fetching region data', error);
        refreshDatabases();
      }
    };

    fetchRegionData();
  }, [regionId]);

  return { regionData, avatars };
};

export default useRegionData;
