import Table, { ColumnProps } from 'antd/lib/table';
import React from 'react';
import { Tag, Button, Tooltip, Input, InputNumber, Icon  } from 'antd';
import {
  ISizeWiseQuantites,
  IQuantitiesUpdate,
  MasterPoCharacteristicEnum,
  OrderQtyTypeQuantitiesDetailsResponse,
  IstartEndIndex
} from '@brandix-apps/shared-models/production-planning';
import './shared-utils-po-qty-handler.css';

import {
  IAdditionalDetails,
  AdditionCreationDetails,
  AdditionalCreateContext
} from '@brandix-apps/pages/production-planning-service/production-planning-service-components/additional-summary-context';
import { FormattedMessage } from 'react-intl';

export enum DisplayType {
  value,
  summary
}

/* eslint-disable-next-line */
export interface Props { }

export interface State { }
export class PoDetailQuantityHandler extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {};
  }

  /**
   *  It is a Helper function which converts the components state data to display in the Table
   * @param   $   IAdditionalDetails state data
   * @returns Map<string, ImapQuantitiesDetailsResponse>
   * @since   1.0
   * @version 1.0
   */

  public getSummaryColorMap(
    poDetailSizeQuantities: IAdditionalDetails
  ): Map<string, OrderQtyTypeQuantitiesDetailsResponse> {
    const colorQuantities = new Map<string, any>();
    const verticaltotalQuantites = new Map<string, any>();
    for (const [key, value] of poDetailSizeQuantities.allpoQuanties.entries()) {
      for (const podetailsnew of value) {
        for (const [childkey, podetail] of podetailsnew.keymap.entries()) {
          const keyrole = key + podetail.schedule + podetail.color;
          const sizeQty = new OrderQtyTypeQuantitiesDetailsResponse();
          sizeQty.schedule = podetail.schedule;
          sizeQty.size = podetail.size;
          sizeQty.color = podetail.color;
          sizeQty.quantity = podetail.quantity;
          sizeQty.rowindex = podetail.rowindex;
          sizeQty.mainExcessPercentage = poDetailSizeQuantities.excessRatio;
          if (!colorQuantities.has(keyrole)) {
            colorQuantities.set(keyrole, { total: { quantity: 0 } });
          }
          if (colorQuantities.get(keyrole)[sizeQty.size]) {
            colorQuantities.get(keyrole)[sizeQty.size].quantity =
              colorQuantities.get(keyrole)[sizeQty.size].quantity +
              Number(sizeQty.quantity);
          } else {
            colorQuantities.get(keyrole)[sizeQty.size] = {
              quantity: Number(sizeQty.quantity)
            };
          }
          colorQuantities.get(keyrole)['masterPoDetailsId'] =
            podetail.orderQuantityUpdateDetailsId;
          colorQuantities.get(keyrole)['color'] = sizeQty.color;
          colorQuantities.get(keyrole)['schedule'] = podetail.schedule;
          if (key == 'Extra Shipment') {
            if (podetail.rowExcesspercentage == 0) {
              colorQuantities.get(keyrole)['excessvalue'] =
                poDetailSizeQuantities.excessRatio;
            } else {
              colorQuantities.get(keyrole)['excessvalue'] =
                podetail.rowExcesspercentage;
            }
            // if (poDetailSizeQuantities.excessRatio) {
            //   colorQuantities.get(keyrole)['excessvalue'] =
            //     poDetailSizeQuantities.excessRatio;
            // } else {
            //   colorQuantities.get(keyrole)['excessvalue'] = 0;
            // }
          }
          colorQuantities.get(keyrole)['rowindex'] = podetail.rowindex;
          colorQuantities.get(keyrole)['key'] = key;
          colorQuantities.get(keyrole)['sampleValue'] = podetail.sampleValue;
          colorQuantities.get(keyrole)['total'].quantity =
            colorQuantities.get(keyrole)['total'].quantity +
            Number(podetail.quantity);
        }
      }
    }

    return colorQuantities;
  }

  /**
   *  It is a Helper function which converts the components state data to display total of order Qty's in the Table
   * @param   $   IAdditionalDetails state data
   * @returns Map<string, ImapQuantitiesDetailsResponse>
   * @since   1.0
   * @version 1.0
   */
  public getSummaryColorMaptotalDetails(
    poDetailSizeQuantities: IAdditionalDetails
  ): Map<string, OrderQtyTypeQuantitiesDetailsResponse> {
    const colorQuantities = new Map<string, any>();
    for (const [key, value] of poDetailSizeQuantities.allpoQuanties.entries()) {
      //if(key != MasterPoCharacteristicEnum['OriginalQuantity']){
      for (const podetailsnew of value) {
        for (const [childkey, podetail] of podetailsnew.keymap.entries()) {
          const sizeQty = new OrderQtyTypeQuantitiesDetailsResponse();
          sizeQty.schedule = podetail.schedule;
          sizeQty.size = podetail.size;
          sizeQty.color = podetail.color;
          sizeQty.quantity = podetail.quantity;
          sizeQty.rowindex = podetail.rowindex;

          const datavertical = new OrderQtyTypeQuantitiesDetailsResponse();
          datavertical.schedule = podetail.schedule;
          datavertical.size = podetail.size;
          datavertical.color = podetail.color;
          datavertical.total = { quantity: 0 };
          datavertical.quantity = podetail.quantity;
          datavertical.rowindex = podetail.rowindex;
          const keytotal = 'verticaltotal' + podetail.schedule + podetail.color;
          if (colorQuantities.has(keytotal)) {
            if (colorQuantities.get(keytotal)[sizeQty.size]) {
              colorQuantities.get(keytotal)[sizeQty.size].quantity =
                colorQuantities.get(keytotal)[sizeQty.size].quantity +
                Number(sizeQty.quantity);
            } else {
              colorQuantities.get(keytotal)[sizeQty.size] = {
                quantity: Number(sizeQty.quantity)
              };
            }

            colorQuantities.get(keytotal)['total'].quantity =
              colorQuantities.get(keytotal)['total'].quantity +
              Number(podetail.quantity);
            colorQuantities.get(keytotal)['key'] = 'Total Quantity';
          } else {
            colorQuantities.set(keytotal, datavertical);
            colorQuantities.get(keytotal)[sizeQty.size] = {
              quantity: Number(sizeQty.quantity)
            };
            colorQuantities.get(keytotal)['key'] = 'Total Quantity';
            colorQuantities.get(keytotal)['total'].quantity = Number(sizeQty.quantity);
          }
        }
      }
      //}
    }

    return colorQuantities;
  }

  /**
   *  It is a Helper function to return sizes
   * @param   $  ImapQuantitiesDetailsResponse
   * @returns sizes(Set<string>)
   * @since   1.0
   * @version 1.0
   */
  public getSizes(poDetailSizeQuantities: ISizeWiseQuantites[]): Set<string> {
    const sizes: Set<string> = new Set<string>();
    for (const podetail of poDetailSizeQuantities) {
      sizes.add(podetail.size);
    }
    return sizes;
  }

  /**
   *  It is a Helper function which renders the table
   * @param   $   IAdditionalDetails state data, Colors and orderqty's and sizes information
   * @returns Map<string, ImapQuantitiesDetailsResponse>
   * @since   1.0
   * @version 1.0
   */
  public getDisplayTable(
    masterpodetails: IAdditionalDetails,
    colorQuantities: any,
    sizes: Set<string>,
    diplayType: DisplayType
  ) {
    if (colorQuantities.size > 0 && sizes.size > 0) {
      /*Map to construct data based on key */
      const colspanTypeMap = new Map<string, IstartEndIndex>();
      const dataStore = Array.from(colorQuantities.values());
      /* Map to get orderQuantity Types to merge the row span to Zero for repeated keys */
      dataStore.map((value: any, index) => {
        const qtyTypeKey = value.key;
        const scheduleKey = value.key + '@' + value.schedule;
        colspanTypeMap.set(
          qtyTypeKey,
          colspanTypeMap.has(qtyTypeKey)
            ? {
              start: colspanTypeMap.get(qtyTypeKey).start,
              end: colspanTypeMap.get(qtyTypeKey).end + 1
            }
            : { start: index, end: 1 }
        );
        colspanTypeMap.set(
          scheduleKey,
          colspanTypeMap.has(scheduleKey)
            ? {
              start: colspanTypeMap.get(scheduleKey).start,
              end: colspanTypeMap.get(scheduleKey).end + 1
            }
            : { start: index, end: 1 }
        );
      });
      const columnInfo: ColumnProps<any>[] = [];
      let uniqueId = 0;
      const TemplateColumn: ColumnProps<any> = {
        title: <FormattedMessage id="components.additionalQuantity.action" />,
        width: 150,
        dataIndex: 'key',
        fixed: 'left',
        render: (value, record, index) => {
          const arraylabel = [];
          arraylabel.push(value);
          const obj: any = {
            children: (
              <div className='align-left'> 
                {this.deleteAction(value, diplayType, masterpodetails, record)}
              </div>
            ),
            props: {}
          };
          // if(colspanTypeMap.get(type).start < colspanTypeMap.get(type).end)
          // {
          if (index === colspanTypeMap.get(value).start) {
            obj.props.rowSpan = colspanTypeMap.get(value).end;
          } else {
            obj.props.rowSpan = 0;
          }
          return obj;
        }
      };
      const scheduleColumn: ColumnProps<any> = {
        title: <FormattedMessage id="components.additionalQuantity.schedule" />,
        width: 100,
        dataIndex: 'schedule',
        render: (value, row, index) => {
          const obj: any = {
            children: <div className='align-left'>{value}</div>,
            props: {}
          };
          // if(colspanTypeMap.get(row.key + "@" + value).start < colspanTypeMap.get(row.key + "@" + value).end){
          /* It checks row wise key and start and end of the key count  and makes row span 0*/
          if (index === colspanTypeMap.get(row.key + '@' + value).start) {
            obj.props.rowSpan = colspanTypeMap.get(row.key + '@' + value).end;
          } else {
            obj.props.rowSpan = 0;
          }
          return obj;
        }
      };
      const colorColumn: ColumnProps<any> = {
        title: <FormattedMessage id="components.additionalQuantity.color" />,
        dataIndex: 'color',
        width: 100,
        key: 'po_details_id',
        render: value => <div className='align-left'> <a>{value}</a></div>
      };
      const excessColumn: ColumnProps<any> = {
        title: <FormattedMessage id="components.additionalQuantity.excess" />,
        dataIndex: 'excessvalue',
        width: 100,
        render: (sizevalue: any, record: any) =>
          this.excessrenderValue(sizevalue, diplayType, masterpodetails, record)
      };
      const totalColumn: ColumnProps<any> = {
        title: <FormattedMessage id="components.additionalQuantity.total" />,
        dataIndex: 'total',
        width: 100,
        render: value =><div className='align-right'> <a>{Math.floor(value.quantity)}</a></div>
      };
      columnInfo.push(TemplateColumn);
      columnInfo.push(scheduleColumn);
      columnInfo.push(colorColumn);
      columnInfo.push(excessColumn);
      columnInfo.push(totalColumn);
      for (const size of Array.from(sizes.values())) {
        const sizeColumn = {
          title: size,
          width: 100,
          dataIndex: size,
          render: (sizevalue: any, record: any) =>
            this.renderValue(
              sizevalue,
              diplayType,
              masterpodetails,
              size,
              record
            )
        };
        columnInfo.push(sizeColumn);
      }

      const parentColumn = [
        {
          children: columnInfo
        }
      ];

      return (
        <Table
          size="small"
          columns={columnInfo}
          className="mainTable"
          scroll={{ x: 1024, y: 1000 }}
          style={{ minWidth: '500px', maxHeight: '100%' }}
          dataSource={dataStore}
          bordered
          pagination={false}
          rowKey={record => {
            if (!record.__uniqueId) record.__uniqueId = ++uniqueId;
            return record.__uniqueId;
          }}
        />
      );
    }
  }

  /**
   *  It is a Helper function to call Provider function getValue to update state
   * @param   $  ImapQuantitiesDetailsResponse
   * @returns sizes(Set<string>)
   * @since   1.0
   * @version 1.0
   */
  private renderValue(
    value: any,
    type: DisplayType,
    masterpodetails: IAdditionalDetails,
    size?: string,
    record?: any
  ) {
    if (typeof value != 'undefined') {
      if (record.key == 'Original Quantity' || record.key == 'Total Quantity'      ) {
        return (
          <div>
            <Input
              defaultValue={value.quantity}
              key={value.quantity}
              readOnly
              style={{textAlign: "right"}}
            />
          </div>
        );
      } else if (record.key == 'Extra Shipment') {
        return (
          <div>
            <InputNumber
              min={0}
              max={9999999}
              maxLength={7}
              parser={value => value.replace(/[^0-9]/g, '')}
              value={value.quantity}
              onChange={e => masterpodetails.getValue(e, size, record, value)}
            />
          </div>
        );
      } else {
        return (
          <div>
            <InputNumber
              min={0}
              max={999}
              maxLength={3}
              parser={value => value.replace(/[^0-9]/g, '')}
              value={value.quantity}
              onChange={e => masterpodetails.getValue(e, size, record, value)}
            />
          </div>
        );
      }
    }
  }

  /**
   *  It is a Helper function to call Provider function excessrenderValue to update state
   * @param   $  ImapQuantitiesDetailsResponse
   * @returns sizes(Set<string>)
   * @since   1.0
   * @version 1.0
   */
  private excessrenderValue(
    value: any,
    type: DisplayType,
    masterpodetails: IAdditionalDetails,
    size?: any,
    record?: any
  ) {
    if (typeof value != 'undefined') {
      if (size.key == 'Extra Shipment') {
        return (
          <div className='align-right'> 
            <InputNumber
              min={0}
              max={999}
              maxLength={3}
              parser={value => value.replace(/[^0-9]/g, '')}
              defaultValue={value}
              onChange={e =>
                masterpodetails.getExcessvalue(e, size, record, value)
              }
            />
          </div>
        );
      }
    }
  }

  /**
   *  It is a Helper function to call Provider function deleteAction to update state
   * @param   $  ImapQuantitiesDetailsResponse
   * @returns sizes(Set<string>)
   * @since   1.0
   * @version 1.0
   */

  private deleteAction(
    value: any,
    type: DisplayType,
    masterpodetails: IAdditionalDetails,
    record?: any
  ) {
    if (typeof value != 'undefined') {
      return (
        <div>
          <p id="displayAction">{value}</p>
          {
            record.key != 'CUTTING_WASTAGE' &&
            record.key != 'Extra Shipment' &&
            record.key != 'Original Quantity' &&
            record.key != 'Total Quantity' ? (
              <Tooltip placement="top" title={<FormattedMessage id="common.delete" /> }>
                <Icon className={'viewSamplTypeIcon'} type="delete" theme="filled"
                  onClick={e => masterpodetails.deleteItem(value)}
                  style={{ color: '#f70404', fontSize: '21px',float: 'right' }}
                />
              </Tooltip>
            ) : (
              ''
            )}
        </div>
      );
    }
  }

  /**
   *  It is a Helper function which renders the table with Total of Order Quantites
   * @param   $   IAdditionalDetails state data, Colors and orderqty's and sizes information
   * @returns Map<string, ImapQuantitiesDetailsResponse>
   * @since   1.0
   * @version 1.0
   */
  public getTotalDisplayTable(
    masterpodetails: IAdditionalDetails,
    colorQuantities: any,
    sizes: Set<string>,
    diplayType: DisplayType
  ) {
    if (colorQuantities.size > 0 && sizes.size > 0) {
      const colspanTypeMap = new Map<string, IstartEndIndex>();
      const dataStore = Array.from(colorQuantities.values());
      dataStore.map((value: any, index) => {
        const qtyTypeKey = value.key;
        const scheduleKey = value.key + '@' + value.schedule;
        colspanTypeMap.set(
          qtyTypeKey,
          colspanTypeMap.has(qtyTypeKey)
            ? {
              start: colspanTypeMap.get(qtyTypeKey).start,
              end: colspanTypeMap.get(qtyTypeKey).end + 1
            }
            : { start: index, end: 1 }
        );
        colspanTypeMap.set(
          scheduleKey,
          colspanTypeMap.has(scheduleKey)
            ? {
              start: colspanTypeMap.get(scheduleKey).start,
              end: colspanTypeMap.get(scheduleKey).end + 1
            }
            : { start: index, end: 1 }
        );
      });
      const columnInfo: ColumnProps<any>[] = [];
      let uniqueId = 0;
      const TemplateColumn: ColumnProps<any> = {
        dataIndex: 'key',
        width: 150,
        render: (value, record, index) => {
          const obj: any = {
            children: (
              <div>
                {this.deleteAction(value, diplayType, masterpodetails, record)}
              </div>
            ),
            props: {}
          };
          // if(colspanTypeMap.get(type).start < colspanTypeMap.get(type).end)
          // {
          if (index === colspanTypeMap.get(value).start) {
            obj.props.rowSpan = colspanTypeMap.get(value).end;
          } else {
            obj.props.rowSpan = 0;
          }
          return obj;
        }
      };
      const scheduleColumn: ColumnProps<any> = {
        dataIndex: 'schedule',
        width: 100,
        render: (value, row, index) => {
          const obj: any = {
            children: value,
            props: {}
          };
          // if(colspanTypeMap.get(row.key + "@" + value).start < colspanTypeMap.get(row.key + "@" + value).end){
          if (index === colspanTypeMap.get(row.key + '@' + value).start) {
            obj.props.rowSpan = colspanTypeMap.get(row.key + '@' + value).end;
          } else {
            obj.props.rowSpan = 0;
          }
          return obj;
        }
      };
      const colorColumn: ColumnProps<any> = {
        dataIndex: 'color',
        key: 'po_details_id',
        render: value =><div className='align-left'> <a>{value}</a></div>
      };
      const excessColumn: ColumnProps<any> = {
        dataIndex: 'excessvalue',
        render: (sizevalue: any, record: any) =>
          this.excessrenderValue(sizevalue, diplayType, masterpodetails, record)
      };
      const totalColumn: ColumnProps<any> = {
        dataIndex: 'total',
        render: value =><div className='align-right'>  <a>{Math.floor(value.quantity)}</a></div>
      };
      columnInfo.push(TemplateColumn);
      columnInfo.push(scheduleColumn);
      columnInfo.push(colorColumn);
      columnInfo.push(excessColumn);

      for (const size of Array.from(sizes.values())) {
        const sizeColumn = {
          dataIndex: size,
          render: (sizevalue: any, record: any) =>
            this.renderValue(
              sizevalue,
              diplayType,
              masterpodetails,
              size,
              record
            )
        };
        columnInfo.push(sizeColumn);
      }
      columnInfo.push(totalColumn);

      const parentColumn = [{ children: columnInfo }];

      return (
        <Table
          size="small"
          columns={parentColumn}
          scroll={{ x: true, y: 1000 }}
          className="my-table"
          style={{ minWidth: '500px', maxHeight: '100%' }}
          dataSource={dataStore}
          bordered
          pagination={false}
          rowKey={record => {
            if (!record.__uniqueId) record.__uniqueId = ++uniqueId;
            return record.__uniqueId;
          }}
        />
      );
    }
  }
}
