import { DeleteFilled, ReloadOutlined } from "@ant-design/icons";
import { Button, Col, Form, Input, InputNumber, Row, Select, Space, Switch, TimePicker, Tooltip } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import ColorpickerFormItemComponent from "../form-items-formatted/colorpicker-form-item.component";
import FormListMoveArrows from "../form-list-move-arrows/form-list-move-arrows.component";
import ConfigListEmptyState from "../layout-form-row/config-list-empty-state.component.jsx";
import InlineValidatedFormRow from "../layout-form-row/inline-validated-form-row.component.jsx";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import { ColorPicker } from "./shop-info.rostatus.component";
import {
  DEFAULT_TRANSLUCENT_CARD_COLOR,
  DEFAULT_TRANSLUCENT_PICKER_COLOR,
  getTintedCardSurfaceStyles
} from "./shop-info.color.utils";
import "./shop-info.scheduling.styles.scss";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

const WORKING_DAYS = [
  { key: "sunday", labelKey: "general.labels.sunday" },
  { key: "monday", labelKey: "general.labels.monday" },
  { key: "tuesday", labelKey: "general.labels.tuesday" },
  { key: "wednesday", labelKey: "general.labels.wednesday" },
  { key: "thursday", labelKey: "general.labels.thursday" },
  { key: "friday", labelKey: "general.labels.friday" },
  { key: "saturday", labelKey: "general.labels.saturday" }
];

const APPOINTMENT_COLOR_PICKER_STYLES = {
  default: {
    wrap: {
      display: "flex",
      flexWrap: "wrap",
      gap: "12px",
      alignItems: "flex-start"
    },
    hue: {
      flex: "1 1 180px",
      height: "12px",
      position: "relative",
      marginTop: "20px"
    },
    swatches: {
      flex: "1 1 160px"
    }
  }
};

const SCHEDULING_BUCKET_COLOR_PICKER_STYLES = {
  default: {
    picker: {
      width: "100%",
      height: "100%",
      background: "color-mix(in srgb, var(--imex-form-surface) 92%, transparent)",
      boxShadow: "none",
      border: "1px solid color-mix(in srgb, var(--imex-form-surface-border) 72%, transparent)",
      borderRadius: "8px",
      boxSizing: "border-box",
      overflow: "hidden"
    },
    saturation: {
      width: "100%",
      paddingBottom: "48%",
      position: "relative",
      borderRadius: "8px 8px 0 0",
      overflow: "hidden"
    },
    body: {
      padding: "12px"
    },
    controls: {
      display: "flex",
      gap: "10px"
    },
    color: {
      width: "28px"
    },
    swatch: {
      marginTop: "0",
      width: "12px",
      height: "12px",
      borderRadius: "999px"
    },
    toggles: {
      flex: "1"
    },
    hue: {
      height: "10px",
      position: "relative",
      marginBottom: "8px"
    },
    alpha: {
      height: "10px",
      position: "relative"
    }
  }
};

const SECTION_TITLE_INPUT_STYLE = {
  background: "color-mix(in srgb, var(--imex-form-surface) 78%, transparent)",
  border: "1px solid color-mix(in srgb, var(--imex-form-surface-border) 72%, transparent)",
  borderRadius: 6,
  fontWeight: 500
};

const SECTION_TITLE_INPUT_ROW_STYLE = {
  display: "flex",
  gap: 8,
  flexWrap: "wrap",
  alignItems: "center",
  minWidth: 180,
  maxWidth: "100%"
};

const SECTION_TITLE_INPUT_GROUP_STYLE = {
  display: "flex",
  alignItems: "center",
  gap: 6,
  minWidth: 0
};

const SECTION_TITLE_INPUT_LABEL_STYLE = {
  fontSize: 12,
  lineHeight: 1.1,
  opacity: 0.75,
  whiteSpace: "nowrap"
};

