import { LockOutlined } from "@ant-design/icons";
import { Badge, Card, Col, Collapse, Form, Input, Row, Space, Tooltip } from "antd";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobCloseRoGuardLabor from "./job-close-ro-gaurd.labor";
import JobCloseRoGuardAr from "./job-close-ro-guard.ar";
import JobCloseRoGuardBills from "./job-close-ro-guard.bills";
import JobCloseRoGuardPpd from "./job-close-ro-guard.ppd";
import JobCloseRoGuardProfit from "./job-close-ro-guard.profit";
import "./job-close-ro-guard.styles.scss";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import JobCloseRoGuardTtLifecycle from "./job-close-ro-guard.tt-lifecycle";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobCloseRoGuardContainer);

export function JobCloseRoGuardContainer({ job, jobRO, bodyshop, form }) {
  const { t } = useTranslation();
  const [warnings, setWarnings] = useState([]);

  const warningCallback = useCallback(
    ({ key, warning }) =>
      setWarnings((state) => {
        if (state.find((s) => s.key === key)) return state;
        return [...state, { key, warning }];
      }),
    []
  );

  if (!bodyshop?.md_ro_guard?.enabled) return null;

  return (
    <>
      {warnings.length > 0 && (
        <Card
          title={
            <Space size="small">
              <Badge count={warnings.length} />
              {t("jobs.labels.roguardwarnings")}
            </Space>
          }
        >
          <ul>
            {warnings.map((w, index) => (
              <li key={index}>
                {bodyshop.md_ro_guard[`enforce_${w.key}`] && (
                  <Tooltip title={t("jobs.labels.ro_guard.enforced")}>
                    <LockOutlined style={{ color: "tomato", marginRight: "8px" }} />
                  </Tooltip>
                )}
                {w.warning}
              </li>
            ))}
          </ul>
        </Card>
      )}

      <Collapse
        items={[
          {
            key: "roguard",
            label: t("jobs.labels.roguard"),
            forceRender: true,
            children: (
              <>
                <Row gutter={[32, 32]}>
                  <Col span={24}>
                    <JobCloseRoGuardBills job={job} form={form} warningCallback={warningCallback} />
                  </Col>
                  <Col className="ro-guard-col-multiple" md={24} lg={6}>
                    <Row gutter={[32, 32]} style={{ height: "100%" }}>
                      <Col span={24}>
                        <JobCloseRoGuardProfit job={job} form={form} warningCallback={warningCallback} />
                      </Col>
                      <Col span={24}>
                        <JobCloseRoGuardAr job={job} form={form} warningCallback={warningCallback} />
                      </Col>
                    </Row>
                  </Col>
                  {InstanceRenderManager({
                    rome: (
                      <Col md={24} lg={8}>
                        {/* <JobCloseRoGuardSublet job={job} warningCallback={warningCallback} /> */}
                        <JobCloseRoGuardPpd job={job} warningCallback={warningCallback} />
                      </Col>
                    )
                  })}
                  <Col className="ro-guard-col" md={24} lg={10}>
                    <JobCloseRoGuardLabor job={job} form={form} warningCallback={warningCallback} />
                  </Col>
                </Row>
                <Form.Item
                  name="masterbypass"
                  label={t("jobs.labels.masterbypass")}
                  rules={[
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_bills &&
                          warnings.find((w) => w.key === "bills")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_bills")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_cm &&
                          warnings.find((w) => w.key === "cm")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_cm")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_profit &&
                          warnings.find((w) => w.key === "profit")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_profit")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_ar &&
                          warnings.find((w) => w.key === "ar")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_ar")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_sublet &&
                          warnings.find((w) => w.key === "sublet")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_sublet")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_ppd &&
                          warnings.find((w) => w.key === "ppd")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_ppd")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    }),
                    () => ({
                      validator(_, value) {
                        if (
                          !PasswordCheck({ bodyshop, value }) &&
                          bodyshop.md_ro_guard.enforce_labor &&
                          warnings.find((w) => w.key === "labor")
                        ) {
                          return Promise.reject(
                            t("jobs.labels.ro_guard.enforce_validation", {
                              message: t("jobs.labels.ro_guard.enforce_labor")
                            })
                          );
                        }
                        return Promise.resolve();
                      }
                    })
                  ]}
                >
                  <Input prefix={<LockOutlined />} type="password" placeholder="Password" disabled={jobRO} />
                </Form.Item>
              </>
            )
          },
          {
            key: "job-performance",
            label: t("jobs.labels.performance"),
            children: (
              <Row gutter={[32, 32]}>
                <Col className="ro-guard-col" span={24}>
                  <JobCloseRoGuardTtLifecycle job={job} />
                </Col>
              </Row>
            )
          }
        ]}
      />
    </>
  );
}

function PasswordCheck({ bodyshop, value }) {
  return value === bodyshop?.md_ro_guard?.masterbypass;
}
