import { useCallback, useState } from "react";
import type { ImportOptions } from "../../types/api";
import classNames from "classnames";

export type ImportBarProps = {
  onSubmit: (opts: ImportOptions) => void;
  onStartOver: () => void;
  loading: boolean;  
};

export default function ImportBar({ onSubmit, loading, onStartOver }: ImportBarProps) {
  const [formData, setFormData] = useState<ImportOptions>({ mode: 'add' });

  
  const handleSubmit = useCallback((e: React.FormEvent) => {
    e.preventDefault();



    onSubmit(formData);
  }, [formData, onSubmit]);

  const changeMode = useCallback((mode: ImportOptions['mode']) => {
    if (mode === 'add') {
      setFormData({ ...formData, mode });
    }

    else {
      setFormData({ mode });
    }
  }, [formData, setFormData]);

  return (
    <form onSubmit={handleSubmit}>
      <div className="field">
        <label className="label">Import mode</label>
        <div className="control">
          <div className="buttons has-addons is-left">            
            <button 
              type="button"
              className={classNames("button", { 'is-primary': formData.mode === 'add', 'is-selected': formData.mode === 'add'})}
              onClick={() => changeMode('add')}>Add</button>
            <button 
              type="button"              
              className={classNames("button", { 'is-primary': formData.mode === 'import', 'is-selected': formData.mode === 'import'})}
              onClick={() => changeMode('import')}>Import</button>
          </div>
        </div>
      </div>

      {formData.mode === 'add' && <div className="field">
        <label className="label">Additional options</label>
        <div className="control">
          <label className="checkbox">
            <input 
              type="checkbox" 
              checked={formData.learnCategories}
              onChange={e => setFormData({ ...formData, learnCategories: e.target.checked})}/> Learn categories
          </label>          
        </div>
        <div className="control">
          <label className="checkbox">
            <input 
              type="checkbox" 
              checked={formData.runTransfers}
              onChange={e => setFormData({ ...formData, runTransfers: e.target.checked})}/> Run transfers
          </label>
        </div>
      </div>}

      <div className="field mt-5">
        <div className="control">
          <button 
            type="submit" 
            disabled={loading}
            className={classNames("button", "is-link", "is-fullwidth", { 'is-loading': loading })}>Submit transactions
          </button>          
        </div>
      </div>
      <div className="field">
        <div className="control">
          <button 
              type="button"             
              className="button is-secondary is-fullwidth"
              onClick={onStartOver}>Start over again
          </button>
        </div>
      </div>
    </form>
  ); 
}