import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Form, Input } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { pageLimit } from "../../utils/config";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop
});

const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export default connect(mapStateToProps, mapDispatchToProps)(DmsAllocationsSummaryAp);

export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) {
  const { t } = useTranslation();
  const [allocationsSummary, setAllocationsSummary] = useState([]);
  const socketRef = useRef(socket);

  useEffect(() => {
    socketRef.current = socket;
  }, [socket]);

  useEffect(() => {
    socket.on("ap-export-success", (billid) => {
      setAllocationsSummary((allocationsSummary) =>
        allocationsSummary.map((a) => {
          if (a.billid !== billid) return a;
          return { ...a, status: "Successful" };
        })
      );
    });
    socket.on("ap-export-failure", ({ billid, error }) => {
      allocationsSummary.map((a) => {
        if (a.billid !== billid) return a;
        return { ...a, status: error };
      });
    });

    if (socket.disconnected) socket.connect();
    return () => {
      socket.removeListener("ap-export-success");
      socket.removeListener("ap-export-failure");
      //socket.disconnect();
    };
  }, []);

  useEffect(() => {
    if (socket.connected) {
      socket.emit("pbs-calculate-allocations-ap", billids, (ack) => {
        setAllocationsSummary(ack);
        // Store on socket for side-channel communication
        socketRef.current.allocationsSummary = ack;
      });
    }
  }, [socket, socket.connected, billids]);

  const columns = [
    {
      title: t("general.labels.status"),
      dataIndex: "status",
      key: "status"
    },
    {
      title: t("bills.fields.invoice_number"),
      dataIndex: ["Posting", "Reference"],
      key: "reference"
    },

    {
      title: t("jobs.fields.dms.lines"),
      dataIndex: "Lines",
      key: "Lines",
      render: (text, record) => (
        <ResponsiveTable style={{ tableLayout: "auto", width: "100%" }}>
          <tr>
            <th>{t("bills.fields.invoice_number")}</th>
            <th>{t("bodyshop.fields.dms.dms_acctnumber")}</th>
            <th>{t("jobs.fields.dms.amount")}</th>
          </tr>
          {record.Posting.Lines.map((l, idx) => (
            <tr key={idx}>
              <td>{l.InvoiceNumber}</td>
              <td>{l.Account}</td>
              <td>{l.Amount}</td>
            </tr>
          ))}
        </ResponsiveTable>
      )
    }
  ];

  const handleFinish = async (values) => {
    socket.emit(`pbs-export-ap`, {
      billids,
      txEnvelope: values
    });
  };

  return (
    <Card
      title={title}
      extra={
        <Button
          onClick={() => {
            socket.emit("pbs-calculate-allocations-ap", billids, (ack) => setAllocationsSummary(ack));
          }}
          icon={<SyncOutlined />}
        />
      }
    >
      <ResponsiveTable
        pagination={{ placement: "top", defaultPageSize: pageLimit }}
        columns={columns}
        mobileColumnKeys={["status", "reference", "Lines"]}
        rowKey={(record) => `${record.InvoiceNumber}${record.Account}`}
        dataSource={allocationsSummary}
        locale={{ emptyText: t("dms.labels.refreshallocations") }}
      />
      <Form layout="vertical" onFinish={handleFinish}>
        <Form.Item
          name="journal"
          label={t("jobs.fields.dms.journal")}
          initialValue={bodyshop.cdk_configuration?.default_journal}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Button disabled={!allocationsSummary || allocationsSummary.length === 0} htmlType="submit">
          {t("jobs.actions.dms.post")}
        </Button>
      </Form>
    </Card>
  );
}
