import { Alert, Col, Form, Radio, Row, Skeleton, Space, Spin, Typography } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import ReadOnlyFormItemComponent from "../form-items-formatted/read-only-form-item.component";
import JobSearchSelectComponent from "../job-search-select/job-search-select.component";

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

const getPayoutMethodLabel = (payoutMethod, t) => {
  if (!payoutMethod) {
    return "";
  }

  if (payoutMethod === "hourly" || payoutMethod === "commission") {
    return t(`timetickets.labels.payout_methods.${payoutMethod}`);
  }

  return payoutMethod;
};

export function TimeTicketTaskModalComponent({ bodyshop, form, loading, completedTasks, unassignedHours }) {
  const { t } = useTranslation();

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col xl={12} lg={24}>
          <Form.Item
            name="jobid"
            label={t("timetickets.fields.ro_number")}
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <JobSearchSelectComponent convertedOnly={true} notExported={true} />
          </Form.Item>
          <Space wrap>
            <Form.Item
              name="task"
              label={t("timetickets.labels.task")}
              rules={[
                {
                  required: true
                }
              ]}
            >
              {loading ? (
                <Spin />
              ) : (
                <Radio.Group
                  optionType="button"
                  options={bodyshop.md_tasks_presets.presets.map((preset) => ({
                    value: preset.name,
                    label: preset.name,
                    disabled: completedTasks.map((task) => task.name).includes(preset.name)
                  }))}
                />
              )}
            </Form.Item>
            <Form.Item dependencies={["task"]}>
              {() => {
                const { task } = form.getFieldsValue();
                const theTaskPreset = bodyshop.md_tasks_presets?.presets?.find((tp) => tp.name === task);

                if (!task) return null;
                return (
                  <table className="task-tickets-table">
                    <tbody>
                      <tr>
                        <td>{t("bodyshop.fields.md_tasks_presets.percent")}</td>
                        <td>{`${theTaskPreset.percent || 0}%`}</td>
                      </tr>
                      <tr>
                        <td>{t("bodyshop.fields.md_tasks_presets.hourstype")}</td>
                        <td>{theTaskPreset.hourstype.join(", ")}</td>
                      </tr>
                      <tr>
                        <td>{t("bodyshop.fields.md_tasks_presets.nextstatus")}</td>
                        <td>{theTaskPreset.nextstatus}</td>
                      </tr>
                    </tbody>
                  </table>
                );
              }}
            </Form.Item>
          </Space>
        </Col>
        <Col xl={12} lg={24}>
          {loading ? (
            <Skeleton />
          ) : (
            <Form.List name="timetickets">
              {(fields) => {
                return (
                  <>
                    <Typography.Title level={4}>{t("timetickets.labels.claimtaskpreview")}</Typography.Title>
                    <table className="task-tickets-table">
                      <thead>
                        <tr>
                          <th>{t("timetickets.fields.employee")}</th>
                          <th>{t("timetickets.fields.cost_center")}</th>
                          <th>{t("timetickets.fields.ciecacode")}</th>
                          <th>{t("timetickets.fields.productivehrs")}</th>
                          <th>{t("timetickets.fields.payout_method")}</th>
                          <th>{t("timetickets.fields.rate")}</th>
                          <th>{t("timetickets.fields.amount")}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {fields.map((field, index) => {
                          const payoutMethod = form.getFieldValue(["timetickets", field.name, "payout_context", "payout_method"]);

                          return (
                            <tr key={field.key}>
                              <td>
                                <Form.Item key={`${index}employeeid`} name={[field.name, "employeeid"]}>
                                  <ReadOnlyFormItemComponent type="employee" />
                                </Form.Item>
                              </td>
                              <td>
                                <Form.Item key={`${index}cost_center`} name={[field.name, "cost_center"]}>
                                  <ReadOnlyFormItemComponent />
                                </Form.Item>
                              </td>
                              <td>
                                <Form.Item key={`${index}ciecacode`} name={[field.name, "ciecacode"]}>
                                  <ReadOnlyFormItemComponent />
                                </Form.Item>
                              </td>
                              <td>
                                <Form.Item key={`${index}productivehrs`} name={[field.name, "productivehrs"]}>
                                  <ReadOnlyFormItemComponent />
                                </Form.Item>
                              </td>
                              <td>{getPayoutMethodLabel(payoutMethod, t)}</td>
                              <td>
                                <Form.Item key={`${index}rate`} name={[field.name, "rate"]}>
                                  <ReadOnlyFormItemComponent type="currency" />
                                </Form.Item>
                              </td>
                              <td>
                                <Form.Item key={`${index}payoutamount`} name={[field.name, "payoutamount"]}>
                                  <ReadOnlyFormItemComponent type="currency" />
                                </Form.Item>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                    <Alert type="success" title={t("timetickets.labels.payrollclaimedtasks")} />
                  </>
                );
              }}
            </Form.List>
          )}
          {unassignedHours > 0 && (
            <Alert
              type="error"
              title={t("timetickets.validation.unassignedlines", {
                unassignedHours: unassignedHours
              })}
            />
          )}
        </Col>
      </Row>

      {bodyshop?.md_tasks_presets?.use_approvals && (
        <Col xl={12} lg={24}>
          <Alert title={t("tt_approvals.labels.approval_queue_in_use")} type="warning" />
        </Col>
      )}
    </div>
  );
}
