<template>
  <div>
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*,video/*,.pdf"
      style="display: none"
      @change="onFileSelected"
    />

    <DefaultTable
      v-model:rows="rows"
      title="Contratos"
      :columns
      descricao="contratos"
      :feminino="false"
      no-api-call
      add-item
      :show-search-field="false"
      @on-add-item="handleAdd"
    >
      <template #body-cell-period="{ row }">
        <q-td>{{ row.signature_date }} — {{ row.end_date }}</q-td>
      </template>

      <template #body-cell-status="{ row }">
        <q-td align="center">
          <q-badge
            :color="statusColor(row.status)"
            :label="statusLabel(row.status)"
          />
        </q-td>
      </template>

      <template #body-cell-actions="{ row }">
        <q-td align="center">
          <q-item-section class="no-wrap" style="flex-direction: row; gap: 4px">
            <q-btn
              outline
              icon="mdi-pencil-outline"
              style="width: 36px"
              @click.prevent.stop="handleEdit(row)"
            />
            <q-btn
              outline
              icon="mdi-paperclip"
              style="width: 36px"
              :loading="uploadingId === row.id"
              @click.prevent.stop="triggerFileInput(row)"
            />
            <q-btn
              outline
              icon="mdi-dots-vertical"
              style="width: 36px"
              @click.prevent.stop
            >
              <q-menu>
                <q-list style="min-width: 170px">
                  <q-item
                    v-close-popup
                    clickable
                    :disable="!row.file_url"
                    @click="openFile(row.file_url)"
                  >
                    <q-item-section>Visualizar arquivo</q-item-section>
                  </q-item>
                  <template v-if="row.status === 'frozen' || row.status === 'cancelled'">
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleReactivate(row)"
                    >
                      <q-item-section>Reativar Contrato</q-item-section>
                    </q-item>
                  </template>
                  <template v-else>
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleFreeze(row)"
                    >
                      <q-item-section>Congelar Contrato</q-item-section>
                    </q-item>
                    <q-item
                      v-close-popup
                      clickable
                      @click="handleCancel(row)"
                    >
                      <q-item-section>Cancelar Contrato</q-item-section>
                    </q-item>
                  </template>
                </q-list>
              </q-menu>
            </q-btn>
          </q-item-section>
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import AddEditContractDialog from "src/pages/students/components/AddEditContractDialog.vue";
import ContractActionConfirmDialog from "src/pages/students/components/ContractActionConfirmDialog.vue";
import {
  getStudentContracts,
  attachContractFile,
  freezeContract,
  cancelContract,
  reactivateContract,
} from "src/api/studentContract";

const props = defineProps({
  student: {
    type: Object,
    required: true,
  },
});

const $q = useQuasar();
const rows = ref([]);
const fileInputRef = ref(null);
const uploadingId = ref(null);
let pendingContractId = null;

async function loadContracts() {
  rows.value = await getStudentContracts(props.student.id);
}

onMounted(loadContracts);

function openDialog(contract = null) {
  $q.dialog({
    component: AddEditContractDialog,
    componentProps: { student: props.student, contract },
  }).onOk(loadContracts);
}

function handleAdd() {
  openDialog();
}

function handleEdit(contract) {
  openDialog(contract);
}

function triggerFileInput(row) {
  pendingContractId = row.id;
  fileInputRef.value.value = "";
  fileInputRef.value.click();
}

async function onFileSelected(event) {
  const file = event.target.files?.[0];
  if (!file || !pendingContractId) return;

  uploadingId.value = pendingContractId;
  try {
    const formData = new FormData();
    formData.append("file", file);
    const updated = await attachContractFile(pendingContractId, formData);
    const idx = rows.value.findIndex((r) => r.id === pendingContractId);
    if (idx !== -1) rows.value[idx] = updated;
  } catch (e) {
    console.error(e);
    $q.notify({ type: "negative", message: "Erro ao anexar arquivo." });
  } finally {
    uploadingId.value = null;
    pendingContractId = null;
  }
}

function openFile(url) {
  window.open(url, "_blank");
}

function confirmAction(title, message, apiFn, contract) {
  $q.dialog({
    component: ContractActionConfirmDialog,
    componentProps: { title, message },
  }).onOk(async () => {
    try {
      const updated = await apiFn(contract.id);
      const idx = rows.value.findIndex((r) => r.id === contract.id);
      if (idx !== -1) rows.value[idx] = updated;
    } catch (e) {
      console.error(e);
      $q.notify({ type: "negative", message: "Erro ao atualizar status do contrato." });
    }
  });
}

function handleFreeze(contract) {
  confirmAction(
    "Congelar Contrato",
    "Você tem certeza que deseja CONGELAR este contrato? Isso irá gerar multas e cancelamento da cobrança recorrente.",
    freezeContract,
    contract,
  );
}

function handleCancel(contract) {
  confirmAction(
    "Cancelar Contrato",
    "Você tem certeza que deseja CANCELAR este contrato? Isso irá gerar multas e cancelamento da cobrança recorrente.",
    cancelContract,
    contract,
  );
}

function handleReactivate(contract) {
  confirmAction(
    "Reativar Contrato",
    "Você tem certeza que deseja REATIVAR este contrato?",
    reactivateContract,
    contract,
  );
}

function statusColor(status) {
  if (status === "active") return "positive";
  if (status === "frozen") return "info";
  if (status === "cancelled") return "negative";
  return "warning";
}

function statusLabel(status) {
  if (status === "active") return "Ativo";
  if (status === "frozen") return "Congelado";
  if (status === "cancelled") return "Cancelado";
  return "Inativo";
}

const columns = ref([
  { name: "contract", label: "Contrato", field: "protocol", align: "left" },
  {
    name: "period",
    label: "Data Assinatura - Encerramento",
    field: null,
    align: "left",
  },
  { name: "status", label: "Status", field: "status", align: "center" },
  { name: "actions", label: "Ações", field: null, align: "center" },
]);
</script>
