<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 { Plus, Edit, Trash, Eye, ChevronLeft, ChevronRight } from 'lucide-vue-next'
import { ref, onMounted, computed } from 'vue'
import { useToast } from 'vue-toastification'
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'

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="FU Backlogs" />
  <div class="p-6">
    <div class="flex justify-between">
        <h1 class="text-2xl font-bold mb-4">Functional User Stories Backlogs</h1>
        <div class="flex space-x-2">
            <Button variant="secondary" as-child>
                <Link href="/product-backlogs/non-functional-requirements">
                    Non-Functional Requirements
                </Link>
            </Button>
            <Button variant="secondary" as-child>
                <Link href="/product-backlogs/sprint-backlogs">
                    Sprint Backlogs
                </Link>
            </Button>
            <Button variant="default" v-if="role === 'admin'" as-child>
              <Link href="/product-backlogs/fus-create">
                  <Plus class="h-4 w-4"/>
                  Add New FUs Backlog
              </Link>
            </Button>
        </div>
        
    </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">Description</th>
          <th class="p-2 border">Sprint</th>
          <th class="p-2 border">Updated at</th>
          <th class="p-2 border" v-if="role === 'admin'">Actions</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">{{ requirement.description }}</td>
          <td class="p-2 border">{{ getSprintName(requirement) }}</td>
          <td class="p-2 border">{{ requirement.updated_at }}</td>
          <td class="p-2 border" v-if="role === 'admin'">
            <Dialog @close="() => { 
                editRequirement.value = null; 
                form.reset(); 
            }">
              <DialogTrigger asChild>
                <Button variant="link" @click="openEdit(requirement)" v-if="requirement.project.status === 'requirement change'">
                  <Edit class="h-4 w-4" />
                  Edit
                </Button>
              </DialogTrigger>
              <DialogContent class="w-full sm:min-w-md md:min-w-lg">
                <DialogHeader>
                  <DialogTitle>Edit Project</DialogTitle>
                  <DialogDescription>
                    Update the functional user story details below.
                  </DialogDescription>
                </DialogHeader>

                <form @submit.prevent="submit" class="space-y-4 mt-4">
                  <!-- Name -->
                  <div class="space-y-2">
                    <Label for="name">Name</Label>
                    <Input id="name" v-model="form.name" />
                    <div v-if="form.errors.name" class="text-red-500 text-sm">
                      {{ form.errors.name }}
                    </div>
                  </div>

                  <!-- Description -->
                  <div class="space-y-2">
                    <Label for="description">Description</Label>
                    <Input id="description" v-model="form.description" />
                    <div v-if="form.errors.description" class="text-red-500 text-sm">
                      {{ form.errors.description }}
                    </div>
                  </div>
                  <!-- Footer -->
                  <DialogFooter class="flex justify-end space-x-2">
                    <DialogClose asChild>
                      <Button type="button" variant="secondary">Cancel</Button>
                    </DialogClose>
                    <DialogClose asChild>
                      <Button type="submit" :disabled="form.processing">Save</Button>
                    </DialogClose>
                  </DialogFooter>
                </form>
              </DialogContent>
            </Dialog>
            <Button variant="link" v-if="role === 'admin' && requirement.project.status === 'requirement change'" @click="destroyRequirement(requirement.id)" :disabled="form.processing">
              <Trash class="h-4 w-4"/>
              Delete
            </Button>
          </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>