import { SearchOutlined } from "@ant-design/icons";
import { Button, Checkbox, DatePicker, Form, Input } from "antd";
import React from "react";
import ipcTypes from "../../../ipc.types";
const { ipcRenderer } = window;

export default function JobsSearchFieldsMolecule({ callSearchQuery }) {
  const [form] = Form.useForm();

  const handleFinish = (values) => {
    ipcRenderer.send(ipcTypes.app.toMain.track, {
      event: "SEARCH_JOBS",
      query: values.search,
      datesIncluded: !!values.dateRange,
    });
    callSearchQuery({
      variables: {
        search: values.search || "",
        startDate: (values.dateRange && values.dateRange[0]) || null,
        endDate: (values.dateRange && values.dateRange[1]) || null,
        ...(values.closeDateIsNull
          ? { closeDateIsNull: values.closeDateIsNull }
          : {}),
      },
    });
  };

  return (
    <div>
      <Form
        autoComplete="new-password"
        size="small"
        onFinish={handleFinish}
        form={form}
      >
        <Form.Item name="search">
          <Input placeholder="Search by Claim # or Name" />
        </Form.Item>
        <Form.Item name="dateRange" rules={[{ type: "array" }]}>
          <DatePicker.RangePicker />
        </Form.Item>
        <Form.Item name="closeDateIsNull" valuePropName="checked">
          <Checkbox>Only Jobs with No Ready For Payment Date</Checkbox>
        </Form.Item>
        <Form.Item shouldUpdate>
          {() => {
            const disabled =
              (!!!form.getFieldValue("search") &&
                !!!form.getFieldValue("dateRange") &&
                !form.getFieldValue("closeDateIsNull")) ||
              (form.getFieldValue("search") &&
                form.getFieldValue("search") !== "" &&
                form.getFieldValue("search")?.length < 4);

            return (
              <Button
                type="primary"
                disabled={disabled}
                htmlType="submit"
                onClick={() => form.submit()}
              >
                <SearchOutlined />
                Search
              </Button>
            );
          }}
        </Form.Item>
      </Form>
    </div>
  );
}
