import React, { useEffect, useState } from "react";
import { Breadcrumb, Spinner, Tab, Tabs } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
import { AuthService, TemplateFileService } from "../../services";

const TemplateManager = () => {
  const navigate = useNavigate();
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [uploadingKey, setUploadingKey] = useState("");

  const loadTemplates = () => {
    setIsLoading(true);
    TemplateFileService.listTemplates()
      .then((data) => {
        setTemplates(data?.data?.data || []);
      })
      .catch(() => {
        window.alert("Failed to load templates.");
      })
      .finally(() => setIsLoading(false));
  };

  useEffect(() => {
    if (!AuthService.canAccessLegacySystem()) {
      window.alert("You haven't login yet OR this user does not have access to this page. Please change an admin account to login.");
      AuthService.logout();
      navigate("/login");
      return;
    }
    loadTemplates();
  }, []);

  const handleView = (row) => {
    if (!row?.file?.url) return;
    window.open(TemplateFileService.getTemplateFileUrl(row.file.url), "_blank");
  };

  const handleDownload = (row) => {
    if (!row?.file?.url) return;
    const link = document.createElement("a");
    link.href = TemplateFileService.getTemplateFileUrl(row.file.url);
    link.download = row?.file?.originalName || row?.file?.name || `${row.label}.template`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const onUploadFile = (row, event) => {
    const file = event?.target?.files?.[0];
    event.target.value = "";
    if (!file || !row?.key) return;

    setUploadingKey(row.key);
    TemplateFileService.uploadTemplate(row.key, file)
      .then(() => {
        window.alert("Template uploaded successfully.");
        loadTemplates();
      })
      .catch(() => {
        window.alert("Template upload failed.");
      })
      .finally(() => setUploadingKey(""));
  };

  return (
    <>
      {isLoading && (
        <div className="spinner-overlay">
          <Spinner animation="border" role="status">
            <span className="visually-hidden">Loading...</span>
          </Spinner>
        </div>
      )}

      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item active>Template</Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Template</h4>
        </div>
      </div>

      <div className="app-main-content-list-container form-page">
        <div className="app-main-content-list-func-container">
          <Tabs defaultActiveKey="template" id="medical-template-tab">
            <Tab eventKey="template" title="Template">
              <div className="list row mb-4 mt-3">
                <div className="col-md-12" style={{ overflow: "auto" }}>
                  <table className="personnel-info-table">
                    <thead>
                      <tr>
                        <th className="th-index">No.</th>
                        <th>Template</th>
                        <th>Current File</th>
                        <th>Site</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {templates.map((row, index) => (
                        <tr key={row.key}>
                          <td className="td-index">{index + 1}</td>
                          <td>{row.label}</td>
                          <td>{row?.file?.originalName || row?.file?.name || "No file uploaded"}</td>
                          <td>{row.site || "-"}</td>
                          <td>
                            <button className="btn btn-sm btn-outline-primary me-2" onClick={() => handleView(row)} disabled={!row?.file?.url}>
                              View
                            </button>
                            <button className="btn btn-sm btn-outline-secondary me-2" onClick={() => handleDownload(row)} disabled={!row?.file?.url}>
                              Download
                            </button>
                            <label className="btn btn-sm btn-primary mb-0">
                              {uploadingKey === row.key ? "Uploading..." : "Re-upload"}
                              <input
                                type="file"
                                style={{ display: "none" }}
                                onChange={(event) => onUploadFile(row, event)}
                                disabled={uploadingKey === row.key}
                              />
                            </label>
                          </td>
                        </tr>
                      ))}
                      {templates.length === 0 && (
                        <tr>
                          <td colSpan="5" style={{ textAlign: "center", color: "#999", padding: "20px" }}>
                            No templates found for this site.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>
    </>
  );
};

export default TemplateManager;
