import React, { useState } from 'react';
import { Form, FormikProps } from 'formik';
import _ from 'lodash';
import Input from '../components/Input';
import Button from '../components/Button';
import Select from '../components/Select';
import Paper from '../components/Paper';
import useOptions from '../hooks/useOptions';

const WaybillForm: React.FC<FormikProps> = ({ setFieldValue, values }) => {
  const [recordsNumber, setRecordsNumber] = useState<number>(values.records.length);

  const handleAddRecord = () => setRecordsNumber(v => v + 1);

  const contractorOptions = useOptions('contractors', 'contractorId', values, setFieldValue);
  const productOptions = useOptions('products', 'productId', values, setFieldValue);

  return (
    <Form id="form">
      <Select
        name="contractorId"
        label="Контрагент"
        options={contractorOptions}
      />
      <Select
        name="operation"
        label="Операция"
        options={[
          { key: 'in', label: 'Приход' },
          { key: 'out', label: 'Расход' },
        ]}
      />
      <Button onClick={handleAddRecord}>+</Button>
      {_.times(recordsNumber).map(index => (
        <Paper>
          <Select
            name={`records.${index}.productId`}
            label="Товар"
            options={productOptions}
          />
          <Input
            name={`records.${index}.price`}
            type="number"
            label="Цена, $"
          />
          <Input
            name={`records.${index}.quantity`}
            type="number"
            label="Количество"
          />
          {values.records[index]?.price * values.records[index]?.quantity || 0}
        </Paper>
      ))}
    </Form>
  );
};

export default WaybillForm;
