<script setup lang="ts">
import AppLayout from '@/layouts/AppLayout.vue'
import { useForm, Head } from '@inertiajs/vue3'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu'
import Dialog from '@/components/ui/dialog/Dialog.vue'
import DialogTrigger from '@/components/ui/dialog/DialogTrigger.vue'
import DialogContent from '@/components/ui/dialog/DialogContent.vue'
import DialogHeader from '@/components/ui/dialog/DialogHeader.vue'
import DialogTitle from '@/components/ui/dialog/DialogTitle.vue'
import DialogDescription from '@/components/ui/dialog/DialogDescription.vue'
import DialogFooter from '@/components/ui/dialog/DialogFooter.vue'
import DialogClose from '@/components/ui/dialog/DialogClose.vue'
import type { BreadcrumbItemType } from '@/types'
import { useToast } from 'vue-toastification'

defineOptions({
  layout: AppLayout,
})

const props = defineProps<{
  userOperation: {
    id: number
    project_id: number
    user_id: number
    designation: number
    tech_skills: number
    power: number
    influence: number
    interpersonal_relationship: number
    experience: number
    user: { id: number; name: string }
    project: { id: number; name: string }
  }
  projects: { id: number; name: string }[]
  stakeholders: { id: number; name: string }[]
  breadcrumbs: BreadcrumbItemType[]
}>()

const form = useForm({
  id: props.userOperation.id,
  project_id: props.userOperation.project_id,
  user_id: props.userOperation.user_id,
  designation: props.userOperation.designation,
  tech_skills: props.userOperation.tech_skills,
  power: props.userOperation.power,
  influence: props.userOperation.influence,
  interpersonal_relationship: props.userOperation.interpersonal_relationship,
  experience: props.userOperation.experience,
})

// Type-safe numeric fields
type NumericFieldKey =
  | 'designation'
  | 'interpersonal_relationship'
  | 'influence'
  | 'experience'
  | 'power'
  | 'tech_skills'

const numericFields: { key: NumericFieldKey; label: string }[] = [
  { key: 'designation', label: 'Designation' },
  { key: 'interpersonal_relationship', label: 'Interpersonal Relationship' },
  { key: 'influence', label: 'Influence' },
  { key: 'experience', label: 'Experience' },
  { key: 'power', label: 'Power' },
  { key: 'tech_skills', label: 'Technical Skills' },
]

