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

interface NFR {
  id: number
  name: string
  project_id: number
}

interface FR {
  id: number
  name: string
  project_id: number
  nonFunctionalRequirements: NFR[]   // 👈 link NFRs to FU
}

interface Project {
  id: number
  name: string
  status: string
  requirements: FR[]   // FRs already include their NFRs
}

defineOptions({
  layout: AppLayout,
})

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

const props = defineProps<{
  projects: Project[]
  stakeholders: { id: number; name: string }[]
  breadcrumbs: BreadcrumbItemType[]
}>()

const form = useForm<{
  project_id: number | ''
  user_id: number | ''
  nfu: number | ''
  fu: number | ''
  importance: string | ''
  votes: {
    project_id: number
    project_name: string
    fu_id: number
    fu_name: string
    nfu_id: number
    nfu_name: string
    importance: number
    label: string
  }[]
}>({
  project_id: '',
  user_id: '',
  nfu: '',
  fu: '',
  importance: '',
  votes: [], // initialize votes as empty array
})

const votes = ref<{
  project_id: number
  project_name: string
  fu_id: number
  fu_name: string
  nfu_id: number
  nfu_name: string
  importance: number
  label: string
}[]>([])

// Track temporary NFR votes for selected FU
const tempNFRVotes = ref<
  { nfu_id: number; nfu_name: string; importance: string }[]
>([])

const submitting = ref(false)

// Importance options with weights
const importanceOptions = [
  { value: 'negligible', label: 'Negligible', weight: 0.001 },
  { value: 'very_low', label: 'Very Low Importance', weight: 0.25 },
  { value: 'low', label: 'Low Importance', weight: 0.5 },
  { value: 'high', label: 'High Importance', weight: 0.75 },
  { value: 'very_high', label: 'Very High Importance', weight: 1 },
]

const toast = useToast()

const originalProjects = ref(cloneDeep(props.projects))
const projects = ref(cloneDeep(props.projects)) // this is what you mutate

const submitVotes = async () => {
  if (votes.value.length === 0) return

  // Assign votes to the form
  form.votes = votes.value

  console.log('Submitting payload:', form)

  form.post('/i-uspa-decisions', {
    onSuccess: () => {
      toast.success('All votes submitted successfully!')

      // Reset votes and form fields
      votes.value = []
      form.project_id = ''
      form.fu = ''
      form.nfu = ''
      form.importance = ''
      form.votes = []
    },
    onError: (errors) => {
      const message = errors.votes ? errors.votes : 'Failed to submit votes';
      toast.error(message);
    },
    onFinish: () => {
      submitting.value = false
    },
  })
}

const filteredFUs = computed(() => {
  if (!form.project_id) return []
  const project = projects.value.find(p => p.id === form.project_id)
  return project ? project.requirements : []
})

// Reset dependent dropdowns when selection changes
watch(() => form.project_id, () => {
  form.nfu = ''
  form.fu = ''
})

watch(() => form.fu, (fuId) => {
  tempNFRVotes.value = []
  if (!fuId) return

  const project = projects.value.find(p => p.id === form.project_id)
  const fu = project?.requirements.find(r => r.id === fuId)

  const nfrs = fu?.nonFunctionalRequirements || []
  tempNFRVotes.value = nfrs.map(nfr => ({
    nfu_id: nfr.id,
    nfu_name: nfr.name,
    importance: '',
  }))
})


const addFUVotes = () => {
  if (!form.project_id || !form.fu) return

  const project = projects.value.find(p => p.id === form.project_id)
  const fu = project?.requirements.find(r => r.id === form.fu)
  if (!project || !fu) return

  // Ensure all NFRs have importance selected
  const incomplete = tempNFRVotes.value.some(v => !v.importance)
  if (incomplete) {
    toast.warning('Please assign importance for all NFRs.')
    return
  }

  // Push votes with weight instead of string
  tempNFRVotes.value.forEach(v => {
  const opt = importanceOptions.find(o => o.value === v.importance)
  votes.value.push({
    project_id: project.id,
    project_name: project.name,
    fu_id: fu.id,
    fu_name: fu.name,
    nfu_id: v.nfu_id,
    nfu_name: v.nfu_name,
    importance: opt ? opt.weight : 0,   // backend gets weight
    label: opt ? opt.label : ''         // frontend shows label
  })
})


  // Remove NFRs that were voted
  fu.nonFunctionalRequirements = fu.nonFunctionalRequirements.filter(
    nfr => !tempNFRVotes.value.some(v => v.nfu_id === nfr.id)
  )

  if (fu.nonFunctionalRequirements.length === 0) {
    project.requirements = project.requirements.filter(r => r.id !== fu.id)
  }

  form.fu = ''
  tempNFRVotes.value = []
}


const removeVote = (index: number) => {
  const removed = votes.value[index]
  const project = projects.value.find(p => p.id === removed.project_id)
  if (!project) return

  let fu = project.requirements.find(f => f.id === removed.fu_id)

  if (!fu) {
    // If FU was already consumed, re-add it with the removed NFR
    fu = {
      id: removed.fu_id,
      name: removed.fu_name,
      project_id: removed.project_id,
      nonFunctionalRequirements: []
    }
    project.requirements.push(fu)
  }

  // Add back just this NFR
  fu.nonFunctionalRequirements.push({
    id: removed.nfu_id,
    name: removed.nfu_name,
    project_id: removed.project_id
  })

  // Remove from votes list
  votes.value.splice(index, 1)
}

