import React from 'react';
import { Form, FormikProps } from 'formik';
import _ from 'lodash';
import moment from 'moment';
import Input from '../../components/Input';
import Button from '../../components/Button';
import Select from '../../components/Select';
import Paper from '../../components/Paper';
import hooks from '../../hooks/useAPIClient';
import { Product, Contractor, Waybill } from '../types';


const mapper = (item: Product | Contractor) => ({ key: item._id, label: item.name });


const WaybillForm: React.FC<FormikProps<Waybill>> = ({ setFieldValue, values }) => {
  const { data: products } = hooks.products.useList();
  const { data: contractors } = hooks.contractors.useList();

  if (!values.date) setFieldValue('date', moment().format('YYYY-MM-DD'));
  if (!values.contractorId && contractors?.length) setFieldValue('contractorId', contractors[0]._id);

  const handleAddRecord = () => setFieldValue('records', [...values.records, {
    productId: _.map(products, '_id').reduce((acc, id) => {
      return acc || (!_.map(values.records, 'productId').includes(id) && id);
    }, false),
    price: '',
    quantity: 1,
  }]);

  const handleRemoveRecord = (index: number) => () => {
    const records = [...values.records];
    records.splice(index, 1);
    setFieldValue('records', records);
  };

  return (
    <Form id="form">
      <Select
        name="contractorId"
        label="Контрагент"
        options={contractors?.map(mapper)}
      />
      <div className="grid grid-cols-2">
        <Select
          name="operation"
          label="Операция"
          options={[
            { key: 'in', label: 'Приход' },
            { key: 'out', label: 'Расход' },
          ]}
        />
        <Input name="date" type="date" label="Дата" />
      </div>
      {values.records.map((record, index) => (
        <Paper variant="outlined" className="my-4 md:mx-4" key={`${index}-${record.productId}`}>
          <Select
            name={`records.${index}.productId`}
            label="Товар"
            options={products?.map(mapper)}
            required
          />
          <div className="grid grid-cols-3">
            <Input
              name={`records.${index}.price`}
              type="number"
              label="Цена"
              required
            />
            <Input
              name={`records.${index}.quantity`}
              type="number"
              label="Количество"
              required
            />
            <div className="flex justify-end items-end">
              <Button onClick={handleRemoveRecord(index)} size="sm" variant="outlined">Удалить</Button>
            </div>
          </div>
        </Paper>
      ))}
      <Button onClick={handleAddRecord} variant="outlined" size="sm">Добавить товар</Button>
    </Form>
  );
};

export default WaybillForm;