const valueMatrix = [
  { sl: 1, designation: 'Top Most', designationValue: 10, power: 'Absolutely High', powerValue: 10, domainKnowledge: 'Absolutely High', domainKnowledgeValue: 10, experience: '10 Years', experienceValue: 10, influence: 'Absolutely High', influenceValue: 10, interest: 'Absolutely High', interestValue: 10 },
  { sl: 2, designation: 'Top Middle', designationValue: 9, power: 'Very High', powerValue: 9, domainKnowledge: 'Very High', domainKnowledgeValue: 9, experience: '9 Years', experienceValue: 9, influence: 'Very High', influenceValue: 9, interest: 'Very High', interestValue: 9 },
  { sl: 3, designation: 'Miserable Top', designationValue: 8, power: 'High', powerValue: 8, domainKnowledge: 'High', domainKnowledgeValue: 8, experience: '8 Years', experienceValue: 8, influence: 'High', influenceValue: 8, interest: 'High', interestValue: 8 },
  { sl: 4, designation: 'Uppere Middle', designationValue: 7, power: 'Moderate High', powerValue: 7, domainKnowledge: 'Moderate High', domainKnowledgeValue: 7, experience: '7 Years', experienceValue: 7, influence: 'Moderate High', influenceValue: 7, interest: 'Moderate High', interestValue: 7 },
  { sl: 5, designation: 'Middle', designationValue: 6, power: 'Medium', powerValue: 6, domainKnowledge: 'Medium', domainKnowledgeValue: 6, experience: '6 Years', experienceValue: 6, influence: 'Medium', influenceValue: 6, interest: 'Medium', interestValue: 6 },
  { sl: 6, designation: 'Lower Middle', designationValue: 5, power: 'Moderate Low', powerValue: 5, domainKnowledge: 'Moderate Low', domainKnowledgeValue: 5, experience: '5 Years', experienceValue: 5, influence: 'Moderate Low', influenceValue: 5, interest: 'Moderate Low', interestValue: 5 },
  { sl: 7, designation: 'Upper Lower', designationValue: 4, power: 'Poor', powerValue: 4, domainKnowledge: 'Poor', domainKnowledgeValue: 4, experience: '4 Years', experienceValue: 4, influence: 'Poor', influenceValue: 4, interest: 'Poor', interestValue: 4 },
  { sl: 8, designation: 'Lower', designationValue: 3, power: 'Low', powerValue: 3, domainKnowledge: 'Low', domainKnowledgeValue: 3, experience: '3 Years', experienceValue: 3, influence: 'Low', influenceValue: 3, interest: 'Low', interestValue: 3 },
  { sl: 9, designation: 'Miserable Lower', designationValue: 2, power: 'Normal', powerValue: 2, domainKnowledge: 'Normal', domainKnowledgeValue: 2, experience: '2 Years', experienceValue: 2, influence: 'Normal', influenceValue: 2, interest: 'Normal', interestValue: 2 },
  { sl: 10, designation: 'Most Lower', designationValue: 1, power: 'Very Low', powerValue: 1, domainKnowledge: 'Very Low', domainKnowledgeValue: 1, experience: '1 Year', experienceValue: 1, influence: 'Very Low', influenceValue: 1, interest: 'Very Low', interestValue: 1 },
]

const toast = useToast();

const submit = () => {
    // console.log('Submitting form with ID:', form);
    if (!form.id) return; // make sure the ID exists
    form.put(`/fuzzy-operations/edit-operations/${form.id}`, {
    onSuccess: () => {
      toast.success('Fuzzy operation updated successfully!');
      form.reset();
    },
    onError: () => {
      toast.error('Failed to update fuzzy operation. Please check the form.');
    },
  });
}

const reset = () => {
  form.reset()
}

</script>

