<template>
  <div class="view-container">
    <div class="view-header">
      <h2>Papierkorb</h2>
      <Button v-if="trashItems.length" icon="pi pi-trash" label="Papierkorb leeren"
              size="small" severity="danger" outlined @click="confirmEmpty = true" />
    </div>

    <div v-if="loading" class="loading">
      <i class="pi pi-spin pi-spinner"></i> Laden...
    </div>

    <div v-else-if="!trashItems.length" class="empty-state">
      <i class="pi pi-trash" style="font-size: 3rem; color: var(--p-surface-300)"></i>
      <p>Der Papierkorb ist leer</p>
    </div>

    <DataTable v-else :value="trashItems" striped-rows>
      <Column field="name" header="Name" sortable>
        <template #body="{ data }">
          <div class="file-name">
            <i :class="data.is_folder ? 'pi pi-folder' : 'pi pi-file'"></i>
            <span>{{ data.name }}</span>
          </div>
        </template>
      </Column>
      <Column field="size" header="Groesse" sortable style="width: 120px">
        <template #body="{ data }">
          {{ data.is_folder ? '' : formatSize(data.size) }}
        </template>
      </Column>
      <Column field="trashed_at" header="Geloescht am" sortable style="width: 180px">
        <template #body="{ data }">
          {{ formatDate(data.trashed_at) }}
        </template>
      </Column>
      <Column header="Aktionen" style="width: 160px">
        <template #body="{ data }">
          <Button icon="pi pi-replay" label="Wiederherstellen" text size="small"
                  @click.stop="restoreItem(data)" />
          <Button icon="pi pi-times" text size="small" severity="danger"
                  title="Endgueltig loeschen" @click.stop="confirmPermanentDelete(data)" />
        </template>
      </Column>
    </DataTable>

    <!-- Confirm permanent delete -->
    <Dialog v-model:visible="showDeleteConfirm" header="Endgueltig loeschen" modal :style="{ width: '420px' }">
      <p>Moechtest du <strong>{{ deleteTarget?.name }}</strong> wirklich endgueltig loeschen?</p>
      <p class="warn-text">Diese Aktion kann nicht rueckgaengig gemacht werden!</p>
      <template #footer>
        <Button label="Abbrechen" text @click="showDeleteConfirm = false" />
        <Button label="Endgueltig loeschen" severity="danger" @click="deletePermanently" />
      </template>
    </Dialog>

    <!-- Confirm empty trash -->
    <Dialog v-model:visible="confirmEmpty" header="Papierkorb leeren" modal :style="{ width: '420px' }">
      <p>Moechtest du den gesamten Papierkorb endgueltig leeren?</p>
      <p class="warn-text">Alle {{ trashItems.length }} Eintraege werden unwiderruflich geloescht!</p>
      <template #footer>
        <Button label="Abbrechen" text @click="confirmEmpty = false" />
        <Button label="Papierkorb leeren" severity="danger" @click="emptyTrash" />
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
import apiClient from '../api/client'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import Dialog from 'primevue/dialog'

const toast = useToast()
const trashItems = ref([])
const loading = ref(false)
const showDeleteConfirm = ref(false)
const deleteTarget = ref(null)
const confirmEmpty = ref(false)

function formatSize(bytes) {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let i = 0; let size = bytes
  while (size >= 1024 && i < units.length - 1) { size /= 1024; i++ }
  return `${size.toFixed(i > 0 ? 1 : 0)} ${units[i]}`
}

function formatDate(iso) {
  if (!iso) return ''
  return new Date(iso).toLocaleString('de-DE', {
    day: '2-digit', month: '2-digit', year: 'numeric',
    hour: '2-digit', minute: '2-digit',
  })
}

async function loadTrash() {
  loading.value = true
  try {
    const res = await apiClient.get('/files/trash')
    trashItems.value = res.data
  } catch {
    trashItems.value = []
  } finally {
    loading.value = false
  }
}

async function restoreItem(item) {
  try {
    await apiClient.post(`/files/trash/${item.id}/restore`)
    toast.add({ severity: 'success', summary: `"${item.name}" wiederhergestellt`, life: 3000 })
    await loadTrash()
  } catch (err) {
    toast.add({ severity: 'error', summary: 'Fehler', detail: err.response?.data?.error, life: 5000 })
  }
}

function confirmPermanentDelete(item) {
  deleteTarget.value = item
  showDeleteConfirm.value = true
}

async function deletePermanently() {
  if (!deleteTarget.value) return
  try {
    await apiClient.delete(`/files/trash/${deleteTarget.value.id}`)
    toast.add({ severity: 'success', summary: 'Endgueltig geloescht', life: 3000 })
    showDeleteConfirm.value = false
    await loadTrash()
  } catch (err) {
    toast.add({ severity: 'error', summary: 'Fehler', detail: err.response?.data?.error, life: 5000 })
  }
}

async function emptyTrash() {
  try {
    await apiClient.post('/files/trash/empty')
    toast.add({ severity: 'success', summary: 'Papierkorb geleert', life: 3000 })
    confirmEmpty.value = false
    await loadTrash()
  } catch (err) {
    toast.add({ severity: 'error', summary: 'Fehler', detail: err.response?.data?.error, life: 5000 })
  }
}

onMounted(loadTrash)
</script>

<style scoped>
.view-container { padding: 1.5rem; }
.view-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
.view-header h2 { margin: 0; }
.loading { text-align: center; padding: 2rem; color: var(--p-text-muted-color); }
.empty-state {
  display: flex; flex-direction: column; align-items: center;
  gap: 0.75rem; padding: 4rem 2rem; color: var(--p-text-muted-color);
}
.file-name { display: flex; align-items: center; gap: 0.5rem; }
.warn-text { color: var(--p-red-500); font-size: 0.875rem; }
</style>
