import { h } from "@stencil/core";
import { intl } from "../../../global/global";
import { createStyleSheet } from "../../../styling/JSS";
import { FORM_STEPS } from "../data";
import { PHONE_EXTENSIONS } from "../phoneExtensions";
import LoadingView from "../sqm-tax-and-cash/LoadingView";
import { formatErrorMessage, validateBillingField } from "../utils";
const style = {
  FormWrapper: {},
  ErrorInput: {
    "&::part(base)": {
      border: "var(--sqm-border-thickness, 1px) solid var(--sqm-danger-color-border)",
      borderRadius: "var(--sl-input-border-radius-medium)",
    },
    "&::part(help-text)": {
      color: "var(--sqm-danger-color-text)",
    },
  },
  ErrorText: {
    color: "var(--sqm-danger-color-text)",
    marginTop: "10px",
  },
  TextContainer: {
    display: "flex",
    justifyContent: "flex-start",
    flexDirection: "column",
    gap: "24px",
    paddingBottom: "16px",
  },
  InputContainer: {
    display: "flex",
    justifyContent: "flex-start",
    flexDirection: "column",
    gap: "24px",
    paddingBottom: "36px",
    maxWidth: "450px",
  },
  SearchInput: {
    padding: "var(--sl-spacing-x-small)",
  },
  BtnContainer: {
    paddingTop: "36px",
    display: "flex",
    gap: "8px",
  },
  CheckboxWrapper: {
    display: "flex",
    justifyContent: "flex-start",
    flexDirection: "column",
  },
  BoldText: {
    fontWeight: "bold",
  },
  RoundedCheckbox: {
    "&::part(control)": {
      borderRadius: "50%",
    },
  },
  PageDescriptionText: {
    color: "var(--sqm-text-subdued)",
    fontSize: "var(--sl-font-size-medium)",
  },
  PhoneInputsSection: {
    display: "flex",
    flexDirection: "column",
    gap: "4px",
    "& p": {
      fontSize: "var(--sl-font-size-small)",
      color: "var(--sqm-input-label-color)",
      fontWeight: "var(--sl-font-weight-semibold)",
    },
  },
  PhoneInputsContainer: {
    display: "flex",
    gap: "4px",
    width: "100%",
    "& #phoneNumber": {
      width: "100%",
      minWidth: "0px",
    },
  },
};
const sheet = createStyleSheet(style);
const styleString = sheet.toString();
const vanillaStyle = `
    :host{
      display: block;   
    }
    * {
       margin: 0;
       padding: 0;
       box-sizing: border-box;
    }
    a {
      color: var(--sqm-text);
      color: inherit !important;
      text-decoration: underline;
    }

    p {
      line-height: 18px;
      font-size: var(--sl-font-size-small);
    }

    sl-radio-group::part(base) {
      display: flex;
      flex-direction: column;
    }

    sl-select#phoneNumberCountryCode::part(menu) {
      min-width: 250px;
    }

    sl-button[type="primary"]::part(base){
        background-color: var(--sqm-primary-button-background);
        color: var(--sqm-primary-button-color);
        border-color: var(--sqm-primary-button-color-border);
        border-radius: var(--sqm-primary-button-radius);
    }

    sl-button[type="primary"]::part(base):hover{
        background-color: var(--sqm-primary-button-background-hover);
    }

    sl-button[type="primary"]::part(base):focus{
        box-shadow: none;
    }

    sl-button[type="secondary"]::part(base){
        background-color: var(--sqm-secondary-button-background);
        color: var(--sqm-secondary-button-color);
        border-color: var(--sqm-secondary-button-color-border);
        border-radius: var(--sqm-secondary-button-radius);
    }

    sl-button[type="secondary"]::part(base):hover{
        background-color: var(--sqm-secondary-button-background-hover);
    }



*::part(primarybutton-base){
  background-color: var(--sqm-primary-button-background);
  color: var(--sqm-primary-button-color);
  border-color: var(--sqm-primary-button-color-border);
  border-radius: var(--sqm-primary-button-radius);
}

*::part(primarybutton-base):hover{
  background-color: var(--sqm-primary-button-background-hover);
}

*::part(primarybutton-base):focus{
  box-shadow: none;
}

*::part(secondarybutton-base){
  background-color: var(--sqm-secondary-button-background);
  color: var(--sqm-secondary-button-color);
  border-color: var(--sqm-secondary-button-color-border);
  border-radius: var(--sqm-secondary-button-radius);
}

*::part(secondarybutton-base):hover{
  background-color: var(--sqm-secondary-button-background-hover);
}

*::part(secondarybutton-base){
  background-color: var(--sqm-secondary-button-background);
  color: var(--sqm-secondary-button-color);
  border-color: var(--sqm-secondary-button-color-border);
  border-radius: var(--sqm-secondary-button-radius);
  width: max-content;
  display: flex;
  margin: auto;
}

*::part(secondarybutton-base):hover{
  background: var(--sqm-secondary-button-background-hover);
}

    sl-input::part(label),
    sl-select::part(label),
    sl-textarea::part(label){
      font-size: var(--sqm-input-label-font-size, var(--sl-input-font-size-small));
      font-weight: var(--sl-font-weight-semibold);
      color: var(--sqm-input-label-color, var(--sqm-text), black);
    }

    /* Corrected: Target sl-input, sl-select, sl-textarea base elements */
    sl-input::part(base),
    sl-dropdown::part(base),
    sl-textarea::part(base){
      background-color: var(--sqm-input-background, #fff);
      border-radius: var(--sqm-input-border-radius, var(--sl-input-border-radius-large), 0.25rem);
      color: var(--sqm-input-color, white);
      border-width: var(--sqm-border-thickness, 1px);
      border-style: solid; 
      border-color: var(--sqm-input-border-color, #ccc); 
    }


    sl-select::part(menu) {
      background: var(--sqm-input-background, inherit);
      color: var(--sqm-input-color, inherit);
      border:none;
    }

    sl-menu-item::part(base) {
      color: var(--sqm-input-color);
    }

     sl-menu-item::part(base):hover {
      background-color: var(--sqm-input-border-color-hover);
    }

    sl-select::part(panel) {
      border-radius: var(--sqm-border-radius-normal);
    }

    sl-select::part(help-text) {
      color: var(--sqm-text-subdued, var(--sl-input-help-text-color, #6c757d));
    }

    sl-input::part(base):focus,
    sl-select::part(base):focus, /* Corrected part name for sl-select */
    sl-textarea::part(base):focus { /* Corrected part name for sl-textarea */
      border: var(--sqm-input-focus-border, 1px solid var(--sl-input-border-color-focus, #007bff)); /* Added fallback for --sl-input-border-color-focus */
    }

    sl-input[disabled]::part(base),
    sl-select[disabled]::part(base),
    sl-textarea[disabled]::part(base){
      background: var(--sqm-input-disabled-background, #f5f5f5);
      border-color: var(--sl-input-border-color-disabled, #e0e0e0); /* Example disabled border color */
    }


    sl-input::part(input):-webkit-autofill {
      box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
      -webkit-text-fill-color: var(--sqm-input-color, white) !important;
    }

    sl-input::part(input):-webkit-autofill:hover {
      box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
      -webkit-text-fill-color: var(--sqm-input-color, white) !important;
    }

    sl-input::part(input):-webkit-autofill:focus {
      box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
      -webkit-text-fill-color: var(--sqm-input-color, white) !important;
    }

    sl-checkbox::part(label){
      color: var(--sqm-text);
    }

    sl-checkbox[checked]::part(control){
      background-color: var(--sqm-input-border-color-focus);
    }

    sl-checkbox[checked]::part(checked-icon){
      color: var(--sqm-input-background);
    }
`;
export const UserInfoFormView = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
  const { states, states: { formState }, callbacks, text, refs, data, } = props;
  const { classes } = sheet;
  const bankingCollectionText = intl.formatMessage({
    id: "bankingCollectionText",
    defaultMessage: text.allowBankingCollection,
  }, {
    termsAndConditionsLink: (h("a", { href: text.termsAndConditionsLink, target: "_blank" }, text.termsAndConditionsLabel)),
  });
  let regionLabel = undefined;
  switch (data.regionLabelEnum) {
    case "STATE":
      regionLabel = text.state;
      break;
    case "PROVINCE":
      regionLabel = text.province;
      break;
    case "REGION":
      regionLabel = text.region;
      break;
    default:
      regionLabel = text.state;
  }
  function isDisabledPartnerInput(field) {
    var _a;
    return states.isPartner && !!((_a = data.partnerData) === null || _a === void 0 ? void 0 : _a[field]);
  }
  function isDisabledUserInput(field) {
    var _a;
    return states.isUser && !!((_a = data.userData) === null || _a === void 0 ? void 0 : _a[field]);
  }
  return (h("sl-form", { class: classes.FormWrapper, "onSl-submit": callbacks.onSubmit, ref: (el) => (refs.formRef.current = el), novalidate: true },
    h("style", { type: "text/css" },
      styleString,
      vanillaStyle),
    states.loadingError && (h("div", null,
      h("sqm-form-message", { type: "error" },
        h("p", { part: "alert-title" }, text.error.loadingErrorAlertHeader),
        h("p", { part: "alert-description" }, intl.formatMessage({
          id: "loadingErrorAlertDescription",
          defaultMessage: text.error.loadingErrorAlertDescription,
        }, {
          supportLink: (h("a", { target: "_blank", href: `mailto:advocate-support@impact.com` }, text.supportLink)),
        }))))),
    states.loading ? (h(LoadingView, null)) : (h("div", null,
      h("div", { class: classes.TextContainer },
        h("div", null,
          !states.hideSteps && (h("p", null, intl.formatMessage({
            id: "formStep",
            defaultMessage: text.formStep,
          }, { step: states.step, count: FORM_STEPS }))),
          h("h3", null, text.personalInformation),
          h("p", { class: classes.PageDescriptionText }, text.taxAndPayoutsDescription))),
      ((_a = formState.errors) === null || _a === void 0 ? void 0 : _a.general) && (h("sqm-form-message", { type: "error" },
        h("p", { part: "alert-title" }, text.error.generalTitle),
        h("p", { part: "alert-description" }, intl.formatMessage({
          id: "generalDescription",
          defaultMessage: text.error.generalDescription,
        }, {
          supportLink: (h("a", { target: "_blank", href: `mailto:advocate-support@impact.com` }, text.supportLink)),
        })))),
      (states.isPartner || states.isUser) && (h("sqm-form-message", { loading: states.loading, type: "info" },
        h("p", { part: "alert-title" }, text.isPartnerAlertHeader),
        h("p", { part: "alert-description" }, intl.formatMessage({
          id: "isPartnerAlertDescription",
          defaultMessage: text.isPartnerAlertDescription,
        }, {
          supportLink: (h("a", { target: "_blank", href: `mailto:advocate-support@impact.com` }, text.supportLink)),
        })))),
      h("div", null,
        h("div", { class: classes.InputContainer },
          h("sl-input", Object.assign({ class: "ErrorInput", exportparts: "label: input-label, base: input-base", value: formState.firstName, label: text.firstName, disabled: states.disabled || isDisabledUserInput("firstName") }, (((_b = formState.errors) === null || _b === void 0 ? void 0 : _b.firstName) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.firstName, formState.errors.firstName),
          }
            : {}), { id: "firstName", name: "/firstName", required: true })),
          h("sl-input", Object.assign({ exportparts: "label: input-label, base: input-base", value: formState.lastName, label: text.lastName, disabled: states.disabled || isDisabledUserInput("lastName") }, (((_c = formState.errors) === null || _c === void 0 ? void 0 : _c.lastName) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.lastName, formState.errors.lastName),
          }
            : {}), { id: "lastName", name: "/lastName", required: true })),
          h("sl-input", { exportparts: "label: input-label, base: input-base", value: formState.email, label: text.email, disabled: true, id: "email", name: "/email", required: true }),
          h("sl-select", Object.assign({ id: "countryCode", exportparts: "label: input-label, base: input-base", name: "/countryCode", label: text.country, value: formState.countryCode, disabled: states.disabled || isDisabledPartnerInput("countryCode") }, (((_d = formState.errors) === null || _d === void 0 ? void 0 : _d.countryCode) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.country, formState.errors.countryCode),
          }
            : {}), { required: true, "onSl-select": (e) => callbacks.onFormChange("countryCode", e) }),
            h("sl-input", { class: classes.SearchInput, placeholder: text.searchForCountryText, onKeyDown: (e) => {
                // Stop shoelace intercepting key presses
                e.stopPropagation();
              }, "onSl-input": (e) => {
                callbacks.setCountrySearch(e.target.value);
              } }), (_e = data === null || data === void 0 ? void 0 : data.countries) === null || _e === void 0 ? void 0 :
            _e.map((c) => (h("sl-menu-item", { value: c.countryCode }, c.displayName))), (_f = data === null || data === void 0 ? void 0 : data.allCountries) === null || _f === void 0 ? void 0 :
            _f.map((c) => (h("sl-menu-item", { value: c.countryCode, style: { display: "none" } }, c.displayName)))),
          h("div", { class: classes.PhoneInputsSection },
            h("p", null, text.phoneNumber),
            h("div", { class: classes.PhoneInputsContainer },
              h("sl-select", Object.assign({ id: "phoneNumberCountryCode", exportparts: "label: input-label, base: input-base", name: "/phoneNumberCountryCode", value: formState.phoneNumberCountryCode, disabled: states.disabled ||
                  isDisabledPartnerInput("phoneNumberCountryCode"), ref: (el) => (refs.phoneCountryRef.current = el) }, (((_g = formState.errors) === null || _g === void 0 ? void 0 : _g.phoneNumberCountryCode) ? {
                class: classes.ErrorInput,
              }
                : {}), { required: true, "onSl-select": (e) => callbacks.onFormChange("phoneCountry", e) }),
                h("sl-input", { class: classes.SearchInput, placeholder: text.searchForCountryText, onKeyDown: (e) => {
                    // Stop shoelace intercepting key presses
                    e.stopPropagation();
                  }, "onSl-input": (e) => {
                    callbacks.setPhoneCountrySearch(e.target.value);
                  } }), (_h = data === null || data === void 0 ? void 0 : data.phoneCountries) === null || _h === void 0 ? void 0 :
                _h.map((c) => {
                  var _a, _b;
                  return (h("sl-menu-item", { value: c.countryCode },
                    h("div", { slot: "prefix" }, `${(_a = PHONE_EXTENSIONS[c.countryCode]) === null || _a === void 0 ? void 0 : _a.name} `), (_b = PHONE_EXTENSIONS[c.countryCode]) === null || _b === void 0 ? void 0 :
                    _b.dial_code));
                }), (_j = data === null || data === void 0 ? void 0 : data.allCountries) === null || _j === void 0 ? void 0 :
                _j.map((c) => {
                  var _a, _b;
                  return (h("sl-menu-item", { value: c.countryCode, style: { display: "none" } },
                    h("div", { slot: "prefix" }, `${(_a = PHONE_EXTENSIONS[c.countryCode]) === null || _a === void 0 ? void 0 : _a.name} `), (_b = PHONE_EXTENSIONS[c.countryCode]) === null || _b === void 0 ? void 0 :
                    _b.dial_code));
                })),
              h("sl-input", Object.assign({ exportparts: "label: input-label, base: input-base", id: "phoneNumber", name: "/phoneNumber", value: formState.phoneNumber, validationError: ({ value }) => {
                  // Naive phone number validation
                  validateBillingField(/[a-zA-Z]+/, value) &&
                    formatErrorMessage(text.phoneNumber, text.error.fieldInvalidError);
                }, disabled: states.disabled || isDisabledPartnerInput("phoneNumber") }, (((_k = formState.errors) === null || _k === void 0 ? void 0 : _k.phoneNumber) ? {
                class: classes.ErrorInput,
                helpText: formatErrorMessage(text.phoneNumber, formState.errors.phoneNumber),
              }
                : {}), { required: true })))),
          h("sl-input", Object.assign({ exportparts: "label: input-label, base: input-base", label: text.address, id: "address", name: "/address", value: formState.address, validationError: ({ value }) => 
            // Checks for non-ASCII characters
            !validateBillingField(/^[\x20-\xFF]+$/, value) &&
              formatErrorMessage(text.address, text.error.invalidCharacterError), disabled: states.disabled || isDisabledPartnerInput("billingAddress") }, (((_l = formState.errors) === null || _l === void 0 ? void 0 : _l.address) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.address, formState.errors.address),
          }
            : {}), { required: true })),
          h("sl-input", Object.assign({ exportparts: "label: input-label, base: input-base", label: text.city, id: "city", name: "/city", value: formState.city, validationError: ({ value }) => 
            // Checks for non-ASCII characters
            !validateBillingField(/^[\x20-\xFF]+$/, value) &&
              formatErrorMessage(text.city, text.error.invalidCharacterError), disabled: states.disabled || isDisabledPartnerInput("billingCity") }, (((_m = formState.errors) === null || _m === void 0 ? void 0 : _m.city) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.city, formState.errors.city),
          }
            : {}), { required: true })),
          !states.hideState && (h("sl-select", Object.assign({ label: regionLabel, exportparts: "label: input-label, base: input-base", id: "state", name: "/state", value: formState.state, disabled: states.disabled || isDisabledPartnerInput("billingState") }, (((_o = formState.errors) === null || _o === void 0 ? void 0 : _o.state) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.state, formState.errors.state),
          }
            : {}), { required: true }), (_p = data.regions) === null || _p === void 0 ? void 0 : _p.map((r) => (h("sl-menu-item", { value: r.value }, r.label))))),
          h("sl-input", Object.assign({ label: text.postalCode, exportparts: "label: input-label, base: input-base", id: "postalCode", name: "/postalCode", value: formState.postalCode, disabled: states.disabled || isDisabledPartnerInput("billingPostalCode") }, (((_q = formState.errors) === null || _q === void 0 ? void 0 : _q.postalCode) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.postalCode, formState.errors.postalCode),
          }
            : {}), { required: true })),
          h("sl-select", Object.assign({ id: "currency", exportparts: "label: input-label, base: input-base", name: "/currency", label: text.currency, menu: true, value: formState.currency, disabled: states.disabled || isDisabledPartnerInput("currency"), helpText: text.currencyHelpText }, (((_r = formState.errors) === null || _r === void 0 ? void 0 : _r.currency) ? {
            class: classes.ErrorInput,
            helpText: formatErrorMessage(text.currency, formState.errors.currency),
          }
            : {}), { required: true, ref: (el) => (refs.currencyRef.current = el) }),
            h("sl-input", { class: classes.SearchInput, placeholder: text.searchForCurrencyText, onKeyDown: (e) => {
                // Stop shoelace intercepting key presses
                e.stopPropagation();
              }, "onSl-input": (e) => {
                callbacks.setCurrencySearch(e.target.value);
              } }), (_s = data === null || data === void 0 ? void 0 : data.currencies) === null || _s === void 0 ? void 0 :
            _s.map((c) => (h("sl-menu-item", { value: c.currencyCode },
              c.currencyCode,
              " - ",
              c.displayName))), (_t = data === null || data === void 0 ? void 0 : data.allCurrencies) === null || _t === void 0 ? void 0 :
            _t.map((c) => (h("sl-menu-item", { value: c.currencyCode, style: { display: "none" } },
              c.currencyCode,
              " - ",
              c.displayName)))),
          h("div", { class: classes.CheckboxWrapper },
            h("sl-checkbox", { checked: formState.allowBankingCollection === true, "onSl-change": (e) => {
                e.target.value = e.target.checked;
              }, disabled: states.disabled, required: true, value: formState.allowBankingCollection, id: "allowBankingCollection", name: "/allowBankingCollection" }, bankingCollectionText),
            ((_u = formState.errors) === null || _u === void 0 ? void 0 : _u.allowBankingCollection) && (h("p", { class: classes.ErrorText }, formatErrorMessage(text.termsAndConditionsLabel, formState.errors.allowBankingCollection))))),
        h("sl-button", { type: "primary", disabled: states.disabled, submit: true, exportparts: "base: primarybutton-base" }, text.continueButton))))));
};