<template>
  <Head title="Edit Operation" />
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-6">Edit Operation</h1>

    <div class="flex justify-between items-center mb-6">
        <p>Please fill-up the form to add new fuzzy operation</p>
        <Dialog>
            <!-- Button that opens the dialog -->
            <DialogTrigger asChild>
              <Button variant="link">Refer to Value Matrix</Button>
            </DialogTrigger>

            <!-- Dialog content -->
            <DialogContent class="w-full sm:min-w-2xl md:min-w-3xl lg:min-w-5xl">
                <DialogHeader>
                    <DialogTitle>Value Matrix</DialogTitle>
                    <DialogDescription>
                    Shows the value mapping for Designation, Power, Domain Knowledge, Experience, Influence, and Interest.
                    </DialogDescription>
                </DialogHeader>

                <div class="overflow-x-auto max-h-[70vh] mt-4">
                    <table class="min-w-full border border-gray-300 text-sm">
                    <thead class="bg-gray-100 sticky top-0 dark:bg-neutral-900">
                        <tr>
                        <th class="border px-2 py-1">SL No.</th>
                        <th class="border px-2 py-1">Designation</th>
                        <th class="border px-2 py-1">Value</th>
                        <th class="border px-2 py-1">Power</th>
                        <th class="border px-2 py-1">Value</th>
                        <th class="border px-2 py-1">Domain Knowledge</th>
                        <th class="border px-2 py-1">Value</th>
                        <th class="border px-2 py-1">Experience</th>
                        <th class="border px-2 py-1">Value</th>
                        <th class="border px-2 py-1">Influence</th>
                        <th class="border px-2 py-1">Value</th>
                        <th class="border px-2 py-1">Interest</th>
                        <th class="border px-2 py-1">Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="row in valueMatrix" :key="row.sl">
                        <td class="border px-2 py-1">{{ row.sl }}</td>
                        <td class="border px-2 py-1">{{ row.designation }}</td>
                        <td class="border px-2 py-1">{{ row.designationValue }}</td>
                        <td class="border px-2 py-1">{{ row.power }}</td>
                        <td class="border px-2 py-1">{{ row.powerValue }}</td>
                        <td class="border px-2 py-1">{{ row.domainKnowledge }}</td>
                        <td class="border px-2 py-1">{{ row.domainKnowledgeValue }}</td>
                        <td class="border px-2 py-1">{{ row.experience }}</td>
                        <td class="border px-2 py-1">{{ row.experienceValue }}</td>
                        <td class="border px-2 py-1">{{ row.influence }}</td>
                        <td class="border px-2 py-1">{{ row.influenceValue }}</td>
                        <td class="border px-2 py-1">{{ row.interest }}</td>
                        <td class="border px-2 py-1">{{ row.interestValue }}</td>
                        </tr>
                    </tbody>
                    </table>
                </div>

                <DialogFooter class="mt-4 flex justify-end">
                    <DialogClose asChild>
                    <Button>Close</Button>
                    </DialogClose>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    </div>

    <form @submit.prevent="submit" class="grid grid-cols-2 gap-6">

      <!-- Left Column -->
      <div class="space-y-4">
        <!-- Project Dropdown -->
        <div class="space-y-1">
          <Label>Project</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" disabled>
                <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="text-gray-800 dark:text-gray-100 hover:bg-gray-50"
                @click="form.project_id = project.id"
              >
                {{ project.name }}
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
          <div v-if="form.errors.project_id" class="text-red-500 text-sm">
            {{ form.errors.project_id }}
          </div>
        </div>

        <!-- Numeric Fields Left Column -->
        <div
          v-for="field in numericFields.slice(0, 3)"
          :key="field.key"
          class="space-y-2"
        >
          <Label>{{ field.label }}</Label>
          <Input v-model="form[field.key]" type="number" min="0" max="10" />
          <div v-if="form.errors[field.key]" class="text-red-500 text-sm">
            {{ form.errors[field.key] }}
          </div>
        </div>
      </div>

      <!-- Right Column -->
      <div class="space-y-4">
        <!-- Stakeholder Dropdown -->
        <div class="space-y-1">
          <Label>Stakeholder</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" disabled>
                <span class="text-left">
                  {{ form.user_id ? props.stakeholders.find(s => s.id === form.user_id)?.name : 'Select a Stakeholder' }}
                </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="stakeholder in props.stakeholders"
                :key="stakeholder.id"
                class="text-gray-800 dark:text-gray-100 hover:bg-gray-50"
                :class="{ 'opacity-50 cursor-not-allowed': assignedUserIds.includes(stakeholder.id) }"
                :disabled="assignedUserIds.includes(stakeholder.id)"
                @click="!assignedUserIds.includes(stakeholder.id) && (form.user_id = stakeholder.id)"
              >
                {{ stakeholder.name }}
              </DropdownMenuItem> -->
            </DropdownMenuContent>
          </DropdownMenu>
          <div v-if="form.errors.user_id" class="text-red-500 text-sm">
            {{ form.errors.user_id }}
          </div>
        </div>

        <!-- Numeric Fields Right Column -->
        <div
          v-for="field in numericFields.slice(3)"
          :key="field.key"
          class="space-y-2"
        >
          <Label>{{ field.label }}</Label>
          <Input v-model="form[field.key]" type="number" min="0" max="10"/>
          <div v-if="form.errors[field.key]" class="text-red-500 text-sm">
            {{ form.errors[field.key] }}
          </div>
        </div>
      </div>

      <!-- Submit Button -->
      <div class="col-span-2 flex justify-end mt-4 space-x-2">
        <Button type="button" variant="outline" @click="reset">
            Reset
        </Button>
        <Button type="submit" variant="default" :disabled="form.processing">
          Edit Operation
        </Button>
      </div>
    </form>
  </div>
</template>
