import { EditFilled, FileExcelFilled, SyncOutlined } from "@ant-design/icons";
import { Button, Card, Col, Row, Space } from "antd";
import React, { useEffect, useState } from "react";
import { Gallery } from "react-grid-gallery";
import { useTranslation } from "react-i18next";
import DocumentsUploadComponent from "../documents-upload/documents-upload.component";
import { DetermineFileType } from "../documents-upload/documents-upload.utility";
import { GenerateSrcUrl, GenerateThumbUrl } from "./job-documents.utility";
import JobsDocumentsDownloadButton from "./jobs-document-gallery.download.component";
import JobsDocumentsGalleryReassign from "./jobs-document-gallery.reassign.component";
import JobsDocumentsDeleteButton from "./jobs-documents-gallery.delete.component";
import JobsDocumentsGallerySelectAllComponent from "./jobs-documents-gallery.selectall.component";

import Lightbox from "react-image-lightbox";
import "react-image-lightbox/style.css";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import UpsellComponent, { upsellEnum } from "../upsell/upsell.component";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({});

function JobsDocumentsComponent({
  bodyshop,
  data,
  jobId,
  refetch,
  billId,
  billsCallback,
  totalSize,
  downloadIdentifier,
  ignoreSizeLimit
}) {
  const [galleryImages, setgalleryImages] = useState({ images: [], other: [] });
  const { t } = useTranslation();
  const [modalState, setModalState] = useState({ open: false, index: 0 });

  useEffect(() => {
    let documents = data.reduce(
      (acc, value) => {
        const fileType = DetermineFileType(value.type);
        if (value.type.startsWith("image")) {
          acc.images.push({
            // src: GenerateSrcUrl(value),
            src: GenerateThumbUrl(value),
            // src: GenerateSrcUrl(value),
            // thumbnail: GenerateThumbUrl(value),
            fullsize: GenerateSrcUrl(value),
            height: 225,
            width: 225,
            isSelected: false,
            key: value.key,
            extension: value.extension,
            id: value.id,
            type: value.type,
            size: value.size,
            tags: [{ value: value.type, title: value.type }]
          });
        } else {
          let thumb;
          switch (fileType) {
            case "raw":
              thumb = `${window.location.origin}/file.png`;
              break;
            default:
              thumb = GenerateThumbUrl(value);
              break;
          }

          const fileName = value.key.split("/").pop();
          acc.other.push({
            source: GenerateSrcUrl(value),
            src: thumb,
            thumbnail: thumb,
            tags: [
              {
                value: fileName,
                title: fileName
              },

              { value: value.type, title: value.type },
              ...(value.bill
                ? [
                    {
                      value: value.bill.vendor.name,
                      title: t("vendors.fields.name")
                    },
                    { value: value.bill.date, title: t("bills.fields.date") },
                    {
                      value: value.bill.invoice_number,
                      title: t("bills.fields.invoice_number")
                    }
                  ]
                : [])
            ],
            height: 225,
            width: 225,
            isSelected: false,
            extension: value.extension,
            key: value.key,
            id: value.id,
            type: value.type,
            size: value.size
          });
        }

        return acc;
      },
      { images: [], other: [] }
    );
    setgalleryImages(documents);
  }, [data, setgalleryImages, t]);
  const hasMediaAccess = HasFeatureAccess({ bodyshop, featureName: "media" });
  const hasMobileAccess = HasFeatureAccess({ bodyshop, featureName: "mobile" });
  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Space wrap>
            <Button onClick={() => refetch && refetch()}>
              <SyncOutlined />
            </Button>
            <JobsDocumentsGallerySelectAllComponent galleryImages={galleryImages} setGalleryImages={setgalleryImages} />
            <JobsDocumentsDownloadButton galleryImages={galleryImages} identifier={downloadIdentifier} />
            <JobsDocumentsDeleteButton galleryImages={galleryImages} deletionCallback={billsCallback || refetch} />
            {!billId && <JobsDocumentsGalleryReassign galleryImages={galleryImages} callback={refetch} />}
          </Space>
        </Col>
        {!hasMediaAccess && (
          <Col span={24}>
            <Card>
              <UpsellComponent disableMask upsell={upsellEnum().media.general} />
            </Card>
          </Col>
        )}

        <Col span={24}>
          <Card>
            <DocumentsUploadComponent
              jobId={jobId}
              totalSize={totalSize}
              billId={billId}
              callbackAfterUpload={billsCallback || refetch}
              ignoreSizeLimit={ignoreSizeLimit}
            />
          </Card>
        </Col>
        {hasMediaAccess && !hasMobileAccess && (
          <Col span={24}>
            <Card>
              <UpsellComponent upsell={upsellEnum().media.mobile} />
            </Card>
          </Col>
        )}
        <Col span={24}>
          <Card title={t("jobs.labels.documents-images")}>
            <Gallery
              images={galleryImages.images}
              onClick={(index, item) => {
                setModalState({ open: true, index: index });
                // window.open(
                //   item.fullsize,
                //   "_blank",
                //   "toolbar=0,location=0,menubar=0"
                // );
              }}
              onSelect={(index, image) => {
                setgalleryImages({
                  ...galleryImages,
                  images: galleryImages.images.map((g, idx) =>
                    index === idx ? { ...g, isSelected: !g.isSelected } : g
                  )
                });
              }}
            />
          </Card>
        </Col>
        <Col span={24}>
          <Card title={t("jobs.labels.documents-other")}>
            <Gallery
              images={galleryImages.other}
              thumbnailStyle={() => {
                return {
                  backgroundImage: <FileExcelFilled />,
                  height: "100%",
                  width: "100%",
                  cursor: "pointer"
                };
              }}
              onClick={(index) => {
                window.open(galleryImages.other[index].source, "_blank", "toolbar=0,location=0,menubar=0");
              }}
              onSelect={(index) => {
                setgalleryImages({
                  ...galleryImages,
                  other: galleryImages.other.map((g, idx) => (index === idx ? { ...g, isSelected: !g.isSelected } : g))
                });
              }}
            />
          </Card>
        </Col>
        {modalState.open && (
          <Lightbox
            toolbarButtons={[
              <EditFilled
                onClick={() => {
                  const newWindow = window.open(
                    `${window.location.protocol}//${window.location.host}/edit?documentId=${
                      galleryImages.images[modalState.index].id
                    }`,
                    "_blank",
                    "noopener,noreferrer"
                  );
                  if (newWindow) newWindow.opener = null;
                }}
              />
            ]}
            mainSrc={galleryImages.images[modalState.index].fullsize}
            nextSrc={galleryImages.images[(modalState.index + 1) % galleryImages.images.length].fullsize}
            prevSrc={
              galleryImages.images[(modalState.index + galleryImages.images.length - 1) % galleryImages.images.length]
                .fullsize
            }
            onCloseRequest={() => setModalState({ open: false, index: 0 })}
            onMovePrevRequest={() =>
              setModalState({
                ...modalState,
                index: (modalState.index + galleryImages.images.length - 1) % galleryImages.images.length
              })
            }
            onMoveNextRequest={() =>
              setModalState({
                ...modalState,
                index: (modalState.index + 1) % galleryImages.images.length
              })
            }
          />
        )}
      </Row>
    </div>
  );
}

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