<script setup lang="ts">
import AppLayout from '@/layouts/AppLayout.vue'
import type { BreadcrumbItemType } from '@/types'
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { usePage, router, Link, useForm, Head } from '@inertiajs/vue3';
import { Plus, Edit, Trash, ChevronLeft, ChevronRight } from 'lucide-vue-next'
import { useToast } from 'vue-toastification'
import { ref, onMounted } from 'vue'
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<{
  users: any
  breadcrumbs: BreadcrumbItemType[]
  flash?: {
    success?: string
    error?: string
  }
}>()

const toast = useToast()

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

// Form setup
const editUser = ref<any>(null)
const form = useForm<{
    name: string,
    email: string,
}>({
    name: '',
    email: '',
})

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

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

const destroyUser = (id: number) => {
  if (confirm('Are you sure you want to delete this user?')) {
    form.delete(`/user-management/${id}`, {
      onSuccess: () => {
        toast.success('Stakeholder deleted successfully!')
      },
      onError: () => {
        toast.error('Failed to delete stakeholder. Please try again.')
      },
    })
  }
}

const openEdit = (user: any) => {
  editUser.value = user
  form.name = user.name
  form.email = user.email
}

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

  form.put(`/user-management/${editUser.value.id}`, {
    onSuccess: () => {
      editUser.value = null
      form.reset()
      toast.success('Stakeholder details updated successfully!')
    },
    onError: () => {
      // show server validation errors automatically
      toast.error('Failed to update stakeholder details.')
    },
  })
}

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

</script>

<template>
  <Head title="User" />
  <div class="p-6">
    <div class="flex justify-between">
        <h1 class="text-2xl font-bold mb-4">User Management</h1>
        <Button variant="default" as-child>
          <Link href="/user-management/user-create">
              <Plus class="h-4 w-4"/>
              Add Stakeholder
          </Link>
        </Button>
    </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">Name</th>
          <th class="p-2 border">Email</th>
          <th class="p-2 border">Role</th>
          <th class="p-2 border">Created at</th>
          <th class="p-2 border">Action</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in users.data" :key="user.id">
          <td class="p-2 border">{{ getRowNumber(index) }}</td>
          <td class="p-2 border">{{ user.name }}</td>
          <td class="p-2 border">{{ user.email }}</td>
          <td class="p-2 border">
            <Badge variant="secondary">{{ user.role }}</Badge>
          </td>
          <td class="p-2 border">{{ user.created_at }}</td>
          <td class="p-2 border">
            <!-- Edit Dialog -->
            <Dialog @close="() => { 
                editUser.value = null; 
                form.reset(); 
            }">
              <DialogTrigger asChild>
                <Button variant="link" @click="openEdit(user)">
                  <Edit class="h-4 w-4" />
                  Edit
                </Button>
              </DialogTrigger>
              <DialogContent class="w-full sm:min-w-md md:min-w-lg">
                <DialogHeader>
                  <DialogTitle>Edit Stakeholder</DialogTitle>
                  <DialogDescription>
                    Update the stakeholder 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>

                  <!-- email -->
                  <div class="space-y-2">
                    <Label for="email">Email</Label>
                    <Input id="email" v-model="form.email" />
                    <div v-if="form.errors.email" class="text-red-500 text-sm">
                      {{ form.errors.email }}
                    </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'" @click="destroyUser(user.id)" :disabled="form.processing">
              <Trash class="h-4 w-4"/>
              Delete
            </Button>
          </td>
        </tr>
        
        <!-- Show message if no users -->
        <tr v-if="users.data.length === 0">
          <td colspan="6" class="p-4 border text-center text-gray-500">
            No users found.
          </td>
        </tr>
      </tbody>
    </table>

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

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

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

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

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