<template>
  <Layout>
    <h2 class="page-title">{{ isSupervisor ? 'Inspections' : 'My Tasks' }}</h2>
    <p class="page-sub">{{ isSupervisor ? 'Schedule, assign, and track all inspections.' : 'All inspections assigned to you.' }}</p>

    <div class="toolbar">
      <button v-if="isSupervisor" class="btn-primary" @click="openNewModal">+ New inspection</button>
      <input type="search" v-model="search" placeholder="Search title or equipment…" style="max-width:280px" />
      <select v-model="statusFilter" style="max-width:200px">
        <option value="">All {{ isTechnician ? 'Tasks' : 'Statuses' }}</option>
        <option v-for="s in uniqueStatuses" :key="s" :value="s">{{ s }}</option>
      </select>
    </div>

    <div class="tabs" v-if="!isSupervisor">
      <button :class="{ active: typeFilter === '' }" @click="typeFilter = ''">All</button>
      <button :class="{ active: typeFilter === 'daily' }" @click="typeFilter = 'daily'">Daily</button>
      <button :class="{ active: typeFilter === 'weekly' }" @click="typeFilter = 'weekly'">Weekly</button>
      <button :class="{ active: typeFilter === 'monthly' }" @click="typeFilter = 'monthly'">Monthly</button>
    </div>

    <div class="panel">
      <table v-if="filteredInspections.length">
        <thead><tr><th>Inspection</th><th>Type</th><th>Scheduled</th><th>Assigned</th><th>Status</th><th></th></tr></thead>
        <tbody>
          <tr v-for="i in filteredInspections" :key="i.id" class="clickable" @click="openDetail(i)">
            <td style="font-weight: 600">{{ i.title }}<br><small style="color:#64748b">{{ i.equipment?.name }}</small></td>
            <td style="text-transform: capitalize">{{ i.inspection_type }}</td>
            <td>{{ formatDate(i.scheduled_date) }}</td>
            <td>{{ i.assignee?.name || '—' }}</td>
            <td><span :class="badgeClass(i.status)">{{ i.status }}</span></td>
            <td><button class="btn-sm">View</button></td>
          </tr>
        </tbody>
      </table>
      <div v-else class="state"><div class="big">📭</div>No inspections match.</div>
    </div>

    <!-- Detail Modal -->
    <Modal :show="!!selected" :title="selected?.title || ''" @close="selected = null">
      <div v-if="selected" class="inspection-detail">
        <div class="detail-grid">
          <div><div class="k">Equipment</div><div class="v">{{ selected.equipment?.name || '—' }}</div></div>
          <div><div class="k">Area / Location</div><div class="v">{{ selected.equipment?.area }} · {{ selected.equipment?.location }}</div></div>
          <div><div class="k">Type</div><div class="v" style="text-transform: capitalize">{{ selected.inspection_type }}</div></div>
          <div><div class="k">Status</div><div class="v"><span :class="badgeClass(selected.status)">{{ selected.status }}</span></div></div>
          <div><div class="k">Scheduled</div><div class="v">{{ formatDate(selected.scheduled_date) }}</div></div>
          <div><div class="k">Assigned to</div><div class="v">{{ selected.assignee?.name || '—' }}</div></div>
        </div>

        <div v-if="selected.revision_notes && selected.status === 'Needs Revision'" class="note-box">
          <strong>Supervisor asked for revision:</strong> {{ selected.revision_notes }}
        </div>

        <!-- Supervisor Action Forms -->
        <div v-if="activeAction === 'return'" class="section note-box" style="background: #fef2f2; border-color: #fecaca; color: #991b1b">
          <h3>Return for Revision</h3>
          <div class="field">
            <label>Correction Notes</label>
            <textarea v-model="actionNotes" placeholder="Explain what needs to be fixed..."></textarea>
          </div>
          <div class="modal-actions" style="border: none; margin-top: 0; padding-top: 0">
            <button class="btn-sm" @click="activeAction = null">Cancel</button>
            <button class="btn-primary" @click="submitTransition('return', { revision_notes: actionNotes })" :disabled="!actionNotes">Confirm Return</button>
          </div>
        </div>

        <div v-if="activeAction === 'assign'" class="section note-box" style="background: #eff6ff; border-color: #bfdbfe; color: #1e40af">
          <h3>Assign Technician</h3>
          <div class="field">
            <label>Select Technician</label>
            <select v-model="actionTechId">
              <option v-for="t in techs" :key="t.id" :value="t.id">{{ t.name }}</option>
            </select>
          </div>
          <div class="modal-actions" style="border: none; margin-top: 0; padding-top: 0">
            <button class="btn-sm" @click="activeAction = null">Cancel</button>
            <button class="btn-primary" @click="submitTransition('assign', { assigned_to: actionTechId })" :disabled="!actionTechId">Confirm Assignment</button>
          </div>
        </div>

        <div v-if="activeAction === 'reschedule'" class="section note-box">
          <h3>Reschedule Inspection</h3>
          <div class="field">
            <label>New Date</label>
            <input type="date" v-model="actionDate" />
          </div>
          <div class="modal-actions" style="border: none; margin-top: 0; padding-top: 0">
            <button class="btn-sm" @click="activeAction = null">Cancel</button>
            <button class="btn-primary" @click="submitTransition('reschedule', { scheduled_date: actionDate })" :disabled="!actionDate">Confirm Reschedule</button>
          </div>
        </div>

        <div v-if="checklist.length" class="section">
          <h3>Checklist</h3>
          <div v-for="(item, idx) in checklist" :key="idx" class="check-item">
            <div class="ci-head">
              <div class="ci-name">{{ item.item }}</div>
              <div class="ci-toggle">
                <button type="button" @click="setItemCond(idx, 'normal')" :disabled="!isEditable" :class="{ 'sel-normal': item.condition === 'normal' }">Normal</button>
                <button type="button" @click="setItemCond(idx, 'abnormal')" :disabled="!isEditable" :class="{ 'sel-abnormal': item.condition === 'abnormal' }">Abnormal</button>
              </div>
            </div>
            <div class="ci-note">
              <input type="text" v-model="item.note" placeholder="Note / reading" :disabled="!isEditable" />
            </div>
            <div v-if="item.condition === 'abnormal'" class="ci-evidence">
               <label class="ci-ev-label">Abnormal condition photo</label>
               <div v-if="item.photo" class="ci-preview">
                 <img :src="item.photo" @click="openPhoto(item.photo)" class="clickable" />
                 <button v-if="isEditable" class="btn-sm red" @click="item.photo = ''">Remove</button>
               </div>
               <input v-else-if="isEditable" type="file" @change="e => uploadPhoto(idx, e)" accept="image/*" class="ci-file" />
               <p v-else class="ci-ev-help">No photo evidence provided.</p>
            </div>
          </div>
        </div>

        <div v-if="isEditable || selected.result_notes" class="field">
          <label>Result Notes</label>
          <textarea v-model="resultNotes" :disabled="!isEditable" placeholder="Add summary of findings or results..."></textarea>
        </div>

        <div class="modal-actions">
          <!-- Technician Actions -->
          <template v-if="isTechnician">
            <button v-if="canStart" class="btn-primary" @click="transition('start')">▶ Start Inspection</button>
            <button v-if="isEditable" class="btn-sm" @click="raiseFinding">⚠ Raise Finding</button>
            <button v-if="isEditable" class="btn-sm" @click="saveProgress">Save Progress</button>
            <button v-if="isEditable" class="btn-primary" @click="transition('submit', { checklist_results: checklist, result_notes: resultNotes })">Submit for Validation</button>
          </template>

          <!-- Supervisor Actions -->
          <template v-if="isSupervisor">
             <template v-if="selected.status === 'Awaiting Validation' && !activeAction">
               <button class="btn-primary" @click="transition('validate')">✓ Validate (Complete)</button>
               <button class="btn-sm red" @click="activeAction = 'return'">↩ Return for Revision</button>
             </template>
             <template v-if="['Scheduled', 'Assigned', 'Overdue', 'Rescheduled'].includes(selected.status) && !activeAction">
               <button class="btn-sm blue" @click="activeAction = 'assign'">Assign Technician</button>
               <button class="btn-sm" @click="activeAction = 'reschedule'">Reschedule</button>
               <button class="btn-sm red" @click="cancelInspection">Cancel</button>
             </template>
          </template>
          
          <button class="btn-sm" @click="selected = null">Close</button>
        </div>
      </div>
    </Modal>

    <!-- New Inspection Modal -->
    <Modal :show="showNew" title="New Inspection" @close="showNew = false">
       <form @submit.prevent="submitNew" class="grid2">
         <div class="field" style="grid-column: span 2">
           <label>Title</label>
           <input v-model="newForm.title" required placeholder="e.g. Daily check — VHF Radio" />
         </div>
         <div class="field">
           <label>Type</label>
           <select v-model="newForm.inspection_type" required>
             <option value="daily">Daily</option>
             <option value="weekly">Weekly</option>
             <option value="monthly">Monthly</option>
           </select>
         </div>
         <div class="field">
           <label>Equipment</label>
           <select v-model="newForm.equipment_id" required>
             <option v-for="e in equipment" :key="e.id" :value="e.id">{{ e.name }} ({{ e.area }})</option>
           </select>
         </div>
         <div class="field">
           <label>Checklist Template</label>
           <select v-model="newForm.checklist_template_id" required>
             <option v-for="t in filteredTemplates" :key="t.id" :value="t.id">{{ t.name }}</option>
           </select>
         </div>
         <div class="field">
           <label>Assign To</label>
           <select v-model="newForm.assigned_to">
             <option :value="null">— Unassigned —</option>
             <option v-for="t in techs" :key="t.id" :value="t.id">{{ t.name }}</option>
           </select>
         </div>
         <div class="field">
           <label>Scheduled Date</label>
           <input type="date" v-model="newForm.scheduled_date" required />
         </div>
         <div class="field">
           <label>Priority</label>
           <select v-model="newForm.priority">
             <option value="low">Low</option>
             <option value="normal">Normal</option>
             <option value="high">High</option>
           </select>
         </div>
         <div class="modal-actions" style="grid-column: span 2">
           <button type="button" class="btn-sm" @click="showNew = false">Cancel</button>
           <button type="submit" class="btn-primary" :disabled="newForm.processing">Create</button>
         </div>
       </form>
    </Modal>
  </Layout>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { usePage, router, useForm } from '@inertiajs/vue3'
