import { AuditOutlined, DeleteFilled, EditFilled, EyeInvisibleFilled, WarningFilled } from "@ant-design/icons";
import { Button, Card, Form, Input, Space, Table } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { setModalContext } from "../../redux/modals/modals.actions";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { TemplateList } from "../../utils/TemplateConstants";
import useLocalStorage from "../../utils/useLocalStorage";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import NoteUpsertModal from "../note-upsert-modal/note-upsert-modal.container";
import PrintWrapperComponent from "../print-wrapper/print-wrapper.component";

const mapStateToProps = createStructuredSelector({
  jobRO: selectJobReadOnly
});

const mapDispatchToProps = (dispatch) => ({
  setNoteUpsertContext: (context) => dispatch(setModalContext({ context: context, modal: "noteUpsert" }))
});

export function JobNotesComponent({
  jobRO,
  loading,
  data,
  refetch,
  handleNoteDelete,
  jobId,
  setNoteUpsertContext,
  deleteLoading,
  ro_number,
  relatedRos
}) {
  const { t } = useTranslation();
  const [filter, setFilter] = useLocalStorage("filter_job_notes_icons", null);

  const Templates = TemplateList("job_special", {
    ro_number
  });

  const columns = [
    {
      title: "",
      dataIndex: "icons",
      key: "icons",
      width: 80,
      filteredValue: filter?.icons || null,
      filters: [
        {
          text: t("notes.labels.usernotes"),
          value: false
        },
        {
          text: t("notes.labels.systemnotes"),
          value: true
        }
      ],
      onFilter: (value, record) => record.audit === value,
      render: (text, record) => (
        <span>
          {record.critical ? <WarningFilled style={{ margin: 4, color: "red" }} /> : null}
          {record.private ? <EyeInvisibleFilled style={{ margin: 4 }} /> : null}
          {record.audit ? <AuditOutlined style={{ margin: 4 }} /> : null}
        </span>
      )
    },
    {
      title: t("notes.fields.type"),
      dataIndex: "type",
      key: "type",
      width: 120,
      filteredValue: filter?.type || null,
      filters: [
        { value: "general", text: t("notes.fields.types.general") },
        { value: "customer", text: t("notes.fields.types.customer") },
        { value: "shop", text: t("notes.fields.types.shop") },
        { value: "office", text: t("notes.fields.types.office") },
        { value: "parts", text: t("notes.fields.types.parts") },
        { value: "paint", text: t("notes.fields.types.paint") },
        {
          value: "supplement",
          text: t("notes.fields.types.supplement")
        }
      ],
      onFilter: (value, record) => value.includes(record.type),
      render: (text, record) => t(`notes.fields.types.${record.type}`)
    },
    {
      title: t("notes.fields.text"),
      dataIndex: "text",
      key: "text",
      ellipsis: true,
      render: (text, record) => <span style={{ whiteSpace: "pre-line" }}>{text}</span>
    },

    {
      title: t("notes.fields.updatedat"),
      dataIndex: "updated_at",
      key: "updated_at",
      defaultSortOrder: "descend",
      width: 200,
      sorter: (a, b) => new Date(a.updated_at) - new Date(b.updated_at),
      render: (text, record) => <DateTimeFormatter>{record.updated_at}</DateTimeFormatter>
    },
    {
      title: t("notes.fields.createdby"),
      dataIndex: "created_by",
      key: "created_by",
      width: 200
    },
    {
      title: t("notes.actions.actions"),
      dataIndex: "actions",
      key: "actions",
      width: 200,
      render: (text, record) => (
        <Space wrap>
          <Button loading={deleteLoading} disabled={record.audit || jobRO} onClick={() => handleNoteDelete(record.id)}>
            <DeleteFilled />
          </Button>
          <Button
            disabled={record.audit || jobRO}
            onClick={() => {
              setNoteUpsertContext({
                actions: { refetch: refetch },
                context: {
                  jobId: jobId,
                  existingNote: record
                }
              });
            }}
          >
            <EditFilled />
          </Button>
          <PrintWrapperComponent
            templateObject={{
              name: Templates.individual_job_note.key,

              variables: { id: record.id }
            }}
            messageObject={{
              subject: Templates.individual_job_note.subject
            }}
            id={jobId}
          />
        </Space>
      )
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setFilter(filters);
  };

  return (
    <div>
      <LayoutFormRow>
        <Form.Item label={t("jobs.fields.invoice_final_note")} name="invoice_final_note">
          <Input.TextArea disabled={jobRO} />
        </Form.Item>
      </LayoutFormRow>
      <Card
        title={t("jobs.labels.notes")}
        extra={
          <Button
            onClick={() => {
              setNoteUpsertContext({
                actions: { refetch: refetch },
                context: {
                  jobId: jobId,
                  relatedRos: relatedRos
                }
              });
            }}
          >
            {t("notes.actions.new")}
          </Button>
        }
      >
        <NoteUpsertModal />

        <Table loading={loading} columns={columns} rowKey="id" dataSource={data} onChange={handleTableChange} />
      </Card>
    </div>
  );
}

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