import { DeleteFilled } from "@ant-design/icons";
import { useApolloClient } from "@apollo/client/react";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Button, Divider, Form, Input, InputNumber, Select, Space, Switch } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import { useTranslation } from "react-i18next";
import { CHECK_VENDOR_NAME } from "../../graphql/vendors.queries";
import FormFieldsChanged from "../form-fields-changed-alert/form-fields-changed-alert.component";
import FormItemEmail from "../form-items-formatted/email-form-item.component";
import PhoneFormItem, { PhoneItemFormatterValidation } from "../form-items-formatted/phone-form-item.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import VendorsPhonebookAdd from "../vendors-phonebook-add/vendors-phonebook-add.component";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { selectIsPartsEntry } from "../../redux/application/application.selectors.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  isPartsEntry: selectIsPartsEntry
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(VendorsFormComponent);

export function VendorsFormComponent({ bodyshop, form, formLoading, handleDelete, selectedvendor, isPartsEntry }) {
  const { t } = useTranslation();
  const client = useApolloClient();

  const {
    treatments: { DmsAp }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["DmsAp"],
    splitKey: bodyshop?.imexshopid
  });

  const { getFieldValue } = form;
  return (
    <div>
      <PageHeader
        title={<Form.Item shouldUpdate>{() => form.getFieldValue("name")}</Form.Item>}
        extra={
          <Space>
            <Form.Item label={t("vendors.fields.active")} name="active" initialValue={true} valuePropName="checked">
              <Switch />
            </Form.Item>
            <Button onClick={() => form.submit()} type="primary" loading={formLoading}>
              {t("general.actions.save")}
            </Button>
            <Button
              type="primary"
              danger
              disabled={selectedvendor === "new"}
              onClick={handleDelete}
              loading={formLoading}
            >
              {t("general.actions.delete")}
            </Button>
            {!isPartsEntry && <VendorsPhonebookAdd form={form} disabled={form.isFieldsTouched()} />}
          </Space>
        }
      />
      <FormFieldsChanged form={form} />
      <LayoutFormRow grow>
        <Form.Item
          label={t("vendors.fields.name")}
          name="name"
          validateTrigger="onBlur"
          hasFeedback
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            },
            () => ({
              async validator(rule, value) {
                if (value) {
                  const response = await client.query({
                    query: CHECK_VENDOR_NAME,
                    variables: {
                      name: value
                    }
                  });

                  if (response.data.vendors_aggregate.aggregate.count === 0) {
                    return Promise.resolve();
                  } else if (
                    response.data.vendors_aggregate.nodes.length === 1 &&
                    response.data.vendors_aggregate.nodes[0].id === form.getFieldValue("id")
                  ) {
                    return Promise.resolve();
                  }
                  return Promise.reject(t("vendors.validation.unique_vendor_name"));
                } else {
                  return Promise.resolve();
                }
              }
            })
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label={t("vendors.fields.email")}
          rules={
            [
              // {
              //   type: "email",
              //   message: t("general.validation.invalidemail"),
              // },
            ]
          }
          name="email"
        >
          <FormItemEmail email={getFieldValue("email")} />
        </Form.Item>
        <Form.Item
          label={t("vendors.fields.phone")}
          name="phone"
          rules={[({ getFieldValue }) => PhoneItemFormatterValidation(getFieldValue, "phone")]}
        >
          <PhoneFormItem />
        </Form.Item>
      </LayoutFormRow>
      <LayoutFormRow grow>
        <Form.Item label={t("vendors.fields.street1")} name="street1">
          <Input />
        </Form.Item>
        <Form.Item label={t("vendors.fields.street2")} name="street2">
          <Input />
        </Form.Item>
        <Form.Item label={t("vendors.fields.city")} name="city">
          <Input />
        </Form.Item>
      </LayoutFormRow>
      <LayoutFormRow grow>
        <Form.Item label={t("vendors.fields.state")} name="state">
          <Input />
        </Form.Item>
        <Form.Item label={t("vendors.fields.zip")} name="zip">
          <Input />
        </Form.Item>
        <Form.Item label={t("vendors.fields.country")} name="country">
          <Input />
        </Form.Item>
      </LayoutFormRow>
      <LayoutFormRow grow>
        {!isPartsEntry && (
          <>
            <Form.Item label={t("vendors.fields.discount")} name="discount">
              <InputNumber min={0} max={1} precision={3} step={0.01} />
            </Form.Item>

            <Form.Item label={t("vendors.fields.due_date")} name="due_date">
              <InputNumber min={0} />
            </Form.Item>
          </>
        )}

        {
          // <Form.Item
          //   label={t("vendors.fields.cost_center")}
          //   rules={[
          //     { required: true, message: t("general.validation.required") },
          //   ]}
          //   name="cost_center"
          // >
          //   <Select style={{ width: "150px" }}>
          //     {responsibilityCenters.costs.map((item) => (
          //       <Select.Option key={item.name}>{item.name}</Select.Option>
          //     ))}
          //   </Select>
          // </Form.Item>
        }
      </LayoutFormRow>

      <Form.Item
        name="tags"
        label={t("vendors.fields.tags")}
        rules={[
          {
            //message: t("general.validation.required"),
            type: "array"
          }
        ]}
      >
        <Select mode="tags" />
      </Form.Item>
      {DmsAp.treatment === "on" && (
        <Form.Item label={t("vendors.fields.dmsid")} name="dmsid">
          <Input />
        </Form.Item>
      )}
      <Divider align="left">{t("vendors.labels.preferredmakes")}</Divider>
      <Form.List name="favorite">
        {(fields, { add, remove }) => {
          return (
            <div>
              {fields.map((field, index) => (
                <Form.Item key={field.key}>
                  <Space wrap>
                    <Form.Item
                      label={t("vendors.fields.make")}
                      key={`${index}make`}
                      name={[field.name]}
                      rules={[
                        {
                          required: true
                          //message: t("general.validation.required"),
                        }
                      ]}
                    >
                      <Input />
                    </Form.Item>

                    <DeleteFilled
                      onClick={() => {
                        remove(field.name);
                      }}
                    />
                  </Space>
                </Form.Item>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => {
                    add();
                  }}
                  style={{ width: "100%" }}
                >
                  {t("vendors.actions.newpreferredmake")}
                </Button>
              </Form.Item>
            </div>
          );
        }}
      </Form.List>
    </div>
  );
}