export function ShopInfoSchedulingComponent({ form, bodyshop }) {
  const { t } = useTranslation();
  const appointmentColors = Form.useWatch(["appt_colors"], form) || form.getFieldValue(["appt_colors"]) || [];
  const schedulingBuckets = Form.useWatch(["ssbuckets"], form) || form.getFieldValue(["ssbuckets"]) || [];

  return (
    <div>
      <LayoutFormRow grow header={t("bodyshop.labels.scheduling")} id="shopinfo-scheduling">
        <>
          <Form.Item
            name={["appt_alt_transport"]}
            label={t("bodyshop.fields.appt_alt_transport")}
            rules={[
              {
                //message: t("general.validation.required"),
                type: "array"
              }
            ]}
          >
            <Select mode="tags" />
          </Form.Item>
          <Form.Item
            name={["md_lost_sale_reasons"]}
            label={t("bodyshop.fields.md_lost_sale_reasons")}
            rules={[
              {
                // required: true,
                //message: t("general.validation.required"),
                type: "array"
              }
            ]}
          >
            <Select mode="tags" />
          </Form.Item>
          <Row gutter={[16, 0]} wrap>
            <Col xs={24} sm={12} xl={6}>
              <Form.Item
                label={t("bodyshop.fields.appt_length")}
                name={"appt_length"}
                rules={[
                  {
                    required: true
                    //message: t("general.validation.required"),
                  }
                ]}
              >
                <InputNumber min={15} precision={0} suffix="min" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} xl={6}>
              <Form.Item
                label={t("bodyshop.fields.schedule_start_time")}
                name={"schedule_start_time"}
                rules={[
                  {
                    required: true
                    //message: t("general.validation.required"),
                  }
                ]}
                id="schedule_start_time"
              >
                <TimePicker disableSeconds={true} format="HH:mm" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} xl={6}>
              <Form.Item
                label={t("bodyshop.fields.schedule_end_time")}
                name={"schedule_end_time"}
                rules={[
                  {
                    required: true
                    //message: t("general.validation.required"),
                  }
                ]}
                id="schedule_end_time"
              >
                <TimePicker disableSeconds={true} format="HH:mm" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} xl={6}>
              <Form.Item
                name={["ss_configuration", "dailyhrslimit"]}
                label={t("bodyshop.fields.ss_configuration.dailyhrslimit")}
              >
                <InputNumber min={0} suffix="hrs" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} xl={6}>
              <Form.Item
                name={["ss_configuration", "nobusinessdays"]}
                label={t("bodyshop.fields.ss_configuration.nobusinessdays")}
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </>
      </LayoutFormRow>
      <LayoutFormRow header={t("bodyshop.labels.workingdays")} id="workingdays">
        <Space wrap size="middle">
          {WORKING_DAYS.map(({ key, labelKey }) => (
            <Form.Item key={key} label={t(labelKey)} name={["workingdays", key]} valuePropName="checked">
              <Switch />
            </Form.Item>
          ))}
        </Space>
      </LayoutFormRow>
      <Form.List name={["appt_colors"]}>
        {(fields, { add, remove, move }) => {
          return (
            <LayoutFormRow
              header={t("bodyshop.labels.apptcolors")}
              id="apptcolors"
              actions={[
                <Button
                  key="add-appointment-color"
                  type="primary"
                  block
                  onClick={() => {
                    add({
                      color: {
                        ...DEFAULT_TRANSLUCENT_PICKER_COLOR,
                        rgb: { ...DEFAULT_TRANSLUCENT_PICKER_COLOR.rgb }
                      }
                    });
                  }}
                >
                  {t("bodyshop.actions.addapptcolor")}
                </Button>
              ]}
            >
              <div>
                {fields.length === 0 ? (
                  <ConfigListEmptyState actionLabel={t("bodyshop.actions.addapptcolor")} />
                ) : (
                  fields.map((field, index) => {
                    const appointmentColor =
                      appointmentColors[field.name] || form.getFieldValue(["appt_colors", field.name]) || {};
                    const appointmentColorSurfaceStyles = getTintedCardSurfaceStyles(appointmentColor.color);

                    return (
                      <Form.Item noStyle key={field.key}>
                        <InlineValidatedFormRow
                          form={form}
                          errorNames={[["appt_colors", field.name, "label"]]}
                          noDivider
                          title={
                            <div style={{ minWidth: 180, maxWidth: "100%" }}>
                              <Form.Item
                                noStyle
                                key={`${index}aptcolorlabel`}
                                name={[field.name, "label"]}
                                rules={[
                                  {
                                    required: true
                                    //message: t("general.validation.required"),
                                  }
                                ]}
                              >
                                <Input
                                  size="small"
                                  placeholder={t("bodyshop.fields.appt_colors.label")}
                                  style={SECTION_TITLE_INPUT_STYLE}
                                />
                              </Form.Item>
                            </div>
                          }
                          extra={
                            <Space align="center" size="small">
                              <Button
                                type="text"
                                danger
                                icon={<DeleteFilled />}
                                onClick={() => {
                                  remove(field.name);
                                }}
                              />
                              <FormListMoveArrows
                                move={move}
                                index={index}
                                total={fields.length}
                                orientation="horizontal"
                              />
                            </Space>
                          }
                          {...appointmentColorSurfaceStyles}
                        >
                          <Form.Item
                            key={`${index}aptcolorcolor`}
                            name={[field.name, "color"]}
                            rules={[
                              {
                                required: true
                                //message: t("general.validation.required"),
                              }
                            ]}
                          >
                            <ColorpickerFormItemComponent styles={APPOINTMENT_COLOR_PICKER_STYLES} />
                          </Form.Item>
                        </InlineValidatedFormRow>
                      </Form.Item>
                    );
                  })
                )}
              </div>
            </LayoutFormRow>
          );
        }}
      </Form.List>
      {HasFeatureAccess({ featureName: "smartscheduling", bodyshop }) && (
        <Form.List name={["ssbuckets"]}>
          {(fields, { add, remove, move }) => {
            return (
              <LayoutFormRow
                header={t("bodyshop.labels.ssbuckets")}
                id="ssbuckets"
                actions={[
                  <Button
                    key="add-job-size-definition"
                    type="primary"
                    block
                    onClick={() => {
                      add({
                        color: { ...DEFAULT_TRANSLUCENT_CARD_COLOR }
                      });
                    }}
                  >
                    {t("bodyshop.actions.addbucket")}
                  </Button>
                ]}
              >
                <div>
                  {fields.length === 0 ? (
                    <ConfigListEmptyState actionLabel={t("bodyshop.actions.addbucket")} />
                  ) : (
                    fields.map((field, index) => {
                      const schedulingBucket =
                        schedulingBuckets[field.name] || form.getFieldValue(["ssbuckets", field.name]) || {};
                      const schedulingBucketSurfaceStyles = getTintedCardSurfaceStyles(schedulingBucket.color);

                      return (
                        <Form.Item noStyle key={field.key}>
                          <InlineValidatedFormRow
                            form={form}
                            errorNames={[
                              ["ssbuckets", field.name, "id"],
                              ["ssbuckets", field.name, "label"]
                            ]}
                            noDivider
                            title={
                              <div style={SECTION_TITLE_INPUT_ROW_STYLE}>
                                <div style={SECTION_TITLE_INPUT_GROUP_STYLE}>
                                  <div style={SECTION_TITLE_INPUT_LABEL_STYLE}>{t("bodyshop.fields.ssbuckets.id")}</div>
                                  <Form.Item
                                    noStyle
                                    key={`${index}id`}
                                    name={[field.name, "id"]}
                                    rules={[
                                      {
                                        required: true
                                        //message: t("general.validation.required"),
                                      }
                                    ]}
                                  >
                                    <Input
                                      size="small"
                                      placeholder={t("bodyshop.fields.ssbuckets.id")}
                                      style={{
                                        ...SECTION_TITLE_INPUT_STYLE,
                                        width: 72
                                      }}
                                    />
                                  </Form.Item>
                                </div>
                                <div
                                  style={{
                                    ...SECTION_TITLE_INPUT_GROUP_STYLE,
                                    flex: 1,
                                    minWidth: 0
                                  }}
                                >
                                  <div style={SECTION_TITLE_INPUT_LABEL_STYLE}>
                                    {t("bodyshop.fields.ssbuckets.label")}
                                  </div>
                                  <Form.Item
                                    noStyle
                                    key={`${index}label`}
                                    name={[field.name, "label"]}
                                    rules={[
                                      {
                                        required: true
                                        //message: t("general.validation.required"),
                                      }
                                    ]}
                                  >
                                    <Input
                                      size="small"
                                      placeholder={t("bodyshop.fields.ssbuckets.label")}
                                      style={{
                                        ...SECTION_TITLE_INPUT_STYLE,
                                        width: "100%"
                                      }}
                                    />
                                  </Form.Item>
                                </div>
                              </div>
                            }
                            extra={
                              <Space align="center" size="small">
                                <Button
                                  type="text"
                                  danger
                                  icon={<DeleteFilled />}
                                  onClick={() => {
                                    remove(field.name);
                                  }}
                                />
                                <Tooltip title={t("bodyshop.tooltips.reset-color")}>
                                  <Button
                                    type="text"
                                    icon={<ReloadOutlined />}
                                    onClick={() => {
                                      form.setFieldValue(["ssbuckets", field.name, "color"]);

                                      form.setFields([
                                        {
                                          name: ["ssbuckets", field.name, "color"],
                                          touched: true
                                        }
                                      ]);
                                    }}
                                  />
                                </Tooltip>
                                <FormListMoveArrows
                                  move={move}
                                  index={index}
                                  total={fields.length}
                                  orientation="horizontal"
                                />
                              </Space>
                            }
                            {...schedulingBucketSurfaceStyles}
                          >
                            <div className="shop-info-scheduling__bucket-card-body">
                              <div className="shop-info-scheduling__bucket-card-fields">
                                <Form.Item
                                  label={t("bodyshop.fields.ssbuckets.gte")}
                                  key={`${index}gte`}
                                  name={[field.name, "gte"]}
                                  rules={[
                                    {
                                      required: true
                                      //message: t("general.validation.required"),
                                    }
                                  ]}
                                >
                                  <InputNumber suffix="hrs" />
                                </Form.Item>

                                <Form.Item
                                  label={t("bodyshop.fields.ssbuckets.lt")}
                                  key={`${index}lt`}
                                  name={[field.name, "lt"]}
                                >
                                  <InputNumber suffix="hrs" />
                                </Form.Item>

                                <Form.Item
                                  label={t("bodyshop.fields.ssbuckets.target")}
                                  key={`${index}target`}
                                  name={[field.name, "target"]}
                                  rules={[
                                    {
                                      required: true
                                      //message: t("general.validation.required"),
                                    }
                                  ]}
                                >
                                  <InputNumber />
                                </Form.Item>
                              </div>
                              <div className="shop-info-scheduling__bucket-card-color">
                                <Form.Item key={`${index}color`} name={[field.name, "color"]}>
                                  <ColorPicker styles={SCHEDULING_BUCKET_COLOR_PICKER_STYLES} />
                                </Form.Item>
                              </div>
                            </div>
                          </InlineValidatedFormRow>
                        </Form.Item>
                      );
                    })
                  )}
                </div>
              </LayoutFormRow>
            );
          }}
        </Form.List>
      )}
    </div>
  );
}

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