import { UploadOutlined, UserAddOutlined } from "@ant-design/icons";
import { Button, Divider, Dropdown, Form, Input, Select, Space, Tabs, Upload } from "antd";
import _ from "lodash";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectEmailConfig } from "../../redux/email/email.selectors";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { CreateExplorerLinkForJob } from "../../utils/localmedia";
import EmailDocumentsComponent from "../email-documents/email-documents.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
  emailConfig: selectEmailConfig
});

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

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

export function EmailOverlayComponent({ emailConfig, form, selectedMediaState, bodyshop, currentUser }) {
  const { t } = useTranslation();

  const handleClick = ({ item }) => {
    const email = item.props.value;
    form.setFieldsValue({
      to: _.uniq([...form.getFieldValue("to"), ...(typeof email === "string" ? [email] : email)])
    });
  };

  const handle_CC_Click = ({ item }) => {
    const email = item.props.value;
    form.setFieldsValue({
      cc: _.uniq([...(form.getFieldValue("cc") || ""), ...(typeof email === "string" ? [email] : email)])
    });
  };

  const emailsToMenu = {
    items: [
      ...bodyshop.employees
        .filter((e) => e.user_email && e.active === true)
        .map((e, idx) => ({
          key: idx,
          label: `${e.first_name} ${e.last_name}`,
          value: e.user_email
        })),
      ...bodyshop.md_to_emails.map((e, idx) => ({
        key: idx + "group",
        label: e.label,
        value: e.emails
      }))
    ],
    onClick: handleClick
  };

  const menuCC = {
    items: [
      ...bodyshop.employees
        .filter((e) => e.user_email && e.active === true)
        .map((e, idx) => ({
          key: idx,
          label: `${e.first_name} ${e.last_name}`,
          value: e.user_email
        })),
      ...bodyshop.md_to_emails.map((e, idx) => ({
        key: idx + "group",
        label: e.label,
        value: e.emails
      }))
    ],
    onClick: handle_CC_Click
  };

  return (
    <div>
      <Form.Item
        label={t("emails.fields.from")}
        name="from"
        rules={[
          {
            required: true
            //message: t("general.validation.required"),
          }
        ]}
      >
        <Select
          options={[
            { key: currentUser.email, value: currentUser.email, label: currentUser.email },
            { key: bodyshop.email, value: bodyshop.email, label: bodyshop.email },
            ...(bodyshop.md_from_emails ? bodyshop.md_from_emails.map((e) => ({ key: e, value: e, label: e })) : [])
          ]}
        />
      </Form.Item>
      <Form.Item
        label={
          <Space>
            {t("emails.fields.to")}
            <Dropdown menu={emailsToMenu}>
              <a className="ant-dropdown-link" href=" #" onClick={(e) => e.preventDefault()}>
                <UserAddOutlined />
              </a>
            </Dropdown>
          </Space>
        }
        name="to"
        rules={[
          {
            required: true
            //message: t("general.validation.required"),
          }
        ]}
      >
        <Select mode="tags" tokenSeparators={[",", ";"]} />
      </Form.Item>
      <Form.Item
        label={
          <Space>
            {t("emails.fields.cc")}
            <Dropdown menu={menuCC}>
              <a className="ant-dropdown-link" href=" #" onClick={(e) => e.preventDefault()}>
                <UserAddOutlined />
              </a>
            </Dropdown>
          </Space>
        }
        name="cc"
      >
        <Select mode="tags" tokenSeparators={[",", ";"]} />
      </Form.Item>
      <Form.Item
        label={t("emails.fields.subject")}
        name="subject"
        rules={[
          {
            required: true
            //message: t("general.validation.required"),
          }
        ]}
      >
        <Input />
      </Form.Item>
      <Divider>{t("emails.labels.preview")}</Divider>
      {bodyshop.attach_pdf_to_email && <strong>{t("emails.labels.pdfcopywillbeattached")}</strong>}
      <Form.Item shouldUpdate>
        {() => {
          return (
            <div
              style={{
                padding: "1rem",
                backgroundColor: "var(--preview-bg)",
                borderLeft: "6px solid var(--preview-border-color)"
              }}
              dangerouslySetInnerHTML={{ __html: form.getFieldValue("html") }}
            />
          );
        }}
      </Form.Item>
      <Tabs
        defaultActiveKey="documents"
        items={[
          {
            key: "documents",
            label: t("emails.labels.documents"),
            children: <EmailDocumentsComponent selectedMediaState={selectedMediaState} form={form} />
          },
          {
            key: "attachments",
            label: t("emails.labels.attachments"),
            children: (
              <>
                {bodyshop.uselocalmediaserver && emailConfig.jobid && (
                  <a href={CreateExplorerLinkForJob({ jobid: emailConfig.jobid })}>
                    <Button>{t("documents.labels.openinexplorer")}</Button>
                  </a>
                )}
                <Form.Item
                  name="fileList"
                  valuePropName="fileList"
                  getValueFromEvent={(e) => {
                    if (Array.isArray(e)) {
                      return e;
                    }
                    return e && e.fileList;
                  }}
                  rules={[
                    () => ({
                      validator(rule, value) {
                        const totalSize = value.reduce((acc, val) => (acc = acc + val.size), 0);
                        const limit = 10485760 - new Blob([form.getFieldValue("html")]).size;
                        if (totalSize > limit) {
                          return Promise.reject(t("general.errors.sizelimit"));
                        }
                        return Promise.resolve();
                      }
                    })
                  ]}
                >
                  <Upload.Dragger beforeUpload={Upload.LIST_IGNORE} multiple listType="picture-card">
                    <>
                      <p className="ant-upload-drag-icon">
                        <UploadOutlined />
                      </p>
                      <p className="ant-upload-text">Click or drag files to this area to upload.</p>
                    </>
                  </Upload.Dragger>
                </Form.Item>
              </>
            )
          }
        ]}
      />
    </div>
  );
}
