import { PageHeader } from "@ant-design/pro-layout";
import { Button, Result, Space, Steps } from "antd";

import { useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import AlertComponent from "../../components/alert/alert.component";
import JobsCreateJobsInfo from "../../components/jobs-create-jobs-info/jobs-create-jobs-info.component";
import JobsCreateOwnerInfoContainer from "../../components/jobs-create-owner-info/jobs-create-owner-info.container";
import JobsCreateVehicleInfoContainer from "../../components/jobs-create-vehicle-info/jobs-create-vehicle-info.container";
import JobCreateContext from "../../pages/jobs-create/jobs-create.context";

export default function JobsCreateComponent({ form, isSubmitting }) {
  const [pageIndex, setPageIndex] = useState(0);
  const [errorMessage, setErrorMessage] = useState(null);
  const [state] = useContext(JobCreateContext);
  const { t } = useTranslation();

  const steps = [
    {
      title: t("jobs.labels.create.vehicleinfo"),
      id: "step-job-vehicleinfo",
      content: <JobsCreateVehicleInfoContainer form={form} />,
      validation: !!state.vehicle.new || !!state.vehicle.selectedid || !!state.vehicle.none,
      error: t("vehicles.errors.selectexistingornew")
    },
    {
      title: t("jobs.labels.create.ownerinfo"),
      id: "step-job-ownerinfo",
      content: <JobsCreateOwnerInfoContainer />,
      validation: !!state.owner.new || !!state.owner.selectedid,
      error: t("owners.errors.selectexistingornew")
    },
    {
      title: t("jobs.labels.create.jobinfo"),
      id: "step-job-jobinfo",
      content: <JobsCreateJobsInfo form={form} selected={pageIndex === 2} />
    }
  ];

  const next = () => {
    setPageIndex(pageIndex + 1);
  };
  const prev = () => {
    setPageIndex(pageIndex - 1);
  };

  const ProgressButtons = ({ top }) => {
    return (
      <PageHeader
        extra={
          <Space wrap>
            {pageIndex > 0 && <Button onClick={() => prev()}>{t("general.actions.previous")}</Button>}
            {pageIndex < steps.length - 1 && (
              <Button
                type="primary"
                onClick={() => {
                  next();
                  form
                    .validateFields()
                    .then(() => {
                      if (steps[pageIndex].validation) {
                        setErrorMessage(null);
                        next();
                      } else {
                        setErrorMessage(steps[pageIndex].error);
                      }
                    })
                    .catch((error) => console.log("error", error));
                }}
              >
                {t("general.actions.next")}
              </Button>
            )}
            {pageIndex === steps.length - 1 && (
              <Button
                type="primary"
                loading={isSubmitting}
                onClick={() => {
                  form
                    .validateFields()
                    .then(() => {
                      form.submit();
                    })
                    .catch((error) => {
                      console.log("error", error);
                    });
                }}
              >
                {t("general.actions.done")}
              </Button>
            )}
          </Space>
        }
      >
        {top && (
          <Steps
            current={pageIndex}
            items={steps.map((item, idx) => ({
              key: item.title,
              title: item.title,
              style: {
                cursor: "pointer",
                fontWeight: idx === pageIndex && "bolder"
              },
              onClick: () => {
                setPageIndex(idx);
                form
                  .validateFields()
                  .then(() => {
                    if (steps[pageIndex].validation) {
                      setErrorMessage(null);
                      setPageIndex(idx);
                    } else {
                      setErrorMessage(steps[pageIndex].error);
                    }
                  })
                  .catch((error) => console.log("error", error));
              }
            }))}
          />
        )}
      </PageHeader>
    );
  };

  return (
    <div>
      {state.created ? (
        <div>
          <Result
            status="success"
            title={t("jobs.successes.creatednoclick")}
            extra={[
              <Link to={`/manage/jobs/${state.newJobId}`} key="gotojob">
                <Button type="primary">{t("jobs.actions.gotojob")}</Button>
              </Link>,
              <Link to={`/manage/jobs/`} key="gotojoblist">
                <Button>{t("menus.header.activejobs")}</Button>
              </Link>
            ]}
          />
        </div>
      ) : (
        <div>
          <ProgressButtons top />
          {errorMessage ? (
            <div>
              <AlertComponent title={errorMessage} type="error" />
            </div>
          ) : null}
          {steps.map((item, idx) => (
            <div
              key={idx}
              style={{
                display: idx === pageIndex ? "" : "none",
                margin: "1rem"
              }}
            >
              {item.content}
            </div>
          ))}
          <ProgressButtons />
        </div>
      )}
    </div>
  );
}
