import { useCallback, useEffect, useState } from 'react';
import LoadFileForm from './LoadFileForm';
import { fetchConfig, loadTransactions } from '../../services/api.service';
import { useStore } from '../../store/AppStore';
import { useLoader } from '../../hooks/useLoader';

export default function LoadFilePage() {
  const { dispatch } = useStore();
  
  const [profiles, setProfiles] = useState<string[]>([]);
  const [servers, setServers] = useState<string[]>([]);
  const [defaultProfile, setDefaultProfile] = useState<string|undefined>(undefined);
  const [defaultServer, setDefaultServer] = useState<string|undefined>(undefined);

  const loadConfig = useCallback(async () => {
    const config = await fetchConfig();

    setProfiles(config.profiles);
    setServers(config.servers);
    setDefaultProfile(config.defaultProfile);    
    setDefaultServer(config.defaultServer);

    dispatch({
      type: 'UPDATE_CONFIG',
      payload: config
    });
  }, [setProfiles, setServers, setDefaultProfile, setDefaultServer]);

  useEffect(() => {
    loadConfig();
  }, [loadConfig]);  

  const { fn: handleSubmit, loading } = useLoader(async (csvFile: File, profile: string, server: string) => {    
    const data = await loadTransactions(csvFile, profile, server);

    dispatch({
      type: 'UPDATE_DATA',
      payload: {
        profile,
        server,
        ...data
      }
    });    

    dispatch({
      type: 'MOVE_STEP',
      payload: {
        offset: 1
      }
    });
  });

  return (
    <div className="columns mt-6">
      <div className="column is-6 is-offset-3">
        <div className="box">
          <h2 className="title is-4 has-text-centered">Import Transactions</h2>              
          <LoadFileForm 
            loading={loading}
            profiles={profiles} 
            servers={servers} 
            defaultProfile={defaultProfile} 
            defaultServer={defaultServer} 
            onSubmit={handleSubmit} />
        </div>
      </div>
    </div>
  );
}