import { CalculatorFilled } from "@ant-design/icons";
import { Button, Form, InputNumber, Popover, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";

export default function CABCpvrtCalculator({ disabled, form }) {
  const [visibility, setVisibility] = useState(false);

  const { t } = useTranslation();

  const handleFinish = async (values) => {
    logImEXEvent("job_ca_bc_pvrt_calculate");
    form.setFieldsValue({
      ca_bc_pvrt: ((values.rate || 0) * (values.days || 0)).toFixed(2)
    });
    form.setFields([{ name: "ca_bc_pvrt", touched: true }]);
    setVisibility(false);
  };

  const popContent = (
    <div>
      <Form onFinish={handleFinish} initialValues={{ rate: 1.5 }}>
        <Form.Item name="rate" label={t("jobs.labels.ca_bc_pvrt.rate")}>
          <InputNumber precision={2} min={0} />
        </Form.Item>
        <Form.Item name="days" label={t("jobs.labels.ca_bc_pvrt.days")}>
          <InputNumber precision={0} min={0} />
        </Form.Item>
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <Space>
            <Button type="primary" htmlType="submit">
              {t("general.actions.calculate")}
            </Button>
            <Button onClick={() => setVisibility(false)}>Close</Button>
          </Space>
        </div>
      </Form>
    </div>
  );

  return (
    <Popover destroyOnHidden content={popContent} open={visibility} disabled={disabled}>
      <Button disabled={disabled} onClick={() => setVisibility(true)} icon={<CalculatorFilled />} />
    </Popover>
  );
}
