import React, { useEffect, useState } from "react";
import {
  getDocumentsCase,
  uploadDocument,
  deleteDocument,
} from "@/services/caseService";
import { toast } from "react-toastify";
import UploadModal from "@/components/common/UploadModal";
import { useProfile } from "@/context/ProfileContext";

const ALLOWED_EXTENSIONS = [
  "pdf",
  "doc",
  "docx",
  "txt",
  "jpg",
  "jpeg",
  "png",
];


export default function Documents({ data }) {
  const { profile } = useProfile();

  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const caseId = data?.id;

  const [documents, setDocuments] = useState([]);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [loading, setLoading] = useState(false);

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const canEditStatus =
    !isAnalyst || Number(data?.lead_consultant_id) === Number(profile?.id);

  useEffect(() => {
    if (caseId) fetchDocuments();
  }, [caseId]);

  const fetchDocuments = async () => {
    if (!caseId) return;

    try {
      const res = await getDocumentsCase(caseId);
      setDocuments(res?.data?.documents || []);
    } catch (err) {
      const msg =
        err?.response?.data?.detail ||
        err?.message ||
        "Failed to load documents";

      toast.error(msg);
    }
  };

  const handleFileChange = (e) => {
    const files = Array.from(e.target.files || []);

    const validFiles = [];
    const invalidFiles = [];

    files.forEach((file) => {
      const extension = file.name.split(".").pop()?.toLowerCase();

      if (ALLOWED_EXTENSIONS.includes(extension)) {
        validFiles.push(file);
      } else {
        invalidFiles.push(file.name);
      }
    });

    if (invalidFiles.length > 0) {
      toast.error(
        `Only PDF, DOC, DOCX, TXT, JPG, JPEG and PNG files are allowed.`
      );
    }

    if (validFiles.length > 0) {
      setSelectedFiles((prev) => [...prev, ...validFiles]);
    }

    // Reset input so the same file can be selected again
    e.target.value = "";
  };

  const onRemoveFile = (index) => {
    setSelectedFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const handleUpload = async () => {
    if (!caseId) {
      toast.error("Invalid case");
      return;
    }

    if (!selectedFiles.length) {
      toast.warning("Please select files");
      return;
    }

    try {
      setLoading(true);

      const formData = new FormData();
      selectedFiles.forEach((file) => {
        formData.append("upload_files", file);
      });

      await uploadDocument(caseId, formData);

      toast.success("Uploaded successfully");

      setSelectedFiles([]);
      setIsUploadModalOpen(false);

      await fetchDocuments();
    } catch (err) {
      const msg =
        err?.response?.data?.detail || err?.message || "Upload failed";

      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  const openDeleteModal = (doc) => {
    setSelectedDocument(doc);
    setIsDeleteModalOpen(true);
  };

  const handleDeleteDocument = async () => {
    if (!caseId || !selectedDocument) return;

    try {
      setDeleting(true);

      await deleteDocument(caseId, selectedDocument.document_id);

      toast.success("Document deleted successfully");

      setIsDeleteModalOpen(false);
      setSelectedDocument(null);

      await fetchDocuments();
    } catch (err) {
      const msg =
        err?.response?.data?.detail ||
        err?.message ||
        "Failed to delete document";

      toast.error(msg);
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div className="dshboardcaseform">
      <div className="d-flex justify-content-between align-items-center">
        <div className="d-block justify-content-between mt-3">
          <h3>Documents</h3>
        </div>

        <div className="datafrmbtn custom-file-upload m-0 my-2">
          <button
            type="button"
            className="upload-btn"
            onClick={() => setIsUploadModalOpen(true)}
          >
            Upload Documents
          </button>
        </div>
      </div>

      <div className="uploaded-documents-section mt-3">
        {documents.length > 0 ? (
          <>
            <h4>Uploaded Documents ({documents.length})</h4>

            <div className="uploaded-list">
              {documents.map((doc, i) => (
                <div key={doc.document_id || i} className="uploaded-file-pill">
                  <a
                    href={doc.file_url}
                    title={doc.file_name}
                    target="_blank"
                    rel="noreferrer"
                    className="uploaded-link w-100"
                  >
                    <div className="pill-icon">📄</div>

                    <div className="pill-content">
                      <div className="pill-name pe-4">
                        {doc.file_name || `Document ${i + 1}`}
                      </div>
                      <div className="pill-meta">Click to view</div>
                    </div>
                  </a>

                  {!isAnalyst && (
                    <button
                      className="delete-btn"
                      onClick={() => openDeleteModal(doc)}
                    >
                      ✕
                    </button>
                  )}
                </div>
              ))}
            </div>
          </>
        ) : (
          <p>No documents uploaded yet.</p>
        )}
      </div>

      <UploadModal
        isOpen={isUploadModalOpen}
        onClose={() => {
          setIsUploadModalOpen(false);
          setSelectedFiles([]);
        }}
        files={selectedFiles}
        onFileSelect={handleFileChange}
        onUpload={handleUpload}
        onRemoveFile={onRemoveFile}
      />

      {isDeleteModalOpen && (
        <div className="modal-overlay">
          <div className="modal-box">
            <button
              className="modal-close"
              onClick={() => {
                setIsDeleteModalOpen(false);
                setSelectedDocument(null);
              }}
            >
              ✕
            </button>

            <h3>Confirm Delete</h3>

            <p>
              Are you sure you want to delete{" "}
              <b>{selectedDocument?.name || "this document"}</b>?
            </p>

            <div className="modal-actions">
              <button
                className="btn-cancel"
                onClick={() => {
                  setIsDeleteModalOpen(false);
                  setSelectedDocument(null);
                }}
              >
                Cancel
              </button>

              <button
                className="btn-delete"
                onClick={handleDeleteDocument}
                disabled={deleting}
              >
                {deleting ? "Deleting..." : "Delete"}
              </button>
            </div>
          </div>
        </div>
      )}

      <style jsx>{`
        .uploaded-file-pill {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px;
          border: 1px solid #ddd;
          margin-bottom: 8px;
          border-radius: 8px;
          background: #fff;
        }

        .uploaded-link {
          display: flex;
          text-decoration: none;
          color: inherit;
          flex: 1;
        }

        .pill-icon {
          margin-right: 10px;
        }

        .delete-btn {
          position: absolute;
          top: 8px;
          right: 8px;
          width: 28px;
          height: 28px;
          border: none;
          border-radius: 50%;
          background: #f5f5f5;
          color: #ff4d4f;
          font-size: 16px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: 0.2s ease;
        }

        .delete-btn:hover {
          background: #ffeaea;
          transform: scale(1.05);
        }

        .modal-overlay {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 999;
        }

        .modal-box {
          position: relative;
          background: #fff;
          padding: 25px;
          border-radius: 16px;
          width: 420px;
          max-width: 95%;
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        /* CLOSE BUTTON TOP RIGHT */
        .modal-close {
          position: absolute;
          top: 10px;
          right: 10px;
          width: 32px;
          height: 32px;
          border: none;
          border-radius: 50%;
          background: #f2f2f2;
          font-size: 18px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .modal-close:hover {
          background: #e0e0e0;
        }

        .modal-actions {
          display: flex;
          justify-content: flex-end;
          gap: 10px;
          margin-top: 20px;
        }

        .btn-cancel {
          padding: 8px 12px;
          border: 1px solid #ccc;
          background: #fff;
          cursor: pointer;
          border-radius: 6px;
        }

        .btn-delete {
          padding: 8px 12px;
          border: none;
          background: red;
          color: white;
          cursor: pointer;
          border-radius: 6px;
        }
      `}</style>
    </div>
  );
}
