/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from "react";
import { ExportType } from "./type";

import FactoryRenderer from "../../../../Renderer";
import { ExportDataScope } from "../../type";

interface ExportPopupProps {
  setTogglePopup: React.Dispatch<React.SetStateAction<boolean>>;
  onExport: (callBack: () => void, exportViewModel: ExportViewModel) => void;
  onExportDelete: (callBack: ((args: any) => void) | null, id: string) => void;
  onExportList: (callBack: ((args: any) => void) | null) => void;
  onExportDownload: (
    callBack: ((args: any) => void) | null,
    id: string,
  ) => void;
  exportTypes?: string[];
  dataScopes?: ExportDataScope[];
}

export type ExportViewModel = {
  exportType: string;
} & ExportDataScope;

enum Status {
  IN_PROGRESS = "InProcess",
  COMPLETED = "Success",
  FAILED = "Error",
  SCHEDULED = "Scheduled",
}

type ExportHistoryViewModel = {
  id: string;
  fileName: string;
  exportType: ExportType;
  exportDataScope: string;
  date: string;
  status: string;
  src: string;
  referenceId: string;
};

/* const sampleData = [
  {
    id: "1",
    fileName: "Export1",
    date: "2023-10-01",
    status: Status.COMPLETED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "2",
    fileName: "Export2",
    date: "2023-10-02",
    status: Status.IN_PROGRESS,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "3",
    fileName: "Export3",
    date: "2023-10-03",
    status: Status.FAILED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "1",
    fileName: "Export1",
    date: "2023-10-01",
    status: Status.COMPLETED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "2",
    fileName: "Export2",
    date: "2023-10-02",
    status: Status.IN_PROGRESS,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "3",
    fileName: "Export3",
    date: "2023-10-03",
    status: Status.FAILED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "1",
    fileName: "Export1",
    date: "2023-10-01",
    status: Status.COMPLETED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "2",
    fileName: "Export2",
    date: "2023-10-02",
    status: Status.IN_PROGRESS,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
  {
    id: "3",
    fileName: "Export3",
    date: "2023-10-03",
    status: Status.FAILED,
    exportType: ExportType.XLS,
    exportDataScope: "Header List",
    src: "",
  },
]; */

const DEFAULT_EXPORT_TYPES = Object.values(ExportType) as string[];
const DEFAULT_DATA_SCOPES: ExportDataScope[] = [
  { label: "Header List", type: "header", entity: "header" },
];

const ExportPopup = (props: ExportPopupProps) => {
  const exportTypes = props.exportTypes?.length
    ? props.exportTypes
    : DEFAULT_EXPORT_TYPES;
  const dataScopes = props.dataScopes?.length
    ? props.dataScopes
    : DEFAULT_DATA_SCOPES;
  const popupRef = useRef<HTMLDivElement>(null);

  const [exporHistoryList, setExporHistoryList] = useState<
    ExportHistoryViewModel[]
  >([]);

  useEffect(() => {
    props.onExportList((list: ExportHistoryViewModel[]) => {
      setExporHistoryList(list);
    });
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      const isInsideMyPopup = target.closest(
        `.tmpl-prvent-outside-click-close`,
      );
      if (
        popupRef.current &&
        !popupRef.current.contains(event.target as Node) &&
        !isInsideMyPopup
      ) {
        popupRef.current.classList.add("tmpl-popup-animation-reverse");
        setTimeout(() => {
          props.setTogglePopup ? props.setTogglePopup(false) : null;
        }, 200);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const handleExportClick = (
    exportType: string,
    dataScope: ExportDataScope,
  ) => {
    const exportViewModel: ExportViewModel = {
      exportType,
      ...dataScope,
    };
    props.onExport(() => {
      props.onExportList((list: ExportHistoryViewModel[]) => {
        setExporHistoryList(list);
      });
    }, exportViewModel);
  };

  const downloadResultHandler = (response: any, fileName: string) => {
    const blob = new Blob([response]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);
  };

  const handleDownload = async (fileUrl: string, fileName: string) => {
    try {
      props.onExportDownload(
        (res) => downloadResultHandler(res, fileName),
        fileUrl,
      );
    } catch (error) {
      console.error("Download failed:", error);
    }
  };

  return (
    <div className="tmpl-export-popup" ref={popupRef}>
      <div className="tmpl-export-scope-container">
        {dataScopes.map((scope) => (
          <div key={scope.label} className="tmpl-export-scope-section">
            <h4 className="tmpl-export-scope-header">{scope.label}</h4>
            <div className="tmpl-export-options-grid">
              {exportTypes.map((type) => (
                <div
                  title={`${type} - ${scope.label}`}
                  key={`${type}-${scope.label}`}
                  className="tmpl-export-option-card"
                  onClick={() => handleExportClick(type, scope)}
                >
                  <span className="tmpl-export-option-type">{type}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <h4>Previous Exports</h4>
      <div className="tmpl-export-history-items-container">
        {exporHistoryList.map((exportHistoryViewModel) => {
          return (
            <div
              className="tmpl-export-history-item"
              key={exportHistoryViewModel.id}
            >
              <div className="tmpl-export-history-item-info">
                <p>{exportHistoryViewModel.fileName}</p>
                <p>{exportHistoryViewModel.date}</p>
              </div>
              <div className="tmpl-export-history-item-action">
                {exportHistoryViewModel.status === Status.COMPLETED ? (
                  /*                   <Button
                    svgIcon={downloadIcon}
                    type="button"
                    fillMode={"clear"}
                    onClick={() =>
                      handleDownload(
                        exportHistoryViewModel.referenceId,
                        exportHistoryViewModel.fileName
                      )
                    }
                  /> */
                  <FactoryRenderer
                    name="download"
                    uiElementType="WIDGET"
                    widgetStyle={{
                      className: "qo-btn qo-text-default",
                    }}
                    widgetType="ICON"
                    fillMode="clear"
                    title="Download"
                    onClick={() =>
                      handleDownload(
                        exportHistoryViewModel.referenceId,
                        exportHistoryViewModel.fileName,
                      )
                    }
                  />
                ) : exportHistoryViewModel.status === Status.FAILED ? (
                  /*                   <Button
                    svgIcon={fileErrorIcon}
                    type="button"
                    fillMode={"clear"}
                  /> */
                  <FactoryRenderer
                    widgetStyle={{ className: "qo-btn qo-text-warning" }}
                    name="error"
                    uiElementType="WIDGET"
                    widgetType="ICON"
                    fillMode="clear"
                    title="Failed"
                  />
                ) : (
                  <FactoryRenderer
                    name="load"
                    uiElementType="WIDGET"
                    widgetType="ICON"
                    widgetStyle={{ className: "qo-btn qo-text-primary" }}
                    fillMode="clear"
                    title="In Process"
                  />
                  /*  <span className={exportHistoryViewModel.status}>
                    {exportHistoryViewModel.status}
                  </span> */
                )}
                {/*                 <Button
                  svgIcon={trashIcon}
                  type="button"
                  fillMode={"clear"}
                  title="Delete"

                /> */}
                <FactoryRenderer
                  name="delete"
                  uiElementType="WIDGET"
                  widgetType="ICON"
                  fillMode="clear"
                  title="Delete"
                  widgetStyle={{ className: "qo-btn qo-text-danger" }}
                  onClick={() =>
                    props.onExportDelete(() => {
                      props.onExportList((list: ExportHistoryViewModel[]) => {
                        setExporHistoryList(list);
                      });
                    }, exportHistoryViewModel.id)
                  }
                />
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};
export default ExportPopup;