import Layout from '../../Shared/Layout.vue'
import Modal from '../../Shared/Modal.vue'
import { formatDate } from '../../helpers'

const props = defineProps({
  inspections: Array,
  equipment: Array,
  techs: Array,
  templates: Array,
})

const page = usePage()
const user = computed(() => page.props.auth.user)
const isSupervisor = computed(() => user.value.role === 'supervisor')
const isTechnician = computed(() => user.value.role === 'technician')

const search = ref('')
const statusFilter = ref('')
const typeFilter = ref('')

const uniqueStatuses = computed(() => [...new Set(props.inspections.map(i => i.status))])

const filteredInspections = computed(() => {
  return props.inspections.filter(i => {
    if (search.value && !(i.title + ' ' + (i.equipment?.name || '')).toLowerCase().includes(search.value.toLowerCase())) return false;
    if (statusFilter.value && i.status !== statusFilter.value) return false;
    if (typeFilter.value && i.inspection_type !== typeFilter.value) return false;
    return true;
  })
})

const badgeClass = (status) => {
  const map = {
    'Scheduled': 'badge b-grey', 'Assigned': 'badge b-blue', 'In Progress': 'badge b-amber',
    'Awaiting Validation': 'badge b-purple', 'Needs Revision': 'badge b-red', 'Completed': 'badge b-green',
    'Overdue': 'badge b-red', 'Cancelled': 'badge b-grey', 'Rescheduled': 'badge b-grey'
  }
  return map[status] || 'badge b-grey'
}

