import {Component} from 'react';
import PropTypes from 'prop-types';
import moment from 'moment-jalaali';

class Orders extends Component {
  state = {
    showCount: true,
    showTotalPrice: true,
    showAuthorPrice: false,
    showUnits: true
  };

  toggleShowCount = () => this.setState(state => ({showCount: !state.showCount}));
  toggleShowTotalPrice = () => this.setState(state => ({showTotalPrice: !state.showTotalPrice}));
  toggleShowAuthorPrice = () => this.setState(state => ({showAuthorPrice: !state.showAuthorPrice}));
  toggleShowUnits = () => this.setState(state => ({showUnits: !state.showUnits}));

  presentPrice = price => (this.state.showUnits ? `${price.toLocaleString()} ریال` : price);
  presentCount = count => (this.state.showUnits ? `${count} عدد` : count);

  getMonthkeys = () => {
    const keys = [];
    const today = moment();
    let month = today.jMonth() + 1;
    let year = today.jYear();
    while (year > 1400 || month > 5) {
      keys.push(`${year}-${month < 10 ? `0${month}` : month}`);
      if (month > 1) {
        month = month - 1;
      } else {
        month = 12;
        year = year - 1;
      }
    }
    return keys;
  };

  render() {
    const {showCount, showTotalPrice, showAuthorPrice, showUnits} = this.state;
    const monthKeys = this.getMonthkeys();

    const dataByOrderItem = {};
    for (const orderItem of this.props.orderItems) {
      let price = 0;
      let count = 0;
      for (const monthKey in orderItem.data) {
        if (monthKeys.includes(monthKey)) {
          price += orderItem.data[monthKey].totalPrice;
          count += orderItem.data[monthKey].count;
        }
      }
      dataByOrderItem[orderItem.id] = {price, count};
    }

    const dataByMonthKey = {};
    for (const monthKey of monthKeys) dataByMonthKey[monthKey] = {price: 0, count: 0};
    for (const orderItem of this.props.orderItems) {
      for (const monthKey in orderItem.data) {
        if (monthKeys.includes(monthKey)) {
          dataByMonthKey[monthKey].price += orderItem.data[monthKey]?.totalPrice || 0;
          dataByMonthKey[monthKey].count += orderItem.data[monthKey]?.count || 0;
        }
      }
    }

    const totalData = {price: 0, count: 0};
    for (const orderItemId in dataByOrderItem) {
      totalData.price += dataByOrderItem[orderItemId].price;
      totalData.count += dataByOrderItem[orderItemId].count;
    }

    return (
      <div className='px-4 overflow-x-auto'>
        <p className='font-medium text-lg'>جدول فروش ماهیانه:</p>

        <div className='flex flex-wrap justify-center gap-8 my-2'>
          <div>
            <input
              type='checkbox'
              id='show-total-price'
              checked={showTotalPrice}
              onChange={this.toggleShowTotalPrice}
            />
            <label htmlFor='show-total-price' className='mx-2'>
              نمایش مبلغ کل
            </label>
          </div>

          <div>
            <input
              type='checkbox'
              id='show-count'
              checked={showCount}
              onChange={this.toggleShowCount}
            />
            <label htmlFor='show-count' className='mx-2'>
              نمایش تعداد
            </label>
          </div>

          <div>
            <input
              type='checkbox'
              id='show-author-price'
              checked={showAuthorPrice}
              onChange={this.toggleShowAuthorPrice}
            />
            <label htmlFor='show-author-price' className='mx-2'>
              نمایش سهم مولف
            </label>
          </div>

          <div>
            <input
              type='checkbox'
              id='show-units'
              checked={showUnits}
              onChange={this.toggleShowUnits}
            />
            <label htmlFor='show-units' className='mx-2'>
              نمایش واحدها
            </label>
          </div>
        </div>

        <table className='my-4 mx-auto'>
          <thead className='border-collapse border border-gray-700'>
            <tr className='text-center font-medium bg-indigo-50'>
              <td className='border border-gray-700 p-3'>#</td>
              {monthKeys.map(orderPaid => (
                <td key={orderPaid} className='border border-gray-700 p-3'>
                  {orderPaid}
                </td>
              ))}
              <td className='border border-gray-700 bg-indigo-300 p-3'>مجموع</td>
            </tr>
          </thead>
          <tbody>
            {this.props.orderItems.map(orderItem => (
              <tr key={orderItem.id} className='text-center'>
                <td className='border border-gray-700 bg-indigo-50 font-medium p-3'>
                  {orderItem.name}
                </td>
                {monthKeys.map(monthKey => {
                  const orderPaidData = orderItem.data[monthKey];
                  return (
                    <td key={monthKey} className='border border-gray-700 p-3'>
                      {showTotalPrice && <p>{this.presentPrice(orderPaidData?.totalPrice || 0)}</p>}
                      {showCount && <p>{this.presentCount(orderPaidData?.count || 0)}</p>}
                      {showAuthorPrice && (
                        <p>{this.presentPrice((orderPaidData?.totalPrice || 0) / 5)}</p>
                      )}
                    </td>
                  );
                })}
                <td className='border border-gray-700 bg-indigo-50 p-3'>
                  {showTotalPrice && (
                    <p>{this.presentPrice(dataByOrderItem[orderItem.id].price)}</p>
                  )}
                  {showCount && <p>{this.presentCount(dataByOrderItem[orderItem.id].count)}</p>}
                  {showAuthorPrice && (
                    <p>{this.presentPrice(dataByOrderItem[orderItem.id].price / 5)}</p>
                  )}
                </td>
              </tr>
            ))}
            <tr className='text-center bg-indigo-100'>
              <td className='border border-green-700 bg-indigo-300 font-medium p-3'>مجموع</td>
              {monthKeys.map(monthKey => {
                return (
                  <td key={monthKey} className='border border-gray-700 p-3'>
                    {showTotalPrice && <p>{this.presentPrice(dataByMonthKey[monthKey].price)}</p>}
                    {showCount && <p>{this.presentCount(dataByMonthKey[monthKey].count)}</p>}
                    {showAuthorPrice && (
                      <p>{this.presentPrice(dataByMonthKey[monthKey].price / 5)}</p>
                    )}
                  </td>
                );
              })}
              <td className='border border-gray-700 p-3 bg-indigo-300'>
                {showTotalPrice && <p>{this.presentPrice(totalData.price)}</p>}
                {showCount && <p>{this.presentPrice(totalData.count)}</p>}
                {showAuthorPrice && <p>{this.presentPrice(totalData.price / 5)}</p>}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

Orders.propTypes = {
  orderItems: PropTypes.array.isRequired
};

export default Orders;
