import { useQuery } from "@apollo/client/react";
import { Button, Form, Input, InputNumber, Modal, Radio, Select } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { SEARCH_VENDOR_AUTOCOMPLETE_WITH_ADDR } from "../../graphql/vendors.queries";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import VendorSearchSelect from "../vendor-search-select/vendor-search-select.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function Jobd3RdPartyModal({ bodyshop, jobId, job, technician }) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { data: VendorAutoCompleteData } = useQuery(SEARCH_VENDOR_AUTOCOMPLETE_WITH_ADDR, {
    skip: !isModalVisible,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const notification = useNotification();

  const showModal = () => {
    form.setFieldsValue({
      ded_amt: job.ded_amt,
      depreciation: job.depreciation_taxes,
      custgst: job.ca_customer_gst
    });
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.submit();
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };
  const handleFinish = (values) => {
    const { sendtype, ...restVals } = values;

    GenerateDocument(
      {
        name: TemplateList("job_special").special_thirdpartypayer.key,
        variables: { id: jobId },
        context: restVals
      },
      { subject: TemplateList("job_special").special_thirdpartypayer.subject },
      sendtype,
      null,
      notification
    );
  };

  const handleInsSelect = (value) => {
    const selectedVendor = bodyshop.md_ins_cos.find(s => s.name === value);
    if (selectedVendor) {
      form.setFieldsValue({
        addr1: selectedVendor.name,
        addr2: selectedVendor.street1,
        addr3: selectedVendor.street2,
        city: selectedVendor.city,
        state: selectedVendor.state,
        zip: selectedVendor.zip,
        vendorid: null
      });
    }
  };

  const handleVendorSelect = (vendorid) => {
    const vendor = VendorAutoCompleteData?.vendors?.filter((v) => v.id === vendorid)[0];
    if (vendor) {
      form.setFieldsValue({
        addr1: vendor.name,
        addr2: vendor.street1,
        addr3: vendor.street2,
        city: vendor.city,
        state: vendor.state,
        zip: vendor.zip,
        ins_co_id: null
      });
    }
  };

  return (
    <>
      <Button onClick={showModal}>{t("printcenter.jobs.3rdpartypayer")}</Button>
      <Modal open={isModalVisible} onOk={handleOk} onCancel={handleCancel} getContainer={() => document.body}>
        <Form onFinish={handleFinish} autoComplete={"off"} layout="vertical" form={form}>
          <Form.Item label={t("bills.fields.vendor")} name="vendorid">
            <VendorSearchSelect options={VendorAutoCompleteData?.vendors} onSelect={handleVendorSelect} />
          </Form.Item>
          <Form.Item label={t("bodyshop.fields.md_ins_co.name")} name="ins_co_id">
            <Select
              onSelect={handleInsSelect}
              options={bodyshop.md_ins_cos.map((s) => ({
                value: s.name,
                label: s.name
              }))}
            />
          </Form.Item>
          <LayoutFormRow grow>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.addr1")} name="addr1">
              <Input />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.addr2")} name="addr2">
              <Input />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.addr3")} name="addr3">
              <Input />
            </Form.Item>
          </LayoutFormRow>
          <LayoutFormRow grow>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.city")} name="city">
              <Input />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.state")} name="state">
              <Input />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.zip")} name="zip">
              <Input />
            </Form.Item>
          </LayoutFormRow>
          <LayoutFormRow grow>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.attn")} name="attn">
              <Input />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.refnumber")} name="ponumber">
              <Input />
            </Form.Item>
          </LayoutFormRow>
          <LayoutFormRow grow>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.ded_amt")} name="ded_amt">
              <InputNumber min={0} precision={2} />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.depreciation")} name="depreciation">
              <InputNumber min={0} precision={2} />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.custgst")} name="custgst">
              <InputNumber min={0} precision={2} />
            </Form.Item>
            <Form.Item label={t("printcenter.jobs.3rdpartyfields.other")} name="other">
              <InputNumber min={0} precision={2} />
            </Form.Item>
          </LayoutFormRow>
          <Form.Item
            label={t("printcenter.jobs.3rdpartyfields.sendtype")}
            name="sendtype"
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <Radio.Group>
              {!technician ? <Radio value={"e"}>{t("parts_orders.labels.email")}</Radio> : null}
              <Radio value={"p"}>{t("parts_orders.labels.print")}</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
