import { useQuery } from "@apollo/client/react";
import { Col, Row, Skeleton, Space, Timeline, Typography } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { GET_JOB_LINE_ORDERS } from "../../graphql/jobs.queries";
import { QUERY_JOBLINE_TASKS_PAGINATED } from "../../graphql/tasks.queries.js";
import { selectTechnician } from "../../redux/tech/tech.selectors.js";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { DateFormatter } from "../../utils/DateFormatter";
import AlertComponent from "../alert/alert.component";
import BillDetailEditcontainer from "../bill-detail-edit/bill-detail-edit.container";

import BlurWrapper from "../feature-wrapper/blur-wrapper.component";
import TaskListContainer from "../task-list/task-list.container";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  technician: selectTechnician
});

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

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

export function JobLinesExpander({ jobline, jobid, bodyshop, technician }) {
  const { t } = useTranslation();
  const { loading, error, data } = useQuery(GET_JOB_LINE_ORDERS, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      joblineid: jobline.id
    }
  });

  if (loading) return <Skeleton />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  return (
    <Row>
      <Col md={24} lg={8}>
        <Typography.Title level={4}>{t("parts_orders.labels.parts_orders")}</Typography.Title>
        <Timeline
          items={
            data.parts_order_lines.length > 0
              ? data.parts_order_lines.map((line) => ({
                  key: line.id,
                  children: (
                    <Row wrap>
                      <Col span={4}>
                        {!technician ? (
                          <>
                            <Link to={`/manage/jobs/${jobid}?partsorderid=${line.parts_order.id}`}>
                              {line.parts_order.order_number}
                            </Link>
                          </>
                        ) : (
                          `${line.parts_order.order_number}`
                        )}
                      </Col>
                      <Col span={4}>
                        <DateFormatter>{line.parts_order.order_date}</DateFormatter>
                      </Col>
                      <Col span={4}>{line.parts_order.vendor.name}</Col>
                      {line.backordered_eta ? (
                        <Col span={4}>
                          <span>
                            {`${t("parts_orders.fields.backordered_eta")}: `}
                            <DateFormatter>{line.backordered_eta}</DateFormatter>
                          </span>
                        </Col>
                      ) : null}
                    </Row>
                  )
                }))
              : [
                  {
                    key: "no-orders",
                    children: t("parts_orders.labels.notyetordered")
                  }
                ]
          }
        />
      </Col>
      <Col md={24} lg={8}>
        <Typography.Title level={4}>{t("parts_dispatch.labels.parts_dispatch")}</Typography.Title>
        <Timeline
          items={
            data.parts_dispatch_lines.length > 0
              ? data.parts_dispatch_lines.map((line) => ({
                  key: line.id,
                  children: (
                    <Row>
                      <Col span={8}>{line.parts_dispatch.number}</Col>
                      <Col span={8}>
                        {bodyshop.employees.find((e) => e.id === line.parts_dispatch.employeeid)?.first_name}
                      </Col>
                      <Col span={8}>
                        {line.accepted_at ? (
                          <Space>
                            {t("parts_dispatch_lines.fields.accepted_at")}
                            <DateFormatter>{line.accepted_at}</DateFormatter>
                          </Space>
                        ) : null}
                      </Col>
                    </Row>
                  )
                }))
              : [
                  {
                    key: "dispatch-lines",
                    children: t("parts_dispatch.labels.notyetdispatched")
                  }
                ]
          }
        />
      </Col>

      <Col md={24} lg={8}>
        <Typography.Title level={4}>{t("bills.labels.bills")}</Typography.Title>
        <BillDetailEditcontainer />
        <Timeline
          items={
            data.billlines.length > 0
              ? data.billlines.map((line) => ({
                  key: line.id,
                  children: (
                    <Row wrap>
                      <Col span={4}>
                        {!technician ? (
                          <>
                            <Link to={`/manage/jobs/${jobid}?tab=partssublet&billid=${line.bill.id}`}>
                              {line.bill.invoice_number}
                            </Link>
                          </>
                        ) : (
                          `${line.bill.invoice_number}`
                        )}
                      </Col>
                      <Col span={4}>
                        <span>
                          {`${t("billlines.fields.actual_price")}: `}
                          <CurrencyFormatter>{line.actual_price}</CurrencyFormatter>
                        </span>
                      </Col>
                      <Col span={4}>
                        <span>
                          {`${t("billlines.fields.actual_cost")}: `}
                          <CurrencyFormatter>{line.actual_cost}</CurrencyFormatter>
                        </span>
                      </Col>
                      <Col span={4}>
                        <DateFormatter>{line.bill.date}</DateFormatter>
                      </Col>
                      <Col span={4}> {line.bill.vendor.name}</Col>
                    </Row>
                  )
                }))
              : [
                  {
                    key: "no-orders",
                    children: (
                      <BlurWrapper featureName="bills">
                        <span>{t("bills.labels.nobilllines")}</span>
                      </BlurWrapper>
                    )
                  }
                ]
          }
        />
      </Col>

      <Col md={24} lg={24}>
        <TaskListContainer
          parentJobId={jobid}
          relationshipType={"joblineid"}
          relationshipId={jobline.id}
          query={{ QUERY_JOBLINE_TASKS_PAGINATED }}
          titleTranslation="tasks.titles.job_tasks"
        />
      </Col>
    </Row>
  );
}
