<template>
  <div class="centered-container">
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">
        بارگذاری عملکرد PDF
      </CBreadcrumb>
    </CustomSubHeader>

    <CCard class="upload-card">
      <CCardHeader>
        <slot name="header">
          <i class="fal fa-upload"></i>
          <span class="header-title">بارگذاری عملکرد</span>
        </slot>
      </CCardHeader>
      <CCardBody>
        <CRow>
          <CCol md="12" class="text-center">
            <div class="upload-container">
              <el-upload
                ref="upload"
                class="upload-demo"
                drag
                action="/api/admin/pdf-manager/add"
                :headers="uploadHeaders"
                :data="uploadData"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-change="handleChange"
                :limit="1"
                accept=".pdf"
                :file-list="fileList"
                :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="upload-text">
                  فایل PDF خود را به اینجا بکشید یا
                  <br />
                  <em>برای بارگذاری کلیک کنید</em>
                </div>
              </el-upload>
              <el-input
                v-model="title"
                placeholder="عنوان را وارد کنید"
                class="mt-3" />
              <el-button
                :loading="uploading"
                @click="submitUpload"
                size="small"
                class="mt-3 upload-button"
                type="primary"
                icon="el-icon-upload2">
                بارگذاری
              </el-button>
            </div>
          </CCol>
        </CRow>
      </CCardBody>
    </CCard>

    <CCard class="pdf-list-card mt-4">
      <CCardHeader>
        <h5>PDF های بارگذاری شده</h5>
      </CCardHeader>
      <CCardBody>
        <CRow>
          <CCol md="12">
            <div v-if="pdfs.length > 0" class="pdf-list">
              <el-table
                :data="pdfs"
                class="pdf-table"
                stripe>
                <el-table-column
                  prop="title"
                  label="عنوان"
                  width="70%">
                </el-table-column>
                <el-table-column
                  label="اقدامات"
                  width="30%">
                  <template v-slot="scope">
                    <el-button
                      size="small"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deletePDF(scope.row.id)">
                      حذف
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="text-center">
              <p>هنوز پی دی افی بارگذاری نشده است.</p>
            </div>
          </CCol>
        </CRow>
      </CCardBody>
    </CCard>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      fileList: [],
      uploading: false,
      token: null,
      pdfs: [], // List of uploaded PDFs
    };
  },
  computed: {
    uploadData() {
      return {
        title: this.title,
      };
    },
    uploadHeaders() {
      return {
        Authorization: `Bearer ${this.token}`,
      };
    },
  },
  mounted() {
    if (typeof window !== "undefined") {
      this.token = localStorage.getItem(
        "auth._token.local"
      );
    }
    this.fetchPDFs(); // Fetch the PDFs on component mount
  },
  layout: "admin",

  methods: {
    fetchPDFs() {
      this.$axios
        .get("/api/admin/books", {
          headers: this.uploadHeaders,
        })
        .then((response) => {
          this.pdfs = response.data;
        })
        .catch((error) => {
          console.error("Error fetching PDFs:", error);
          this.$message.error(
            "خطا در بارگذاری لیست PDF ها"
          );
        });
    },
    beforeUpload(file) {
      const isPDF = file.type === "application/pdf";
      if (!isPDF) {
        this.$message.error(
          "فقط فایل های با فرمت پی دی اف مجاز است"
        );
      }
      return isPDF;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      console.log("File list updated:", fileList);
    },
    handleSuccess(response, file, fileList) {
      this.uploading = false;
      this.fileList = fileList; // Ensure fileList is updated
      this.$message.success(
        "پی دی اف با موفقیت بارگزاری شد"
      );
      this.fetchPDFs(); // Refresh the list of PDFs
    },
    handleError(err, file, fileList) {
      this.uploading = false;
      this.$message.error("خطا در آپلود");
    },
    submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning(
          "لطفاً یک فایل را انتخاب کنید"
        );
        return;
      }

      if (this.$refs.upload) {
        this.uploading = true;
        this.$refs.upload.submit();
      } else {
        console.error("Upload reference is not defined");
      }
    },
    deletePDF(id) {
      this.$axios
        .delete(`/api/admin/book/${id}`, {
          headers: this.uploadHeaders,
        })
        .then(() => {
          this.$message.success(
            "پی دی اف با موفقیت حذف شد"
          );
          this.fetchPDFs(); // Refresh the list of PDFs after deletion
        })
        .catch((error) => {
          console.error("Error deleting PDF:", error);
          this.$message.error("خطا در حذف پی دی اف");
        });
    },
  },
};
</script>

<style scoped>
.centered-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  width: 100%;
}

.upload-card,
.pdf-list-card {
  width: 100%;
  max-width: 800px;
}

.header-title {
  color: #000;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 600px;
  width: 100%;
}

.upload-demo {
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  width: 100%;
  text-align: center;
  background: #f9f9f9;
}

.upload-text {
  font-size: 16px;
  color: #606266;
}

.upload-button {
  width: auto;
  margin-top: 20px;
}

.pdf-list {
  margin-top: 20px;
}

.pdf-table {
  width: 100%;
}
</style>
