// The reason this runs standalone is because it is called from Editor.jsx, but the location is inside a Form, so it has to run independently.

import { 
  useEffect, 
  useState 
} from 'react';
import { useOutletContext } from 'react-router-dom';
import { useForm } from 'react-hook-form';

// components

import DateInput from '../../common/formElements/DateInput';
import Selector from '../../common/formElements/Selector';
import TextInput from '../../common/formElements/TextInput';
import Warning from '../../common/display/Warning';

// hooks

import useDeleteLogic from '../../hooks/utilities/useDeleteLogic';

// functions

import { validateUUID } from '../../../services/utils';

// constants

  const nowRunning = 'accounting/transactions/Lines.jsx';
  const errorNumber = 581;

function EditLine(props) {
  
  const {
    accountNames,
    credits,
    debit,
    debits,
    line,
    onDelete,
    setUpdatedCredits,
    setUpdatedDebits,
    theLine
  } = props;

  const { 
    control,
    getValues,
    register,
    setValue 
  } = useForm();

  const { handleError } = useOutletContext();
  
  const [loaded, setLoaded] = useState();

  const {
    DeleteConfirmationModal,
    DeleteIcon
  } = useDeleteLogic();  

  const key = line - 1;

  const onChange = async () => {

    const context = `${nowRunning}.onChange`;

    try {

      if (!debit) {

        const updatedCredits = [...credits];
        updatedCredits[key] = getValues();
        setUpdatedCredits(updatedCredits);

      } else {

        const updatedDebits = [...debits];
        updatedDebits[key] = getValues();
        setUpdatedDebits(updatedDebits);

      }



    } catch (e) {

      handleError(e, context, errorNumber);

    }

  };

  useEffect(() => {

    const context = `${nowRunning}.useEffect`;

    const runThis = async () => {

      if (accountNames) {

        const {
          account,
          amount,
          pointer,
          statement
        } = theLine;

        setValue('account', accountNames[account] ? account : null);
        setValue('amount', amount);
        setValue('pointer', pointer);
        setValue('statement', statement);
        setLoaded(true);

      }

    };

    runThis()
      .catch(e => handleError(e, context, errorNumber));

  }, [accountNames, handleError, setValue, theLine]);

  try {

    if (!loaded || !accountNames) return null;

    let lineType = debit ? 'debit' : 'credit';
    const line = +key + 1;
    const deleteMessage = 'Are you sure you want to delete this ' + lineType + ' line?';
    const validateAccount = validateUUID(getValues('account'));

    return (

      <>        

        <div className="border-gray-2 mt-3 mb-3 p-3">

          <div className="size-65 floats">

            <div className="float-right ml-05 mb-3">
              <DeleteIcon
                deleteMessage={deleteMessage}
                deletePayload={{ line, lineType }}
                deletePrompt="delete line"
              />
            </div>

            {lineType} line {line}

          </div>

          {!validateAccount && (<Warning message="the company ID has to be updated for this transaction line to repost" />)}

          <Selector
            inputName="account"
            label="account"
            onChange={onChange}
            register={register}
            values={accountNames}
          />

          <TextInput
            inputName="amount"
            label="amount"
            onChange={onChange}
            placeholder="enter an amount here..."
            register={register}
          />

          <TextInput
            inputName="pointer"
            label="pointer 1"
            onChange={onChange}
            placeholder="enter a valid pointer here..."
            register={register}
          />          

          <DateInput
            control={control}
            defaultTimezone={localStorage.getItem('uniti_serverTimezone') || 'America/Los_Angeles'}
            inputName="statement"
            label="statement date"
            onChange={onChange}
            required={true}
            sm={6}
            xs={12}
          />

        </div>

        <DeleteConfirmationModal confirmModal={onDelete} />

      </>

    );

  } catch (e) {

    handleError(e, nowRunning, errorNumber);
    return null;

  }

}

export default EditLine;