// Detail Logic
const selected = ref(null)
const checklist = ref([])
const resultNotes = ref('')

// Supervisor action state
const activeAction = ref(null) // 'return', 'assign', 'reschedule'
const actionNotes = ref('')
const actionTechId = ref(null)
const actionDate = ref('')

const isEditable = computed(() => {
  return isTechnician.value && 
         selected.value && 
         selected.value.assigned_to === user.value.id &&
         ['In Progress', 'Needs Revision'].includes(selected.value.status)
})

const canStart = computed(() => {
  return isTechnician.value && 
         selected.value && 
         selected.value.assigned_to === user.value.id &&
         ['Assigned', 'Scheduled', 'Rescheduled', 'Overdue'].includes(selected.value.status)
})

const openDetail = (i) => {
  selected.value = i
  activeAction.value = null
  actionNotes.value = ''
  actionTechId.value = i.assigned_to
  actionDate.value = i.scheduled_date
  if (i.checklist_results) {
    checklist.value = JSON.parse(JSON.stringify(i.checklist_results))
  } else if (i.checklist_template_id) {
    const tpl = props.templates.find(t => t.id === i.checklist_template_id)
    checklist.value = tpl ? tpl.items.map(it => ({ item: it, condition: 'normal', note: '', photo: '' })) : []
  }
  resultNotes.value = i.result_notes || ''
}

