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

const Documents = () => {
  const { projectId } = useParams();
  const { apiURL, apiHeaderFile, apiHeaderJson } = useContext(ConfigContext);
  const [fileData, setFileData] = useState([]);
  const [loadingList, setLoadingList] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [formData, setFormData] = useState({
    pmType: null,
    pmTitle: null,
    file: null,
  });
  const [formErrors, setFormErrors] = useState({});

  const documentTypeOptions = [
    { value: "IMAGE", label: "IMAGE" },
    { value: "DOCUMENT", label: "PDF" },
  ];

  const titleOptions = [
    { value: "Approved dwg", label: "Approved dwg" },
    { value: "As built dwg", label: "As built dwg" },
    { value: "Workshop dwg", label: "Workshop dwg" },
    { value: "Others", label: "Others" },
  ];

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

  const checkIcon = (type) => {
    if (type === "IMAGE") return "ri-image-2-fill";
    if (type === "DOCUMENT") return "ri-file-pdf-fill";
    return "ri-file-zip-fill";
  };

  const downloadDocument = (url, filename) => {
    fetch(`${url}${filename}`)
      .then((response) => response.blob())
      .then((blob) => {
        const newBlobURL = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement("a");
        link.href = newBlobURL;
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(newBlobURL);
      })
      .catch((error) => console.error("Download failed:", error));
  };

  const viewDocument = (type, filename) => {
    if (type === "IMAGE") {
      return `https://tms.atctransline.in/apis/public/images/${filename}`;
    }
    if (type === "DOCUMENT") {
      return `https://tms.atctransline.in/apis/public/documents/${filename}`;
    }
  };

  const handleModalOpen = () => {
    setShowModal(true);
    setFormErrors({});
  };

  const handleModalClose = () => {
    setShowModal(false);
    setFormData({
      pmType: null,
      pmTitle: null,
      file: null,
    });
    setFormErrors({});
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;

    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    setFormErrors((prev) => {
      const updated = { ...prev };
      delete updated[name];
      return updated;
    });
  };

  const handleFileChange = (e) => {
    const selectedFile = e.target.files[0];

    setFormData((prev) => ({
      ...prev,
      file: selectedFile,
    }));

    setFormErrors((prev) => {
      const updated = { ...prev };
      delete updated.file;
      return updated;
    });
  };

  const validateForm = () => {
    const errors = {};
    const { pmType, pmTitle, file } = formData;

    if (!pmType) {
      errors.pmType = "Please select a document type";
    }

    if (!pmTitle) {
      errors.pmTitle = "Please select a title";
    }

    if (!file) {
      errors.file = "Please select a file";
    } else if (file.size > 10 * 1024 * 1024) {
      errors.file = "File size must be less than 10 MB";
    } else {
      const validImageTypes = ["image/jpeg", "image/png", "image/jpg"];
      const validPdfType = "application/pdf";

      if (pmType?.value === "IMAGE" && !validImageTypes.includes(file.type)) {
        errors.file = "Please upload a valid image (JPEG/PNG/JPG)";
      }

      if (pmType?.value === "DOCUMENT" && file.type !== validPdfType) {
        errors.file = "Please upload a valid PDF";
      }
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

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

      const url = `${apiURL}api/project-media`;
      const response = await axios.post(url, formDataToSend, { headers });
      const { success, message, data } = response.data;

      if (success) {
        setFileData((prevData) => [...prevData, data]);
        handleModalClose();
        Swal.fire({
          title: 'Success!',
          text: message,
          icon: 'success',
          timer: 1000,
          showConfirmButton: false
        });
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleDelete = async (id) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: 'You won’t be able to revert this!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    });

    if (result.isConfirmed) {
      try {
        const response = await axios.delete(
          `${apiURL}api/project-media/${id}`,
          apiHeaderJson
        );

        if (response.data.success) {
          Swal.fire({
            title: 'Deleted!',
            text: 'The file has been deleted.',
            icon: 'success',
            timer: 1500,
            showConfirmButton: false
          });

          handleGetFile();
        }
      } catch (error) {
        console.error(error);
        Swal.fire({
          title: 'Error!',
          text: 'There was a problem deleting the file.',
          icon: 'error'
        });
      }
    }
  };

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

  return (
    <div className="col-xxl-12">
      <div className="card">
        {loadingList ? (
          <ContentLoader />
        ) : (
          <div className="card-body">
            <div className="card-header d-flex align-items-center mb-4">
              <h5 className="card-title flex-grow-1 mb-0">Documents</h5>
              <div className="flex-shrink-0">
                <button
                  type="button"
                  onClick={handleModalOpen}
                  className="btn btn-danger"
                >
                  <i className="ri-upload-2-fill me-1 align-bottom" /> Upload File
                </button>
              </div>
            </div>
            <div className="row">
              <div className="col-lg-12">
                <table className="table table-borderless align-middle mb-0">
                  <thead className="table-light">
                    <tr>
                      <th scope="col">File Name</th>
                      <th scope="col">Type</th>
                      <th scope="col">Title</th>
                      <th scope="col">Upload Date</th>
                      <th scope="col">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {fileData?.length === 0 ? (
                      <tr>
                        <td colSpan="6">
                          <NoRecords />
                        </td>
                      </tr>
                    ) : (
                      fileData.map((item, index) => (
                        <tr key={index}>
                          <td>
                            <div className="d-flex align-items-center">
                              <div className="avatar-sm">
                                <div className="avatar-title bg-dark-subtle text-dark rounded fs-20">
                                  <i className={checkIcon(item.pm_type)} />
                                </div>
                              </div>
                              <div className="ms-3 flex-grow-1">
                                <h6 className="fs-14 mb-0">
                                  <a
                                    href="javascript:void(0)"
                                    className="text-body"
                                  >
                                    {item.pm_file_name}
                                  </a>
                                </h6>
                              </div>
                            </div>
                          </td>
                          <td>{item.pm_type}</td>
                          <td>{item.pm_title}</td>
                          <td>{item.created_date}</td>
                          <td>
                            <div className="dropdown">
                              <a
                                href="javascript:void(0);"
                                className="btn btn-light btn-icon"
                                data-bs-toggle="dropdown"
                                aria-expanded="true"
                              >
                                <i className="ri-equalizer-fill" />
                              </a>
                              <ul className="dropdown-menu dropdown-menu-end">
                                <li>
                                  <a
                                    style={{ cursor: "pointer" }}
                                    className="dropdown-item"
                                    target="_blank"
                                    href={viewDocument(
                                      item.pm_type,
                                      item.pm_file_name
                                    )}
                                  >
                                    <i className="ri-eye-fill me-2 align-middle text-muted" />
                                    View
                                  </a>
                                </li>
                                <li>
                                  <a
                                    className="dropdown-item"
                                    onClick={() =>
                                      handleDelete(item.project_media_id)
                                    }
                                  >
                                    <i className="ri-delete-bin-5-line me-2 align-middle text-muted" />
                                    Delete
                                  </a>
                                </li>
                              </ul>
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* Bootstrap Modal for File Upload */}
        {showModal && (
          <div className="modal" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
            <div className="modal-dialog modal-dialog-centered">
              <div className="modal-content">
                <div className="modal-header">
                  <h5 className="modal-title">Upload File</h5>
                  <button type="button" className="btn-close" onClick={handleModalClose}></button>
                </div>
                <div className="modal-body">
                  <form>
                    <div className="mb-3">
                      <label className="form-label">Document Type</label>
                      <Select
                        options={documentTypeOptions}
                        value={formData.pmType}
                        onChange={(selected) => {
                          setFormData((prev) => ({
                            ...prev,
                            pmType: selected,
                          }));

                          setFormErrors((prev) => {
                            const updated = { ...prev };
                            delete updated.pmType;
                            return updated;
                          });
                        }}
                        placeholder="Select document type"
                        className={`basic-single ${formErrors.pmType ? "is-invalid" : ""}`}
                      />
                      {formErrors.pmType && (
                        <div className="invalid-feedback">{formErrors.pmType}</div>
                      )}
                    </div>

                    <div className="mb-3">
                      <label className="form-label">Title</label>
                      <Select
                        options={titleOptions}
                        value={formData.pmTitle}
                        onChange={(selected) => {
                          setFormData((prev) => ({
                            ...prev,
                            pmTitle: selected,
                          }));

                          setFormErrors((prev) => {
                            const updated = { ...prev };
                            delete updated.pmTitle;
                            return updated;
                          });
                        }}
                        placeholder="Select title"
                        className={`basic-single ${formErrors.pmTitle ? "is-invalid" : ""}`}
                      />
                      {formErrors.pmTitle && (
                        <div className="invalid-feedback">{formErrors.pmTitle}</div>
                      )}
                    </div>

                    <div className="mb-3">
                      <label className="form-label">File</label>
                      <input
                        type="file"
                        className={`form-control ${formErrors.file ? 'is-invalid' : ''}`}
                        onChange={handleFileChange}
                        accept={
                          formData.pmType?.value === "IMAGE"
                            ? "image/*"
                            : "application/pdf"
                        }
                      />
                      {formErrors.file && (
                        <div className="invalid-feedback">{formErrors.file}</div>
                      )}
                    </div>
                  </form>
                </div>
                <div className="modal-footer">
                  <button
                    type="button"
                    className="btn btn-secondary"
                    onClick={handleModalClose}
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    className="btn btn-dark"
                    onClick={handleSubmit}
                  >
                    Upload
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Documents;