import { useState, useEffect } from 'react';

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

const useRegionData = (regionId: number, dare: boolean = false, enabled: boolean = true) => {
  const [regionData, setRegionData] = useState<DbRegion | null>(null);
  const [avatars, setAvatars] = useState<string[] | null>(null);
  const [db1, setDb1] = useState<SQLiteDatabase | null>(null);
  const [db2, setDb2] = useState<SQLiteDatabase | null>(null);

  useEffect(() => {
    if (!enabled) return;
    const loadDatabases = async () => {
      const firstDb = await getFirstDatabase();
      const secondDb = await getSecondDatabase();

      setDb1(firstDb);
      setDb2(secondDb);
    };

    if (!db1 || !db2) {
      loadDatabases();
    }
  }, [db1, db2, enabled]);

  useEffect(() => {
    if (!enabled) return;
    const fetchRegionData = async () => {
      const db = dare ? db2 : db1;
      const tableName = dare ? 'places' : 'regions';
      if (!db) return;

      try {
        await getData(db, regionId, tableName, (data, avatars) => {
          setRegionData(data);
          setAvatars(avatars);
        });
      } catch (error) {
        console.error('Error fetching region data', error);
        refreshDatabases();
      }
    };

    fetchRegionData();
  }, [regionId, db1, db2, enabled]);

  return { regionData, avatars };
};

export default useRegionData;
