import useTranslation from 'next-translate/useTranslation';
import React, { FC, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import CRUDBuilder from '../../../../utils/CRUDBuilder/CRUDBuilder';
import { ItemType } from '../../../../utils/CRUDBuilder/types';

import { FetchOrdersAsync, selectOrders, selectOrdersStatus, UpdateOrderAsync } from '../../../../redux/orders';
import { GetServerSideProps } from 'next';
import { Button, Modal, Table, Typography } from 'antd';
import { DashboardAuthenticated } from '../../../../utils/helpers/dashboard-authenticated';
import { OrderStatus } from '../../../../models/order/enum';
import { FetchDashProductsAsync, selectApp, selectProducts, selectProductsStatus } from '../../../../redux';
import { ColumnsType } from 'antd/lib/table';
import { Product } from '../../../../models';
import { EyeFilled } from '@ant-design/icons';

interface OrderDetails {
  product: string;
  qty: string;
}

export const columnsOrders: ItemType[] = [
  {
    columnType: {
      title: 'ID',
      dataIndex: 'id',
      width: 250,
    },
    type: 'primary-key',
  },
  {
    columnType: {
      title: 'Order NO',
      dataIndex: 'order_no',
      width: 250,
    },
    type: 'text',
    demo: true,
  },
  {
    columnType: {
      title: 'First Name',
      dataIndex: 'first_name',
      width: 200,
    },
    type: 'text',
    demo: true,
  },
  {
    columnType: {
      title: 'Last Name',
      dataIndex: 'last_name',
      width: 200,
    },
    type: 'text',
    demo: true,
  },
  {
    columnType: {
      title: 'Phone',
      dataIndex: 'phone',
      width: 200,
    },
    type: 'text',
    demo: true,
  },
  {
    columnType: {
      title: 'Address',
      dataIndex: 'address',
      width: 250,
    },
    type: 'text',
    demo: true,
  },
  {
    columnType: {
      title: 'Status',
      dataIndex: 'status',
      width: 250,
      render: (val: number) => <Typography.Text> {OrderStatus[val].toString()}</Typography.Text>,
      filters: [
        {
          text: 'Pending',
          value: 'pending',
        },
        {
          text: 'On Delivery',
          value: 'on delivery',
        },
        {
          text: 'Rejected',
          value: 'rejected',
        },
        {
          text: 'Done',
          value: 'done',
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        const ind = Object.keys(OrderStatus).findIndex((el) => el === value);
        return Number(record.status) === ind;
      },
    },
    type: 'foreign-key',
    foreignKeyArr: Object.keys(OrderStatus).map((el, ind) => ({ title: el, value: ind })),
  },
  {
    columnType: {
      title: 'Requested Delivery Date',
      dataIndex: 'requested_delivery_date',
      width: 300,
    },
    type: 'date',
    demo: true,
  },
];

const ManageOrders: FC = () => {
  const [visible, setVisible] = useState(false);
  const [orderDetails, setOrderDetails] = useState<(Product & { qty: string })[]>();

  const products = useSelector(selectProducts);
  const proStatus = useSelector(selectProductsStatus);
  const orders = useSelector(selectOrders);
  const status = useSelector(selectOrdersStatus);
  const { user } = useSelector(selectApp);
  const sales = user?.roles[0].name === 'sales';

  const { lang } = useTranslation();

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(FetchOrdersAsync());
    dispatch(FetchDashProductsAsync());
  }, [dispatch]);

  const onClick = (arr: OrderDetails[]) => {
    setVisible(true);
    const pds = products
      .filter((el) => !!arr.find((l) => Number(l.product) === Number(el.id)))
      .map((el) => {
        const pro = arr.find((l) => Number(l.product) === Number(el.id));
        return { ...el, qty: pro!.qty };
      });
    setOrderDetails(pds);
    console.log(pds);
  };

  const pdColumns: ColumnsType<Product> = [
    {
      title: 'ID',
      dataIndex: `id`,
      width: 100,
    },
    {
      title: 'Image',
      dataIndex: `product_images`,
      width: 200,
      render: (val: { image_path: string }[]) => (
        <img src={val[0].image_path} height={200} style={{ height: 200, objectFit: 'cover' }} />
      ),
    },
    {
      title: 'Product Name',
      dataIndex: `name:${lang}`,
      width: 'auto',
    },
    {
      title: 'Product Quantity',
      dataIndex: `qty`,
      width: 200,
    },
  ];

  const tmp: ItemType[] = [
    {
      columnType: {
        title: 'Order Details',
        dataIndex: 'order_details',
        width: 100,
        render: (val: OrderDetails[]) => (
          <Button
            size='middle'
            type='primary'
            ghost
            onClick={() => onClick(val)}
            title='SHOW'
            icon={<EyeFilled />}
            loading={proStatus === 'loading'}
          />
        ),
      },
      type: 'foreign-key',
      demo: true,
    },
  ];

  return (
    <>
      <CRUDBuilder
        lang={lang === 'en' ? 'en' : 'ar'}
        items={orders}
        loading={status === 'loading'}
        UpdateAsync={sales ? undefined : (val) => UpdateOrderAsync({ order_id: val.id, status: val.item.status })}
        itemsHeader={[...columnsOrders, ...tmp]}
      />
      <Modal width={800} visible={visible} footer={false} onCancel={() => setVisible(false)}>
        <Table
          columns={pdColumns}
          dataSource={orderDetails}
          pagination={false}
          bordered
          style={{
            marginTop: 20,
          }}
        />
      </Modal>
    </>
  );
};
export default ManageOrders;

export const getServerSideProps: GetServerSideProps = DashboardAuthenticated;
