<script setup lang="ts">
import AppLayout from '@/layouts/AppLayout.vue'
import type { BreadcrumbItemType } from '@/types'
import { Button } from '@/components/ui/button';
import { usePage, router, Link, useForm, Head } from '@inertiajs/vue3';
import { ChevronLeft, ChevronRight, EllipsisVertical } from 'lucide-vue-next'
import { ref, onMounted, computed } from 'vue'
import { useToast } from 'vue-toastification'
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, } from '@/components/ui/dropdown-menu'

defineOptions({
  layout: AppLayout,
})

const props = defineProps<{
  product_backlogs: any
  breadcrumbs: BreadcrumbItemType[]
  flash?: {
    success?: string
    error?: string
  }
}>()

// Project form state
const editRequirement = ref<any>(null)
const form = useForm<{
    name: string | '',
    description: string | ''
}>({
    name: '',
    description: ''
})

const page = usePage()
const role = page.props.auth?.user?.role ?? 'user'
const toast = useToast();

// Calculate row number with pagination offset
const getRowNumber = (index: number) => {
  const currentPage = props.product_backlogs.meta?.current_page || 1
  const perPage = props.product_backlogs.meta?.per_page || 10
  return (currentPage - 1) * perPage + index + 1
}

// Get the first sprint name, or fallback to '-'
const getSprintName = (requirement: any) => {
  return requirement.sprints.length ? requirement.sprints[0].name : '-'
}

// Inertia pagination function
const visitPage = (url: string | null) => {
  if (url) {
    router.visit(url)
  }
}

const destroyRequirement = (id: number) => {
  if (confirm('Are you sure you want to delete this project?')) {
    form.delete(`/product-backlogs/${id}`, {
      onSuccess: () => {
        toast.success('Functional user story deleted successfully!')
      },
      onError: () => {
        toast.error('Failed to delete functional user story. Please try again.')
      },
    })
  }
}

const openEdit = (product_backlogs: any) => {
  editRequirement.value = product_backlogs
  form.name = product_backlogs.name
  form.description = product_backlogs.description
}

const submit = () => {
  if (!editRequirement.value) return

  form.put(`/product-backlogs/${editRequirement.value.id}`, {
    onSuccess: () => {
      editRequirement.value = null
      form.reset()
      toast.success('Functional user story updated successfully!')
    },
    onError: () => {
      toast.error('Failed to update functional user story.') // ❌ error toast
    },
  })
}

onMounted(() => {
  if (props.flash?.success) {
    toast.success(props.flash.success)
  }
  if (props.flash?.error) {
    toast.error(props.flash.error)
  }
})

</script>

<template>
  <Head title="FUs Result" />
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
        <!-- Left: Title -->
        <h1 class="text-2xl font-bold">I-USPA-FUs Prioritization Result</h1>

        <!-- Right: Dropdown -->
        <DropdownMenu>
        <DropdownMenuTrigger asChild>
            <Button variant="ghost" class="p-2">
                <EllipsisVertical class="h-5 w-5"/>
            </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent align="end" class="bg-white text-gray-800 dark:bg-neutral-900 dark:text-gray-100 border rounded shadow-lg">

            <!-- Only admin can see this -->
            <DropdownMenuItem v-if="role === 'admin'" asChild>
                <Link href="/i-uspa-decisions/change-status">Change Status</Link>
            </DropdownMenuItem>

            <!-- Link: FU Result -->
            <DropdownMenuItem asChild>
                <Link href="/i-uspa-decisions/fu-finals">I-USPA-FU Prioritization Result</Link>
            </DropdownMenuItem>

            <!-- Link: NFR Result -->
            <DropdownMenuItem asChild>
                <Link href="/i-uspa-decisions/nfr-finals">I-USPA-NFR Prioritization Result</Link>
            </DropdownMenuItem>

        </DropdownMenuContent>
        </DropdownMenu>
    </div>

    <table class="w-full border text-left">
      <thead class="bg-gray-100 dark:bg-neutral-900">
        <tr>
          <th class="p-2 border">No</th>
          <th class="p-2 border">Projects</th>
          <th class="p-2 border">FUs</th>
          <th class="p-2 border">Sprint</th>
          <th class="p-2 border">Weight</th>
          <th class="p-2 border">Rank</th>
          <th class="p-2 border">Updated at</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(requirement, index) in product_backlogs.data" :key="requirement.id">
          <td class="p-2 border">{{ getRowNumber(index) }}</td>
          <td class="p-2 border">
            {{ requirement.project.name }}
          </td>
          <td class="p-2 border">{{ requirement.name }}</td>
          <td class="p-2 border">{{ getSprintName(requirement) }}</td>
          <td class="p-2 border">{{ requirement.weight }}</td>
          <td class="p-2 border">{{ requirement.rank }}</td>
          <td class="p-2 border">{{ requirement.updated_at }}</td>
        </tr>
        <!-- Show message if no requirements -->
        <tr v-if="product_backlogs.data.length === 0">
          <td colspan="7" class="p-4 border text-center text-gray-500">
            No requirements found.
          </td>
        </tr>
      </tbody>
    </table>

    <!-- Simple Pagination -->
    <div v-if="product_backlogs.meta && product_backlogs.meta.last_page > 1" class="mt-6 flex items-center justify-center space-x-4">
      <Button
        variant="outline"
        size="sm"
        :disabled="!product_backlogs.links.prev"
        @click="visitPage(product_backlogs.links.prev)"
      >
        <ChevronLeft class="h-4 w-4" />
        Previous
      </Button>

      <span class="text-sm text-gray-700">
        Page {{ product_backlogs.meta.current_page }} of {{ product_backlogs.meta.last_page }}
      </span>

      <Button
        variant="outline"
        size="sm"
        :disabled="!product_backlogs.links.next"
        @click="visitPage(product_backlogs.links.next)"
      >
        Next
        <ChevronRight class="h-4 w-4" />
      </Button>
    </div>

    <!-- Results counter -->
    <div v-if="product_backlogs.meta" class="mt-4 text-center text-sm text-gray-600">
      Showing {{ product_backlogs.meta.from }} to {{ product_backlogs.meta.to }} of {{ product_backlogs.meta.total }} results
    </div>
  </div>
</template>

<style scoped>
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>