const setItemCond = (idx, cond) => {
  checklist.value[idx].condition = cond
  if (cond === 'normal') checklist.value[idx].photo = ''
}

const transition = (action, extra = {}) => {
  router.post(window.route('inspections.transition', selected.value.id), { action, ...extra }, {
    onSuccess: () => {
      // Find the updated inspection in the list and update selected
      const updated = props.inspections.find(i => i.id === selected.value.id)
      if (updated) openDetail(updated)
      else selected.value = null
      activeAction.value = null
    }
  })
}

const submitTransition = (action, extra) => {
  transition(action, extra)
}

const saveProgress = () => {
  router.put(window.route('inspections.update', selected.value.id), {
    checklist_results: checklist.value,
    result_notes: resultNotes.value
  }, {
    onSuccess: () => alert('Progress saved locally')
  })
}

const uploadPhoto = (idx, event) => {
  const file = event.target.files[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = (e) => {
    checklist.value[idx].photo = e.target.result
  }
  reader.readAsDataURL(file)
}

const openPhoto = (src) => {
  window.open(src, '_blank')
}

const raiseFinding = () => {
  // Logic for raising a finding could go here or link to findings page
  alert('Raise finding logic triggered for ' + selected.value.title)
}

const returnForRevision = () => {
  const notes = prompt('Enter correction notes for the technician:')
  if (notes) transition('return', { revision_notes: notes })
}

const openAssign = () => {
  const techId = prompt('Enter Technician ID (E.g. 1, 2, 3):')
  if (techId) transition('assign', { assigned_to: techId })
}

const openReschedule = () => {
  const date = prompt('Enter new scheduled date (YYYY-MM-DD):')
  if (date) transition('reschedule', { scheduled_date: date })
}

const cancelInspection = () => {
  if (confirm('Cancel this inspection?')) transition('cancel')
}

// New Inspection Logic
const showNew = ref(false)
const newForm = useForm({
  title: '',
  inspection_type: 'daily',
  equipment_id: '',
  checklist_template_id: '',
  assigned_to: null,
  scheduled_date: new Date().toISOString().split('T')[0],
  priority: 'normal'
})

const filteredTemplates = computed(() => {
  return props.templates.filter(t => t.inspection_type === newForm.inspection_type)
})

const openNewModal = () => {
  newForm.reset()
  if (props.equipment.length) newForm.equipment_id = props.equipment[0].id
  showNew.value = true
}

const submitNew = () => {
  newForm.post(window.route('inspections.store'), {
    onSuccess: () => {
      showNew.value = false
    }
  })
}

// Listen for deep updates from dashboard links
const urlParams = new URLSearchParams(window.location.search);
const openId = urlParams.get('open');
if (openId) {
  const i = props.inspections.find(x => String(x.id) === String(openId));
  if (i) openDetail(i);
}
</script>
