import { Col, DatePicker, Form, Input, Row, Select, Switch } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { FormDatePicker } from "../form-date-picker/form-date-picker.component.jsx";
import { createStructuredSelector } from "reselect";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors.js";
import dayjs from "../../utils/day";

import { connect } from "react-redux";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component.jsx";
import JobSearchSelectComponent from "../job-search-select/job-search-select.component.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser
});

const mapDispatchToProps = (dispatch) => ({});

export default connect(mapStateToProps, mapDispatchToProps)(TaskUpsertModalComponent);

export function TaskUpsertModalComponent({
  form,
  bodyshop,
  currentUser,
  selectedJobId,
  setSelectedJobId,
  selectedJobDetails,
  loading,
  error
}) {
  const { t } = useTranslation();
  const datePickerPresets = [
    { label: t("tasks.date_presets.today"), value: dayjs() },
    { label: t("tasks.date_presets.tomorrow"), value: dayjs().add(1, "day") },
    { label: t("tasks.date_presets.next_week"), value: dayjs().add(1, "week") },
    { label: t("tasks.date_presets.two_weeks"), value: dayjs().add(2, "weeks") },
    { label: t("tasks.date_presets.three_weeks"), value: dayjs().add(3, "weeks") },
    { label: t("tasks.date_presets.one_month"), value: dayjs().add(1, "month") },
    { label: t("tasks.date_presets.three_months"), value: dayjs().add(3, "month") }
  ];

  const clearRelations = () => {
    form.setFieldsValue({
      billid: null,
      partsorderid: null,
      joblineid: null
    });
  };

  /**
   * Change the selected job id
   * @param jobId
   */
  const changeJobId = (jobId) => {
    setSelectedJobId(jobId || null);
    // Reset the form fields when selectedJobId changes
    clearRelations();
  };

  if (loading || error) return <LoadingSkeleton active />;

  return (
    <>
      <Row gutter={[16, 16]}>
        <Col span={16}>
          <Form.Item
            label={t("tasks.fields.title")}
            name="title"
            rules={[
              {
                required: true
              }
            ]}
          >
            <Input placeholder={t("tasks.fields.title")} />
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item label={t("tasks.fields.priority")} name="priority" initialValue={3}>
            <Select
              options={[
                { value: 3, label: t("tasks.fields.priorities.low") },
                { value: 2, label: t("tasks.fields.priorities.medium") },
                { value: 1, label: t("tasks.fields.priorities.high") }
              ]}
            />
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            label={t("tasks.fields.completed")}
            name="completed"
            valuePropName="checked"
            initialValue={false}
            rules={[
              {
                required: true
              }
            ]}
          >
            <Switch />
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Form.Item
            name="jobid"
            initialValue={selectedJobId}
            label={t("tasks.fields.jobid")}
            rules={[
              {
                required: true
              }
            ]}
          >
            <JobSearchSelectComponent
              placeholder={t("tasks.placeholders.jobid")}
              onSelect={changeJobId}
              onClear={changeJobId}
              autoFocus={false}
            />
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Form.Item label={t("tasks.fields.joblineid")} name="joblineid">
            <Select
              allowClear
              placeholder={t("tasks.placeholders.joblineid")}
              disabled={!selectedJobDetails || !selectedJobId}
            >
              {selectedJobDetails?.joblines?.map((jobline) => (
                <Select.Option key={jobline.id} value={jobline.id}>
                  {jobline.line_desc}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={t("tasks.fields.partsorderid")} name="partsorderid">
            <Select
              allowClear
              placeholder={t("tasks.placeholders.partsorderid")}
              disabled={!selectedJobDetails || !selectedJobId}
            >
              {selectedJobDetails?.parts_orders?.map((partsOrder) => (
                <Select.Option key={partsOrder.id} value={partsOrder.id}>
                  {partsOrder.order_number} - {partsOrder.vendor.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={t("tasks.fields.billid")} name="billid">
            <Select
              allowClear
              placeholder={t("tasks.placeholders.billid")}
              disabled={!selectedJobDetails || !selectedJobId}
            >
              {selectedJobDetails?.bills?.map((bill) => (
                <Select.Option key={bill.id} value={bill.id}>
                  {bill.invoice_number} - {bill.vendor.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Form.Item
            label={t("tasks.fields.assigned_to")}
            name="assigned_to"
            initialValue={currentUser.email}
            rules={[
              {
                required: true
              }
            ]}
          >
            <Select placeholder={t("tasks.placeholders.assigned_to")}>
              {bodyshop.employees
                .filter((x) => x.active)
                .map((employee) => (
                  <Select.Option key={employee.id} value={employee.user_email}>
                    {employee.first_name} {employee.last_name}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={t("tasks.fields.due_date")} name="due_date">
            <FormDatePicker format="MM/DD/YYYY" presets={datePickerPresets} />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={t("tasks.fields.remind_at")} name="remind_at">
            <DatePicker showTime minuteStep={15} format="MM/DD/YYYY h:mm a" presets={datePickerPresets} />
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Form.Item label={t("tasks.fields.description")} name="description">
            <Input.TextArea rows={8} placeholder={t("tasks.fields.description")} />
          </Form.Item>
        </Col>
      </Row>
    </>
  );
}
