import axios from 'axios';
import { API_URL, currencyFormatter } from '@pos/base';
import { Fragment, useEffect, useState } from 'react';
import { Card, Col, DatePicker, notification, Row, Table } from 'antd';
import dayjs from 'dayjs';
import lodash from 'lodash';
import { v4 } from 'uuid';

export default function ReportModule() {
  const [dataItem, setDataItem] = useState<any[]>([]);
  const [dataItemKeys, setDataItemKeys] = useState<any[]>([]);
  const [loadingDataItem, setLoadingDataItem] = useState<boolean>(false);
  const [dataItemTotalPax, setDataItemTotalPax] = useState<number>(0);
  const [dataItemTotalRevenue, setDataItemTotalRevenue] = useState<number>(0);

  const [dataItemMaster, setDataItemMaster] = useState<any[]>([]);
  const [dataItemMasterKeys, setDataItemMasterKeys] = useState<any[]>([]);
  const [loadingDataItemMaster, setLoadingDataItemMaster] = useState<boolean>(false);
  const [dataItemMasterTotalPax, setDataItemMasterTotalPax] = useState<number>(0);
  const [dataItemMasterTotalRevenue, setDataItemMasterTotalRevenue] = useState<number>(0);

  const [filterDate, setFilerDate] = useState(dayjs());

  async function getDataItem(params: any) {
    setLoadingDataItem(true);
    await axios
      .get(API_URL.REPORT_SUMMARY_INCOME_ITEM, { params: params })
      .then((resp) => {
        const data = resp.data.data;

        const groupedData = lodash(data)
          .groupBy('item_owner') // Group by item_owner
          .map((items, owner) => ({
            // Map over each group to sum values and keep children
            title: owner,
            tr_item__qty: lodash.sumBy(items, (item) => Number(item.tr_item__qty)), // Convert to number
            tr_item__total_net_price: lodash.sumBy(items, (item) => Number(item.tr_item__total_net_price)), // Convert to number
            children: items.map((item) => {
              return { ...item, title: item.tr_item__item_name };
            }), // Include the original data as children
          }))
          .value()
          .map((item) => {
            return {
              key: v4(),
              ...item,
            };
          });

        const totalPax = lodash.sumBy(data, (item: any) => Number(item.tr_item__qty));
        const totalRevenue = lodash.sumBy(data, (item: any) => Number(item.tr_item__total_net_price));
        setDataItemTotalPax(totalPax);
        setDataItemTotalRevenue(totalRevenue);

        setDataItemKeys(groupedData.map((item) => item.key));
        setDataItem(groupedData);
      })
      .catch((err) => {
        notification.error({ message: err?.message });
      })
      .finally(() => {
        setLoadingDataItem(false);
      });
  }

  async function getDataItemMaster(params: any) {
    setLoadingDataItemMaster(true);
    await axios
      .get(API_URL.REPORT_SUMMARY_INCOME_ITEM_MASTER, { params: params })
      .then((resp) => {
        const data = resp.data.data;
        const groupedData = lodash(data)
          .groupBy('item_owner') // Group by item_owner
          .map((items, owner) => ({
            // Map over each group to sum values and keep children
            title: owner,
            tr_item__qty: lodash.sumBy(items, (item) => Number(item.tr_item__qty)), // Convert to number
            tr_item_bundling__total_net_price: lodash.sumBy(items, (item) =>
              Number(item.tr_item_bundling__total_net_price),
            ), // Convert to number
            children: items.map((item) => {
              let title = '';
              if (item.tr_item_bundling__item_name) {
                title = `${item.tr_item_bundling__item_name} / ${item.tr_item__item_name}`;
              } else {
                title = item.tr_item__item_name;
              }
              return { ...item, title: title };
            }), // Include the original data as children
          }))
          .value()
          .map((item) => {
            return {
              key: v4(),
              ...item,
            };
          });

        const totalPax = lodash.sumBy(data, (item: any) => Number(item.tr_item__qty));
        const totalRevenue = lodash.sumBy(data, (item: any) => Number(item.tr_item_bundling__total_net_price));
        setDataItemMasterTotalPax(totalPax);
        setDataItemMasterTotalRevenue(totalRevenue);

        setDataItemMasterKeys(groupedData.map((item) => item.key));
        setDataItemMaster(groupedData);
      })
      .catch((err) => {
        notification.error({ message: err?.message });
      })
      .finally(() => {
        setLoadingDataItemMaster(false);
      });
  }

  function handleGetDate(date: any) {
    getDataItem({ date });
    getDataItemMaster({ date });
  }

  useEffect(() => {
    if (filterDate) {
      handleGetDate(filterDate.format('DD-MM-YYYY'));
    }
  }, [filterDate]);

  return (
    <Fragment>
      <Row>
        <Col xl={8} lg={8} md={12} span={24}>
          <DatePicker
            size="large"
            popupStyle={{ fontSize: 16 }}
            allowClear={false}
            value={filterDate}
            style={{ width: '100%' }}
            format={'DD-MM-YYYY'}
            onChange={setFilerDate}
          />
        </Col>
      </Row>
      <div style={{ marginBottom: 20 }}></div>

      <Row gutter={[16, 16]}>
        <Col xl={12} lg={12} span={24}>
          <Card
            title={
              <Row style={{ paddingTop: 10, paddingBottom: 10 }}>
                <Col span={24}>
                  <div
                    style={{ fontSize: 16, fontWeight: 600 }}
                  >{`Pendapatan Per Item ${filterDate.format('DD-MM-YYYY')}`}</div>
                </Col>
                <Col xl={20} lg={20} span={24}>
                  <div
                    style={{ fontWeight: 400, fontSize: 12, color: 'grey', textWrap: 'wrap' }}
                  >{`Total revenue mungkin berbeda dengan pendapatan per item master disebabkan pengambilan harga kepada harga bundling.`}</div>
                </Col>
              </Row>
            }
          >
            <Row gutter={[8, 8]}>
              <Col span={12}>
                <Card styles={{ body: { padding: '6px 12px 6px 12px' } }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>TOTAL PAX</div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: 'rgba(0,0,0,0.6)' }}>{dataItemTotalPax}</div>
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card styles={{ body: { padding: '6px 12px 6px 12px' } }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>TOTAL REVENUE</div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: 'rgba(0,0,0,0.6)' }}>
                      {currencyFormatter({ value: dataItemTotalRevenue })}
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
            <div style={{ marginBottom: 10 }}></div>
            <Table
              bordered
              size="small"
              dataSource={dataItem}
              pagination={false}
              loading={loadingDataItem}
              scroll={{ x: 'max-width', y: 350 }}
              rowKey={(child) => {
                return child.key ?? child?.id ?? child.tr_item__item_name ?? child?.title;
              }}
              expandable={{ expandedRowKeys: dataItemKeys, showExpandColumn: false }}
              rowClassName={(row) => (row.key ? 'row-group' : '')}
              rowHoverable={false}
              columns={[
                { key: 'title', dataIndex: 'title', title: 'TITLE', width: 170 },
                { key: 'tr_item__qty', dataIndex: 'tr_item__qty', title: 'PAX', width: 70 },
                {
                  key: 'tr_item__total_net_price',
                  dataIndex: 'tr_item__total_net_price',
                  title: 'REVENUE',
                  width: 120,
                  render: (value) => currencyFormatter({ value }),
                },
              ]}
            />
          </Card>
        </Col>
        <Col xl={12} lg={12} span={24}>
          <Card
            title={
              <Row style={{ paddingTop: 10, paddingBottom: 10 }}>
                <Col span={24}>
                  <div
                    style={{ fontSize: 16, fontWeight: 600 }}
                  >{`Pendapatan Per Item Master ${filterDate.format('DD-MM-YYYY')}`}</div>
                </Col>
                <Col xl={20} lg={20} span={24}>
                  <div
                    style={{ fontWeight: 400, fontSize: 12, color: 'grey', textWrap: 'wrap' }}
                  >{`Total revenue mungkin berbeda dengan pendapatan per item disebabkan harga item master mengambil harga jual standard item.`}</div>
                </Col>
              </Row>
            }
          >
            <Row gutter={[8, 8]}>
              <Col span={12}>
                <Card styles={{ body: { padding: '6px 12px 6px 12px' } }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>TOTAL PAX</div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: 'rgba(0,0,0,0.6)' }}>
                      {dataItemMasterTotalPax}
                    </div>
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card styles={{ body: { padding: '6px 12px 6px 12px' } }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>TOTAL REVENUE</div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: 'rgba(0,0,0,0.6)' }}>
                      {currencyFormatter({ value: dataItemMasterTotalRevenue })}
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
            <div style={{ marginBottom: 10 }}></div>
            <Table
              bordered
              size="small"
              dataSource={dataItemMaster}
              pagination={false}
              loading={loadingDataItemMaster}
              scroll={{ x: 'max-width', y: 350 }}
              rowKey={(child) => {
                return child.key ?? child?.id ?? child.tr_item__item_name ?? child?.title;
              }}
              expandable={{ expandedRowKeys: dataItemMasterKeys, showExpandColumn: false }}
              rowClassName={(row) => (row.key ? 'row-group' : '')}
              rowHoverable={false}
              columns={[
                { key: 'title', dataIndex: 'title', title: 'TITLE', width: 170 },

                { key: 'tr_item__qty', dataIndex: 'tr_item__qty', title: 'PAX', width: 70 },
                {
                  key: 'tr_item_bundling__total_net_price',
                  dataIndex: 'tr_item_bundling__total_net_price',
                  title: 'REVENUE',
                  width: 120,
                  render: (value) => currencyFormatter({ value }),
                },
              ]}
            />
          </Card>
        </Col>
      </Row>
    </Fragment>
  );
}
