import { DeleteFilled } from "@ant-design/icons";
import { useMutation, useQuery } from "@apollo/client";
import { Button, Card, Form, Input, InputNumber, notification, Space, Switch } from "antd";

import querystring from "query-string";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import CurrencyInput from "../form-items-formatted/currency-form-item.component";
import FormListMoveArrows from "../form-list-move-arrows/form-list-move-arrows.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";

import {
  INSERT_EMPLOYEE_TEAM,
  QUERY_EMPLOYEE_TEAM_BY_ID,
  UPDATE_EMPLOYEE_TEAM
} from "../../graphql/employee_teams.queries";
import EmployeeSearchSelectComponent from "../employee-search-select/employee-search-select.component";

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

export function ShopEmployeeTeamsFormComponent({ bodyshop }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const history = useNavigate();
  const search = querystring.parse(useLocation().search);

  const { error, data } = useQuery(QUERY_EMPLOYEE_TEAM_BY_ID, {
    variables: { id: search.employeeTeamId },
    skip: !search.employeeTeamId || search.employeeTeamId === "new",
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    if (data && data.employee_teams_by_pk) form.setFieldsValue(data.employee_teams_by_pk);
    else {
      form.resetFields();
    }
  }, [form, data, search.employeeTeamId]);

  const [updateEmployeeTeam] = useMutation(UPDATE_EMPLOYEE_TEAM);
  const [insertEmployeeTeam] = useMutation(INSERT_EMPLOYEE_TEAM);

  const handleFinish = async ({ employee_team_members, ...values }) => {
    if (search.employeeTeamId && search.employeeTeamId !== "new") {
      //Update a record.
      logImEXEvent("shop_employee_update");

      const result = await updateEmployeeTeam({
        variables: {
          employeeTeamId: search.employeeTeamId,
          employeeTeam: values,
          teamMemberUpdates: employee_team_members
            .filter((e) => e.id)
            .map((e) => {
              delete e.__typename;
              return { where: { id: { _eq: e.id } }, _set: e };
            }),
          teamMemberInserts: employee_team_members
            .filter((e) => e.id === null || e.id === undefined)
            .map((e) => ({ ...e, teamid: search.employeeTeamId })),
          teamMemberDeletes: data.employee_teams_by_pk.employee_team_members.filter(
            (e) => !employee_team_members.find((etm) => etm.id === e.id)
          )
        }
      });
      if (!result.errors) {
        notification["success"]({
          message: t("employees.successes.save")
        });
      } else {
        notification["error"]({
          message: t("employees.errors.save", {
            message: JSON.stringify(error)
          })
        });
      }
    } else {
      //New record, insert it.
      logImEXEvent("shop_employee_insert");

      insertEmployeeTeam({
        variables: {
          employeeTeam: {
            ...values,
            employee_team_members: { data: employee_team_members },
            bodyshopid: bodyshop.id
          }
        },
        refetchQueries: ["QUERY_TEAMS"]
      }).then((r) => {
        search.employeeTeamId = r.data.insert_employee_teams_one.id;
        history({ search: querystring.stringify(search) });
        notification["success"]({
          message: t("employees.successes.save")
        });
      });
    }
  };

  if (!search.employeeTeamId) return null;
  if (error) return <AlertComponent message={error.message} type="error" />;

  return (
    <Card
      extra={
        <Button type="primary" onClick={() => form.submit()}>
          {t("general.actions.save")}
        </Button>
      }
    >
      <Form onFinish={handleFinish} autoComplete={"off"} layout="vertical" form={form}>
        <LayoutFormRow>
          <Form.Item
            name="name"
            label={t("employee_teams.fields.name")}
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label={t("employee_teams.fields.active")} name="active" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item
            label={t("employee_teams.fields.max_load")}
            name="max_load"
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <InputNumber min={0} precision={1} />
          </Form.Item>
        </LayoutFormRow>
        <Form.List name={["employee_team_members"]}>
          {(fields, { add, remove, move }) => {
            return (
              <div>
                {fields.map((field, index) => (
                  <Form.Item key={field.key} style={{ padding: 0, margin: 2 }}>
                    <Form.Item label={t("employees.fields.id")} key={`${index}`} name={[field.name, "id"]} hidden>
                      <Input />
                    </Form.Item>
                    <LayoutFormRow grow>
                      <Form.Item
                        label={t("employee_teams.fields.employeeid")}
                        key={`${index}`}
                        name={[field.name, "employeeid"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <EmployeeSearchSelectComponent options={bodyshop.employees} />
                      </Form.Item>
                      <Form.Item
                        label={t("employee_teams.fields.percentage")}
                        key={`${index}`}
                        name={[field.name, "percentage"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <InputNumber min={0} max={100} precision={2} />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAA")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAA"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAB")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAB"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAD")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAD"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAE")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAE"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>

                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAF")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAF"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAG")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAG"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAM")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAM"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAR")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAR"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAS")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAS"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LAU")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LAU"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LA1")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LA1"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LA2")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LA2"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LA3")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LA3"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Form.Item
                        label={t("joblines.fields.lbr_types.LA4")}
                        key={`${index}`}
                        name={[field.name, "labor_rates", "LA4"]}
                        rules={[
                          {
                            required: true
                            //message: t("general.validation.required"),
                          }
                        ]}
                      >
                        <CurrencyInput />
                      </Form.Item>
                      <Space align="center">
                        <DeleteFilled
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                        <FormListMoveArrows move={move} index={index} total={fields.length} />
                      </Space>
                    </LayoutFormRow>
                  </Form.Item>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add();
                    }}
                    style={{ width: "100%" }}
                  >
                    {t("employee_teams.actions.newmember")}
                  </Button>
                </Form.Item>
              </div>
            );
          }}
        </Form.List>
      </Form>
    </Card>
  );
}

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