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";

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

  const onCurrentImageChange = (index) => {
    setIndex(index);
  };

  useEffect(() => {
    let documents = data.reduce(
      (acc, value) => {
        const fileType = DetermineFileType(value.type);
        if (value.type.startsWith("image")) {
          acc.images.push({
            src: GenerateSrcUrl(value),
            thumbnail: GenerateThumbUrl(value),
            thumbnailHeight: 225,
            thumbnailWidth: 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: "",
            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"),
                    },
                  ]
                : []),
            ],
            thumbnailHeight: 225,
            thumbnailWidth: 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]);

  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>
        <Col span={24}>
          <Card>
            <DocumentsUploadComponent
              jobId={jobId}
              totalSize={totalSize}
              billId={billId}
              callbackAfterUpload={billsCallback || refetch}
              ignoreSizeLimit={ignoreSizeLimit}
            />
          </Card>
        </Col>

        <Col span={24}>
          <Card title={t("jobs.labels.documents-images")}>
            <Gallery
              images={galleryImages.images}
              backdropClosesModal={true}
              currentImageWillChange={onCurrentImageChange}
              customControls={[
                <Button
                  key="edit-button"
                  style={{
                    float: "right",
                    zIndex: "5",
                  }}
                  onClick={() => {
                    const newWindow = window.open(
                      `${window.location.protocol}//${window.location.host}/edit?documentId=${galleryImages.images[index].id}`,
                      "_blank",
                      "noopener,noreferrer"
                    );
                    if (newWindow) newWindow.opener = null;
                  }}
                >
                  <EditFilled />
                </Button>,
              ]}
              onClickImage={(props) => {
                window.open(
                  props.target.src,
                  "_blank",
                  "toolbar=0,location=0,menubar=0"
                );
              }}
              onSelectImage={(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}
              backdropClosesModal={true}
              enableLightbox={false}
              thumbnailStyle={() => {
                return {
                  backgroundImage: <FileExcelFilled />,
                  height: "100%",
                  width: "100%",
                  cursor: "pointer",
                };
              }}
              onClickThumbnail={(index) => {
                window.open(
                  galleryImages.other[index].source,
                  "_blank",
                  "toolbar=0,location=0,menubar=0"
                );
              }}
              onSelectImage={(index) => {
                setgalleryImages({
                  ...galleryImages,
                  other: galleryImages.other.map((g, idx) =>
                    index === idx ? { ...g, isSelected: !g.isSelected } : g
                  ),
                });
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
export default JobsDocumentsComponent;
