import { Button, Card, DatePicker, Form, Popover, Radio, Space } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { selectTechnician } from "../../redux/tech/tech.selectors";
import DatePIckerRanges from "../../utils/DatePickerRanges";
import dayjs from "../../utils/day";
import { GenerateDocument } from "../../utils/RenderTemplate";
import { TemplateList } from "../../utils/TemplateConstants";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function TechJobPrintTickets({ bodyshop, technician, event, attendacePrint }) {
  const { t } = useTranslation();

  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState(false);
  const Templates = TemplateList("report_center");
  const notification = useNotification();

  useEffect(() => {
    if (visibility && event) {
      form.setFieldsValue(event);
    }
  }, [visibility, form, event]);

  const handleFinish = async (values) => {
    logImEXEvent("schedule_manual_event");

    setLoading(true);
    const start = values.dates[0];
    const end = values.dates[1];

    try {
      await GenerateDocument(
        {
          name: attendacePrint === true ? Templates.attendance_employee.key : Templates.timetickets_employee.key,
          variables: {
            ...(start ? { start: dayjs(start).startOf("day").format("YYYY-MM-DD") } : {}),
            ...(end ? { end: dayjs(end).endOf("day").format("YYYY-MM-DD") } : {}),
            ...(start ? { starttz: dayjs(start).startOf("day") } : {}),
            ...(end ? { endtz: dayjs(end).endOf("day") } : {}),

            id: technician.id
          }
        },
        {
          to: technician.email,
          subject:
            attendacePrint === true ? Templates.attendance_employee.subject : Templates.timetickets_employee.subject
        },
        values.sendby,
        bodyshop,
        notification
      );
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
      setVisibility(false);
      form.resetFields();
    }
  };

  const overlay = (
    <Card>
      <div>
        <Form form={form} layout="vertical" onFinish={handleFinish}>
          <Form.Item
            label={t("reportcenter.labels.dates")}
            name="dates"
            rules={[
              {
                required: true
                //message: t("general.validation.required"),
              }
            ]}
          >
            <DatePicker.RangePicker presets={DatePIckerRanges} format={"MM/DD/YYYY"} />
          </Form.Item>
          <Form.Item dependencies={["dates"]}>
            {() => {
              return (
                <Form.Item label={t("general.labels.sendby")} name="sendby" initialValue="p">
                  <Radio.Group>
                    <Radio value="e">{t("general.labels.email")}</Radio>
                    <Radio value="p">{t("general.labels.print")}</Radio>
                  </Radio.Group>
                </Form.Item>
              );
            }}
          </Form.Item>
          <Space wrap>
            <Button type="primary" onClick={() => form.submit()}>
              {t("reportcenter.actions.generate")}
            </Button>
            <Button
              onClick={() => {
                setVisibility(false);
                form.resetFields();
              }}
            >
              {t("general.actions.cancel")}
            </Button>
          </Space>
        </Form>
      </div>
    </Card>
  );

  const handleClick = () => {
    setVisibility(true);
  };

  return (
    <Popover content={overlay} open={visibility}>
      <Button loading={loading} onClick={handleClick}>
        {t("general.labels.reports")}
      </Button>
    </Popover>
  );
}
