import { MinusCircleFilled, PlusCircleFilled, WarningOutlined } from "@ant-design/icons";
import { Button, Form, Input, InputNumber, Select, Space, Switch } from "antd";
import { useTranslation } from "react-i18next";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyInput from "../form-items-formatted/currency-form-item.component";
import CiecaSelect from "../../utils/Ciecaselect";
import { bodyshopHasDmsKey } from "../../utils/dmsUtils.js";

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

export function BillFormItemsExtendedFormItem({
  value,
  bodyshop,
  form,
  record,
  disabled,
  responsibilityCenters,
  discount
}) {
  // const { billlineskeys } = form.getFieldsValue("billlineskeys");

  const { t } = useTranslation();
  if (!value)
    return (
      <Button
        icon={<PlusCircleFilled />}
        onClick={() => {
          const values = form.getFieldsValue("billlineskeys");

          form.setFieldsValue({
            ...values,
            billlineskeys: {
              ...(values.billlineskeys || {}),
              [record.id]: {
                joblineid: record.id,
                line_desc: record.line_desc,
                quantity: record.part_qty || 1,
                actual_price: record.act_price,
                cost_center: record.part_type
                  ? bodyshopHasDmsKey(bodyshop)
                    ? record.part_type
                    : responsibilityCenters.defaults && (responsibilityCenters.defaults.costs[record.part_type] || null)
                  : null
              }
            }
          });
        }}
      />
    );

  return (
    <Space wrap>
      <Form.Item label={t("billlines.fields.line_desc")} name={["billlineskeys", record.id, "line_desc"]}>
        <Input disabled={disabled} />
      </Form.Item>
      <Form.Item label={t("billlines.fields.quantity")} name={["billlineskeys", record.id, "quantity"]}>
        <InputNumber precision={0} min={0} disabled={disabled} />
      </Form.Item>
      <Form.Item label={t("billlines.fields.actual_price")} name={["billlineskeys", record.id, "actual_price"]}>
        <CurrencyInput
          min={0}
          disabled={disabled}
          onBlur={(e) => {
            const { billlineskeys } = form.getFieldsValue("billlineskeys");
            form.setFieldsValue({
              billlineskeys: {
                ...billlineskeys,
                [record.id]: {
                  ...billlineskeys[billlineskeys],
                  actual_cost: billlineskeys[billlineskeys].actual_cost
                    ? billlineskeys[billlineskeys].actual_cost
                    : Math.round((parseFloat(e.target.value) * (1 - discount) + Number.EPSILON) * 100) / 100
                }
              }
            });
          }}
        />
      </Form.Item>
      <Form.Item label={t("billlines.fields.actual_cost")} name={["billlineskeys", record.id, "actual_cost"]}>
        <CurrencyInput min={0} disabled={disabled} />
      </Form.Item>
      <Form.Item shouldUpdate>
        {() => {
          const line = value;
          if (!line) return null;
          const lineDiscount = (1 - Math.round((line.actual_cost / line.actual_price) * 100) / 100).toPrecision(2);

          if (lineDiscount - discount === 0) return <div />;
          return <WarningOutlined style={{ color: "red" }} />;
        }}
      </Form.Item>
      <Form.Item label={t("billlines.fields.cost_center")} name={["billlineskeys", record.id, "cost_center"]}>
        <Select 
          showSearch 
          style={{ minWidth: "3rem" }} 
          disabled={disabled}
          options={
            bodyshopHasDmsKey(bodyshop)
              ? CiecaSelect(true, false)
              : responsibilityCenters.costs.map((item) => ({ value: item.name, label: item.name }))
          }
        />
      </Form.Item>
      <Form.Item label={t("billlines.fields.location")} name={["billlineskeys", record.id, "location"]}>
        <Select 
          disabled={disabled}
          options={bodyshop.md_parts_locations.map((loc) => ({ value: loc, label: loc }))}
        />
      </Form.Item>
      <Form.Item
        label={t("billlines.fields.deductedfromlbr")}
        name={["billlineskeys", record.id, "deductedfromlbr"]}
        valuePropName="checked"
      >
        <Switch disabled={disabled} />
      </Form.Item>
      <Form.Item shouldUpdate style={{ display: "inline-block" }}>
        {() => {
          if (form.getFieldsValue("billlineskeys").billlineskeys[record.id].deductedfromlbr)
            return (
              <div>
                <Form.Item
                  label={t("joblines.fields.mod_lbr_ty")}
                  rules={[
                    {
                      required: true
                      //message: t("general.validation.required"),
                    }
                  ]}
                  name={["billlineskeys", record.id, "lbr_adjustment", "mod_lbr_ty"]}
                >
                  <Select 
                    allowClear
                    options={CiecaSelect(false, true)}
                  />
                </Form.Item>
                <Form.Item
                  label={t("jobs.labels.adjustmentrate")}
                  name={["billlineskeys", record.id, "lbr_adjustment", "rate"]}
                  initialValue={bodyshop.default_adjustment_rate}
                  rules={[
                    {
                      required: true
                      //message: t("general.validation.required"),
                    }
                  ]}
                >
                  <InputNumber precision={2} min={0.01} />
                </Form.Item>
              </div>
            );
          return <></>;
        }}
      </Form.Item>

      <Form.Item
        label={t("billlines.fields.federal_tax_applicable")}
        name={["billlineskeys", record.id, "applicable_taxes", "federal"]}
        valuePropName="checked"
      >
        <Switch disabled={disabled} />
      </Form.Item>
      <Form.Item
        label={t("billlines.fields.state_tax_applicable")}
        name={["billlineskeys", record.id, "applicable_taxes", "state"]}
        valuePropName="checked"
      >
        <Switch disabled={disabled} />
      </Form.Item>
      <Form.Item
        label={t("billlines.fields.local_tax_applicable")}
        name={["billlineskeys", record.id, "applicable_taxes", "local"]}
        valuePropName="checked"
      >
        <Switch disabled={disabled} />
      </Form.Item>

      <Button
        icon={<MinusCircleFilled />}
        onClick={() => {
          const values = form.getFieldsValue("billlineskeys");

          form.setFieldsValue({
            ...values,
            billlineskeys: {
              ...(values.billlineskeys || {}),
              [record.id]: null
            }
          });
        }}
      />
    </Space>
  );
}