const resetVotes = () => {
  votes.value = []
  form.project_id = ''
  form.fu = ''
  form.nfu = ''
  form.importance = ''

  // restore projects from the original copy
  projects.value = cloneDeep(originalProjects.value)
}
</script>

<template>
  <Head title="Decisions" />
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
        <!-- Left: Title -->
        <h1 class="text-2xl font-bold">I-USPA Decisions</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>
    <p class="mb-6">Please select the project backlog first before proceed to vote.</p>

    <form class="grid grid-cols-2 gap-6">
        <!-- Project Dropdown -->
        <div class="col-span-1 space-y-2">
            <Label>Project</Label>
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                <Button
                    class="w-full bg-white dark:bg-neutral-900 text-gray-800 dark:text-gray-100 border rounded hover:bg-gray-50 dark:hover:bg-neutral-800 flex justify-between items-center"
                >
                    <span class="text-left">
                    {{ form.project_id ? props.projects.find(p => p.id === form.project_id)?.name : 'Select a Project' }}
                    </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
                side="bottom"
                align="end"
                class="bg-white text-gray-800 dark:bg-neutral-900 dark:text-gray-100 border rounded shadow-lg"
                >
                <DropdownMenuItem
                    v-for="project in props.projects"
                    :key="project.id"
                    class="flex justify-between items-center w-full text-left dark:text-gray-100"
                    :class="{
                    'text-gray-400 cursor-not-allowed opacity-60': project.status !== 'voting',
                    'hover:bg-gray-50 text-neutral-800': project.status === 'voting'
                    }"
                    @click="project.status === 'voting' ? (form.project_id = project.id) : null"
                >
                    {{ project.name }}
                    <span class="ml-2 text-xs italic text-gray-500">({{ project.status }})</span>
                </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
            <div v-if="form.errors.project_id" class="text-red-500 text-sm">
                {{ form.errors.project_id }}
            </div>
        </div>

        <!-- FU B Dropdown -->
        <div class="space-y-2">
            <Label>Functional User Story</Label>
            <DropdownMenu :disabled="!form.project_id">
                <DropdownMenuTrigger asChild>
                    <Button
                        class="w-full bg-white dark:bg-neutral-900 text-gray-800 dark:text-gray-100 border rounded hover:bg-gray-50 dark:hover:bg-neutral-800 flex justify-between items-center"
                        :class="{ 'opacity-50 cursor-not-allowed': !form.project_id }"
                        >
                        <span>{{ form.fu ? filteredFUs.find(f => f.id === form.fu)?.name : 'Select Functional User story' }}</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 side="bottom" align="start" class="bg-white text-gray-800 dark:bg-neutral-900 dark:text-gray-100 border rounded shadow-lg">
                    <DropdownMenuItem
                        v-for="fu in filteredFUs"
                        :key="fu.id"
                        class="text-gray-800 hover:bg-gray-50 text-left dark:text-gray-100"
                        @click="form.fu = fu.id"
                        >
                        {{ fu.name }}
                    </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
            <div v-if="form.errors.fu" class="text-red-500 text-sm">
                {{ form.errors.fu }}
            </div>
        </div>

        <div v-if="form.fu && tempNFRVotes.length > 0" class="col-span-2">
            <table class="w-full border text-left">
                <thead class="bg-gray-100 dark:bg-neutral-900">
                    <tr>
                        <th class="p-2 border">NFR</th>
                        <th class="p-2 border">Importance</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(nfr, index) in tempNFRVotes" :key="nfr.nfu_id">
                        <td class="p-2 border">{{ nfr.nfu_name }}</td>
                        <td class="p-2 border">
                            <select v-model="nfr.importance" class="w-full border rounded p-1">
                                <option value="">Select importance</option>
                                <option v-for="opt in importanceOptions" :key="opt.value" :value="opt.value">
                                {{ opt.label }}
                                </option>
                            </select>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <!-- Buttons -->
        <div class="col-span-2 flex justify-end gap-2 mt-4">

            <Button type="button" variant="default" @click="addFUVotes">Add FU Votes</Button>
        </div>
    </form>

    <!-- Votes Table -->
    <div v-if="votes.length > 0" class="mt-6 overflow-x-auto">
        <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">Functional User Stories</th>
                <th class="p-2 border">Non-Functional Requirements</th>
                <th class="p-2 border">Importance</th>
                <th class="p-2 border">Action</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(vote, index) in votes" :key="index">
                    <td class="p-2 border">{{ index + 1 }}</td>
                    <td class="p-2 border">{{ vote.project_name }}</td>
                    <td class="p-2 border">{{ vote.fu_name }}</td>
                    <td class="p-2 border">{{ vote.nfu_name }}</td>
                    <td class="p-2 border">
                        {{ vote.label }}
                    </td>
                    <td class="p-2 border">
                        <Button variant="link" size="sm" @click="removeVote(index)">
                            <Trash class="h-4 w-4"/>
                            Remove
                        </Button>
                    </td>
                </tr>

                <tr v-if="votes.length === 0">
                    <td colspan="6" class="p-4 border text-center text-gray-500">
                        No votes added yet.
                    </td>
                </tr>
            </tbody>
        </table>

      <div class="mt-4 flex gap-2 justify-end">
        <Button variant="outline" @click="resetVotes">Reset All</Button>
        <Button
            variant="default"
            @click="submitVotes"
            :disabled="votes.length === 0 || submitting"
            :loading="submitting"
            >
            Submit All
        </Button>
      </div>
    </div>
  </div>
</template>
