// DocumentManager.js
import React, { useState } from "react";
import DocumentForm from "./DocumentForm";
import ConfirmModal from "../common/ConfirmModal";

const EmpDocuments = () => {
  const [searchText, setSearchText] = useState("");
  const [documents, setDocuments] = useState([
    {
      name: "Adhar Card",
      uploadedDate: "21 Aug, 2025",
      uploadedBy: "Alice Johnson",
      fileType: "PDF",
      url: "#",
      initials: "AC",
      files: [],
    },
    {
      name: "Pan Card",
      uploadedDate: "15 Jul, 2025",
      uploadedBy: "Bob Smith",
      fileType: "Excel",
      url: "#",
      initials: "PC",
      files: [],
    },
    {
      name: "Driving Licence",
      uploadedDate: "10 Aug, 2025",
      uploadedBy: "Carol Lee",
      fileType: "Word",
      url: "#",
      initials: "DL",
      files: [],
    },
    {
      name: "",
      uploadedDate: "05 Aug, 2025",
      uploadedBy: "David Kim",
      fileType: "PNG",
      url: "#",
      initials: "DM",
      files: [],
    },
    {
      name: "Client Presentation",
      uploadedDate: "18 Aug, 2025",
      uploadedBy: "Eve Brown",
      fileType: "PPT",
      url: "#",
      initials: "CP",
      files: [],
    },
  ]);

  const [showForm, setShowForm] = useState(false);
  const [currentDocument, setCurrentDocument] = useState(null);

  // New state for the delete modal
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [documentToDelete, setDocumentToDelete] = useState(null);

  const filteredDocuments = documents.filter((doc) =>
    (doc.name || "Unnamed Document").toLowerCase().includes(searchText.toLowerCase())
  );

  const handleSearch = (e) => {
    setSearchText(e.target.value);
  };

  const handleCreateClick = () => {
    setCurrentDocument(null);
    setShowForm(true);
  };

  const handleEditClick = (doc) => {
    setCurrentDocument(doc);
    setShowForm(true);
  };

  const handleSave = (newDoc) => {
    if (currentDocument) {
      // Edit an existing document
      setDocuments(
        documents.map((doc) => (doc === currentDocument ? { ...newDoc, initials: doc.initials } : doc))
      );
    } else {
      // Create a new document
      setDocuments([...documents, { ...newDoc, initials: newDoc.name ? newDoc.name.slice(0, 2).toUpperCase() : "--" }]);
    }
    setShowForm(false);
  };

  const handleCancel = () => {
    setShowForm(false);
    setCurrentDocument(null);
  };

  const handleDelete = (doc) => {
    // Set the document to be deleted and open the modal
    setDocumentToDelete(doc);
    setIsDeleteModalOpen(true);
  };

  // New function to handle the confirmed deletion
  const handleConfirmDelete = () => {
    if (documentToDelete) {
      setDocuments(documents.filter((doc) => doc !== documentToDelete));
      setIsDeleteModalOpen(false); // Close the modal
      setDocumentToDelete(null); // Clear the document to delete
    }
  };

  // Function to close the delete modal
  const handleCloseDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setDocumentToDelete(null);
  };

  return (
    <div className="card px-4 mt-2 py-2" style={{ minHeight: "200px" }}>
      {/* Header: Search & Create */}
      <div className="d-flex justify-content-between align-items-center py-2">
        <div className="dataTables_filter">
          <label className="mb-0">
            <input
              type="search"
              value={searchText}
              onChange={handleSearch}
              className="form-control form-control-sm"
              placeholder="Search Document"
              aria-controls="DataTables_Table_0"
            />
          </label>
        </div>
        <div>
          <button className="btn btn-primary btn-sm" onClick={handleCreateClick}>
            Create Document
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="table-responsive text-nowrap">
        <table className="table mb-0">
          <thead>
            <tr className="text-center">
              <th colSpan={2}>Document Name</th>
              <th>Uploaded Date</th>
              <th>Uploaded By</th>
              <th>File Type</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {filteredDocuments.length > 0 ? (
              filteredDocuments.map((doc, index) => (
                <tr key={index} className="align-middle" style={{ height: "50px" }}>
                  <td colSpan={2}>
                    <div className="d-flex align-items-center">
                      <div
                        className="avatar bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center"
                        style={{ width: "30px", height: "30px", fontSize: "0.75rem" }}
                      >
                        {doc.initials || (doc.name ? doc.name.slice(0, 2).toUpperCase() : "--")}
                      </div>

                      <div className="d-flex flex-column ms-3">
                        <a href={doc.url || "#"} className="text-heading text-truncate">
                          <span className="fw-normal">
                            {doc.name || "Unnamed Document"}
                          </span>
                        </a>
                      </div>
                    </div>
                  </td>
                  <td>{doc.uploadedDate}</td>
                  <td>{doc.uploadedBy}</td>
                  <td>{doc.fileType}</td>
                  <td className="text-center">
                    <i
                      className="bx bx-edit text-secondary cursor-pointer me-2"
                      onClick={() => handleEditClick(doc)}
                    ></i>
                    <i
                      className="bx bx-trash text-danger cursor-pointer"
                      onClick={() => handleDelete(doc)}
                    ></i>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={6} className="text-center text-muted py-3">
                  No documents available.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Document Form Modal */}
      {showForm && (
        <div className="modal fade show d-block" style={{ backgroundColor: "rgba(0, 0, 0, 0.5)" }}>
          <DocumentForm
            initialData={currentDocument}
            onSave={handleSave}
            onCancel={handleCancel}
          />
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div
          className={`modal fade ${isDeleteModalOpen ? "show" : ""}`}
          tabIndex="-1"
          role="dialog"
          style={{
            display: "block",
            backgroundColor: "rgba(0,0,0,0.5)",
          }}
          aria-hidden="false"
        >
          <ConfirmModal
            type={"delete"}
            header={"Delete Document"}
            message={`Are you sure you want to delete "${documentToDelete?.name || "Unnamed Document"}"?`}
            onSubmit={handleConfirmDelete}
            onClose={handleCloseDeleteModal}
            // `loading` prop is not needed for this example but can be added
            // `paramData` is also not needed since we're using a state variable
          />
        </div>
      )}
    </div>
  );
};

export default EmpDocuments;
