import React, { useContext, useEffect, useState, useRef } from "react";
import GallerySlider from "./GallerySlider";
import { ConfigContext } from "../../Context/ConfigContext";
import { useParams } from "react-router-dom";
import axios from "axios";
import { ContentLoader, NoRecords } from "../Shimmer";
import Swal from 'sweetalert2';
import Select from 'react-select';
import { formatDate } from "../GlobalFunctions";

const Gallery = () => {
  const { projectId } = useParams();
  const [isSlider, setisSlider] = useState(false);
  const [galleryData, setGalleryData] = useState([]);
  const [loadingList, setLoadingList] = useState(true);
  const { apiURL, apiHeaderFile, imageURL } = useContext(ConfigContext);
  const [showModal, setShowModal] = useState(false);
  const [file, setFile] = useState(null);
  const [pmTitle, setPmTitle] = useState("");
  const [selectedType, setSelectedType] = useState(null);
  const [errors, setErrors] = useState({});
  const fileInputRef = useRef(null);

  const typeOptions = [
    { value: 'IMAGE', label: 'IMAGE' },
    { value: 'DOCUMENT', label: 'PDF' }
  ];

  const handleSlider = (isSlid) => {
    setisSlider(isSlid);
  };

  const handleGetGallery = async () => {
    const headers = apiHeaderFile;
    try {
      setLoadingList(true);
      const response = await axios.get(`${apiURL}api/project-media/project/${projectId}`);
      const { data, success } = response.data;
      setLoadingList(false);
      if (success) {
        setGalleryData(data);
      }
    } catch (error) {
      setLoadingList(false);
      console.error(error);
    }
  };

  const validateForm = () => {
    const newErrors = {};

    if (!file) {
      newErrors.file = "Please select a file";
    } else if (file.size > 10 * 1024 * 1024) {
      newErrors.file = "File size must be less than 10 MB";
    } else if (selectedType?.value === "IMAGE") {
      const validImageTypes = ["image/jpeg", "image/png", "image/jpg"];
      if (!validImageTypes.includes(file.type)) {
        newErrors.file = "Please upload a valid image (JPEG/PNG/JPG)";
      }
    } else if (selectedType?.value === "DOCUMENT") {
      if (file.type !== "application/pdf") {
        newErrors.file = "Please upload a valid PDF";
      }
    }

    if (!pmTitle.trim()) {
      newErrors.pmTitle = "Please enter the title";
    } else {
      const titleRegex = /^[a-zA-Z0-9][a-zA-Z0-9 _-]*[a-zA-Z0-9]$/;
      if (!titleRegex.test(pmTitle)) {
        newErrors.pmTitle = "Invalid title. Title must start and end with an alphanumeric character and can include spaces, underscores, and dashes.";
      }
    }

    if (!selectedType) {
      newErrors.type = "Please select a document type";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
    setErrors({ ...errors, file: null });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) return;

    try {
      const headers = apiHeaderFile;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("pm_project_id", projectId);
      formData.append("pm_title", pmTitle);
      formData.append("pm_type", selectedType.value);
      formData.append("created_by", localStorage.getItem("user_id"));
      formData.append("created_date", formatDate());

      const url = `${apiURL}api/project-media`;

      const response = await axios.post(url, formData, { headers });
      const { success, message, data } = response.data;

      if (success) {
        setGalleryData((prevData) => [...prevData, data]);
        resetForm();
        setShowModal(false);
        Swal.fire({
        title: 'Success!',
        text: message,
        icon: 'success',
        timer: 1500,
        showConfirmButton: false
      });
      }
    } catch (error) {
      console.error(error);
      Swal.fire({
        title: 'Error!',
        text: error.message,
        icon: 'error',
        showConfirmButton: true
      });
    }
  };

  const resetForm = () => {
    setFile(null);
    setPmTitle("");
    setSelectedType(null);
    setErrors({});
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleModalClose = () => {
    resetForm();
    setShowModal(false);
  };

  useEffect(() => {
    handleGetGallery();
  }, []);

  return (
    <div className="col-xxl-12">
      <div className="card">
        <div className="row">
          <div className="col-lg-12">
            <div className="card-body">
              <div className="card-header d-flex align-items-center mb-4">
                <h5 className="card-title flex-grow-1 mb-0">Gallery</h5>
                <div className="flex-shrink-0">
                  <button
                    type="button"
                    className="btn btn-warning"
                    onClick={() => setShowModal(true)}
                  >
                    <i className="ri-upload-2-fill me-1 align-bottom" /> Upload Images
                  </button>
                </div>
              </div>

              {isSlider === false ? (
                <div className="row">
                  <div className="col-lg-12">
                    <div className="row gallery-wrapper">
                      {loadingList ? (
                        <ContentLoader />
                      ) : galleryData.length === 0 ? (
                        <NoRecords />
                      ) : (
                        galleryData.map((item) => (
                          item.pm_type === "IMAGE" && (
                            <div
                              className="element-item col-xxl-3 col-xl-4 col-sm-6 project designing development"
                              key={item.project_media_id}
                            >
                              <div className="gallery-box card">
                                <div className="gallery-container">
                                  <a
                                    className="image-popup"
                                    onClick={() => handleSlider(true)}
                                  >
                                    <img
                                      className="gallery-img img-fluid mx-auto"
                                      src={imageURL + item.pm_file_name}
                                      alt=""
                                    />
                                    <div className="gallery-overlay"></div>
                                  </a>
                                </div>
                                <div className="box-content">
                                  <div className="d-flex align-items-center mt-1">
                                    <div className="flex-grow-1 text-muted">
                                      by{" "}
                                      <a
                                        href="#"
                                        className="text-body text-truncate"
                                      >
                                        NEW LINE ENGINEERING CONSULTATION
                                      </a>
                                    </div>
                                    <div className="flex-shrink-0"></div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          )
                        ))
                      )}
                    </div>
                  </div>
                </div>
              ) : (
                <>
                  <GallerySlider />
                  {isSlider && (
                    <div className="d-flex justify-content-center align-items-center">
                      <button
                        className="btn btn-primary"
                        onClick={() => handleSlider(false)}
                      >
                        Go Back
                      </button>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Bootstrap Modal */}
      <div className={`modal fade ${showModal ? 'show d-block' : ''}`} id="uploadModal" tabIndex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="uploadModalLabel">Upload File</h5>
              <button type="button" className="btn-close" onClick={handleModalClose} aria-label="Close"></button>
            </div>
            <div className="modal-body">
              <form onSubmit={handleSubmit}>
                <div className="mb-3">
                  <label className="form-label">Document Type:</label>
                  <Select
                    options={typeOptions}
                    value={selectedType}
                    onChange={(selected) => {
                      setSelectedType(selected);
                      setErrors({ ...errors, type: null });
                    }}
                    className={`basic-single ${errors.type ? 'is-invalid' : ''}`}
                    classNamePrefix="select"
                    placeholder="Select document type"
                  />
                  {errors.type && <div className="invalid-feedback d-block">{errors.type}</div>}
                </div>
                <div className="mb-3">
                  <label htmlFor="pmTitle" className="form-label">Title</label>
                  <input
                    type="text"
                    className={`form-control ${errors.pmTitle ? 'is-invalid' : ''}`}
                    id="pmTitle"
                    value={pmTitle}
                    onChange={(e) => {
                      setPmTitle(e.target.value);
                      setErrors({ ...errors, pmTitle: null });
                    }}
                    placeholder="Enter title"
                  />
                  {errors.pmTitle && <div className="invalid-feedback">{errors.pmTitle}</div>}
                </div>
                <div className="mb-3">
                  <label htmlFor="fileInput" className="form-label">File</label>
                  <input
                    type="file"
                    className={`form-control ${errors.file ? 'is-invalid' : ''}`}
                    id="fileInput"
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    accept={selectedType?.value === "IMAGE" ? "image/*" : "application/pdf"}
                  />
                  {errors.file && <div className="invalid-feedback">{errors.file}</div>}
                  <small className="text-muted">Max file size: 10MB</small>
                </div>
              </form>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" onClick={handleModalClose}>Cancel</button>
              <button type="button" className="btn btn-primary" onClick={handleSubmit}>Upload</button>
            </div>
          </div>
        </div>
      </div>
      {showModal && <div className="modal-backdrop fade show"></div>}
    </div>
  );
};

export default Gallery;