<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 { router, useForm, Head } from '@inertiajs/vue3';
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose, DialogOverlay } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, } from '@/components/ui/dropdown-menu'
import { Play, Edit, Trash, Eye, ChevronLeft, ChevronRight } from 'lucide-vue-next'
import { ref, onMounted } from 'vue'
import { useToast } from 'vue-toastification'

defineOptions({
  layout: AppLayout,
})

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

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

const statusOptions = [
  { value: 'requirement change', label: 'Requirement Change' },
  { value: 'voting', label: 'Voting' },
  { value: 'calculate', label: 'Calculate' },
  { value: 'done', label: 'Done' },
]

const toast = useToast()

const openEdit = (project: any) => {
  editingProject.value = project
  form.name = project.name
  form.description = project.description
  form.status = project.status
}

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

  form.put(`/i-uspa-decisions/change-status/${editingProject.value.id}`, {
    onSuccess: () => {
      editingProject.value = null
      form.reset()
      toast.success('Project updated successfully!')
    },
    onError: () => {
      toast.error('Failed to update project.') // ❌ error toast
    },
  })
}

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

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

const calculate = (projectId: number) => {
  console.log("Calculate project ID:", projectId);
  if (confirm('Are you sure you want to calculate this project?')) {
    form.post(`/i-uspa-decisions/calculate/${projectId}`, {
      onSuccess: (page) => {
        // Check if backend returned a success flash message
        const message = page.props.flash?.success;
        if (message) {
          toast.success(message);
        } else {
          toast.success('Calculation initiated successfully!');
        }
      },
      onError: (errors) => {
        const message = errors.calculate ? errors.calculate : 'Failed to initiate calculation. Please try again.';
        toast.error(message);
      },
    })
  }
}

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

<template>
  <Head title="Change Status" />
  <div class="p-6">
    <div class="flex justify-between">
        <h1 class="text-2xl font-bold mb-4">Change Status Project</h1>
    </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">Project</th>
          <th class="p-2 border">Description</th>
          <th class="p-2 border">Status</th>
          <th class="p-2 border">Create at</th>
          <th class="p-2 border">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(project, index) in projects.data" :key="project.id">
          <td class="p-2 border">{{ getRowNumber(index) }}</td>
          <td class="p-2 border">{{ project.name }}</td>
          <td class="p-2 border">{{ project.description }}</td>
          <td class="p-2 border">
            <Badge variant="secondary">{{ project.status }}</Badge>
          </td>
          <td class="p-2 border">{{ project.created_at }}</td>
          <td class="p-2 border">
            <!-- Edit Dialog -->
            <Dialog @close="() => { 
                editingProject.value = null; 
                form.reset(); 
            }">
              <DialogTrigger asChild>
                <Button variant="link" @click="openEdit(project)">
                  <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 project 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>

                  <!-- Status Dropdown -->
                  <div class="space-y-2">
                    <Label>Status</Label>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          class="w-full bg-white dark:bg-neutral-900 dark:text-gray-100 text-gray-800 border rounded hover:bg-gray-50 flex justify-between items-center"
                        >
                          <span>
                            {{ form.status ? statusOptions.find(s => s.value === form.status)?.label : 'Select a Status' }}
                          </span>
                          <svg
                            class="w-4 h-4 ml-2 text-gray-500"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            viewBox="0 0 24 24"
                          >
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7"></path>
                          </svg>
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent class="bg-white text-gray-800 dark:bg-neutral-900 dark:text-gray-100 border rounded shadow-lg">
                        <DropdownMenuItem
                          v-for="option in statusOptions"
                          :key="option.value"
                          class="text-gray-800 dark:text-gray-100 hover:bg-gray-50"
                          @click="form.status = option.value"
                        >
                          {{ option.label }}
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                    <div v-if="form.errors.status" class="text-red-500 text-sm">
                      {{ form.errors.status }}
                    </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="project.status === 'calculate'"  @click="calculate(project.id)" :disabled="form.processing">
              <Play class="h-4 w-4"/>
              Compute now
            </Button>
          </td>
        </tr>
        
        <!-- Show message if no projects -->
        <tr v-if="projects.data.length === 0">
          <td colspan="6" class="p-4 border text-center text-gray-500">
            No projects found.
          </td>
        </tr>
      </tbody>
    </table>

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

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

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

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

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