// 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 { 
  Controller, 
  useForm 
} from 'react-hook-form';

// components

import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import Selector from '../../common/formElements/Selector';
import TextInput from '../../common/formElements/TextInput';

// hooks

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

// functions

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

// constants

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

function EditLine(props) {
  
  const {
    accountNames,
    credits,
    debit,
    debits,
    line,
    onDelete,
    setTrigger,
    setUpdatedCredits,
    setUpdatedDebits,
    theLine,
    trigger
  } = 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) {

        credits[key] = getValues();
        setUpdatedCredits(credits);

      } else {

        debits[key] = getValues();
        setUpdatedDebits(debits);

      }

      setTrigger(trigger + 1); // This is used to force an immediate new rendering on Editor (see useEffect).

    } catch (e) {

      handleError(e, context, errorNumber);

    }

  };

  useEffect(() => {

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

    const runThis = async () => {

      if (accountNames) {

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

        setValue('account', account);
        setValue('amount', amount);
        setValue('pointer', pointer);
        setValue('statement', statement);
        setLoaded(true);

      }

    };

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

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

  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?';

    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>

          <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}
          />

          <div className="size-65 text-muted mb-2">statement date</div>

          <Controller
            control={control}
            name="statement"
            render={({ field }) => (
              <DatePicker
                className="form-control mb-3 p-3"
                dateFormat="yyyy-MM-dd"
                onChange={date => {
                  field.onChange(convertToServerTimezone(date));
                  onChange();
                }}
                placeholderText="select date..."
                selected={Date.parse(field.value)}
              />
            )}
          />

        </div>

        <DeleteConfirmationModal confirmModal={onDelete} />

      </>

    );

  } catch (e) {

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

  }

}

export default EditLine;