<script lang="ts" setup>
import { useForm, router } from '@inertiajs/vue3'
import { ref } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import type { Department, SlaPolicy, SlaBusinessHoursEntry, TicketTag, TicketCustomField } from '@/types'

interface StaffUser {
  id: number
  name: string
  email: string
}

interface Props {
  departments: Department[]
  slaPolicies: SlaPolicy[]
  businessHours: SlaBusinessHoursEntry[]
  tags: TicketTag[]
  customFields: TicketCustomField[]
  staffUsers: StaffUser[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const activeTab = ref<string>('departments')

// --- Department ---
const deptDialog = ref<boolean>(false)
const editingDept = ref<Department | null>(null)
const deptForm = useForm({
  name: '',
  slug: '',
  email: null as string | null,
  auto_assign_to: null as number | null,
  sla_policy_id: null as number | null,
  sort_order: 0,
})

function openDeptDialog(dept: Department | null): void {
  editingDept.value = dept
  if (dept) {
    deptForm.name = dept.name
    deptForm.slug = dept.slug
    deptForm.email = dept.email
    deptForm.auto_assign_to = dept.auto_assign_to
    deptForm.sla_policy_id = dept.sla_policy_id
    deptForm.sort_order = dept.sort_order
  } else {
    deptForm.reset()
  }
  deptDialog.value = true
}

function saveDept(): void {
  if (editingDept.value) {
    deptForm.put(`/tickets/settings/departments/${editingDept.value.id}`, {
      preserveScroll: true,
      onSuccess: () => { deptDialog.value = false },
    })
  } else {
    deptForm.post('/tickets/settings/departments', {
      preserveScroll: true,
      onSuccess: () => { deptDialog.value = false },
    })
  }
}

function deleteDept(dept: Department): void {
  if (confirm(`Delete department "${dept.name}"?`)) {
    router.delete(`/tickets/settings/departments/${dept.id}`, { preserveScroll: true })
  }
}

// --- SLA Policy ---
const slaDialog = ref<boolean>(false)
const editingSla = ref<SlaPolicy | null>(null)
const slaForm = useForm({
  name: '',
  priority: 'medium' as string,
  first_response_hours: 4,
  resolution_hours: 24,
  business_hours_only: true,
})

function openSlaDialog(sla: SlaPolicy | null): void {
  editingSla.value = sla
  if (sla) {
    slaForm.name = sla.name
    slaForm.priority = sla.priority
    slaForm.first_response_hours = sla.first_response_hours
    slaForm.resolution_hours = sla.resolution_hours
    slaForm.business_hours_only = sla.business_hours_only
  } else {
    slaForm.reset()
  }
  slaDialog.value = true
}

function saveSla(): void {
  if (editingSla.value) {
    slaForm.put(`/tickets/settings/sla-policies/${editingSla.value.id}`, {
      preserveScroll: true,
      onSuccess: () => { slaDialog.value = false },
    })
  } else {
    slaForm.post('/tickets/settings/sla-policies', {
      preserveScroll: true,
      onSuccess: () => { slaDialog.value = false },
    })
  }
}

function deleteSla(sla: SlaPolicy): void {
  if (confirm(`Delete SLA policy "${sla.name}"?`)) {
    router.delete(`/tickets/settings/sla-policies/${sla.id}`, { preserveScroll: true })
  }
}

// --- Business Hours ---
const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

function initBusinessHours(): SlaBusinessHoursEntry[] {
  return Array.from({ length: 7 }, (_, i) => {
    const existing = props.businessHours.find(bh => bh.day_of_week === i)
    return existing ? { ...existing } : {
      day_of_week: i,
      start_time: '09:00',
      end_time: '17:00',
      is_holiday: i === 0 || i === 6,
    }
  })
}

const businessHoursLocal = ref<SlaBusinessHoursEntry[]>(initBusinessHours())
const savingHours = ref<boolean>(false)

function saveBusinessHours(): void {
  savingHours.value = true
  const activeHours = businessHoursLocal.value.filter(h => !h.is_holiday)
  router.put('/tickets/settings/business-hours', {
    hours: activeHours,
  }, {
    preserveScroll: true,
    onFinish: () => { savingHours.value = false },
  })
}

// --- Tags ---
const tagDialog = ref<boolean>(false)
const editingTag = ref<TicketTag | null>(null)
const tagForm = useForm({
  name: '',
  color: '#3b82f6',
})

function openTagDialog(tag: TicketTag | null): void {
  editingTag.value = tag
  if (tag) {
    tagForm.name = tag.name
    tagForm.color = tag.color
  } else {
    tagForm.reset()
    tagForm.color = '#3b82f6'
  }
  tagDialog.value = true
}

function saveTag(): void {
  if (editingTag.value) {
    tagForm.put(`/tickets/settings/tags/${editingTag.value.id}`, {
      preserveScroll: true,
      onSuccess: () => { tagDialog.value = false },
    })
  } else {
    tagForm.post('/tickets/settings/tags', {
      preserveScroll: true,
      onSuccess: () => { tagDialog.value = false },
    })
  }
}

function deleteTag(tag: TicketTag): void {
  if (confirm(`Delete tag "${tag.name}"?`)) {
    router.delete(`/tickets/settings/tags/${tag.id}`, { preserveScroll: true })
  }
}

// --- Custom Fields ---
const cfDialog = ref<boolean>(false)
const editingCf = ref<TicketCustomField | null>(null)
const cfForm = useForm({
  name: '',
  type: 'text' as string,
  options: [] as string[],
  is_required: false,
  department_id: null as number | null,
  sort_order: 0,
})
const newOption = ref<string>('')

function openCfDialog(cf: TicketCustomField | null): void {
  editingCf.value = cf
  if (cf) {
    cfForm.name = cf.name
    cfForm.type = cf.type
    cfForm.options = cf.options ?? []
    cfForm.is_required = cf.is_required
    cfForm.department_id = cf.department_id
    cfForm.sort_order = cf.sort_order
  } else {
    cfForm.reset()
    cfForm.options = []
  }
  cfDialog.value = true
}

function addOption(): void {
  if (newOption.value.trim()) {
    cfForm.options.push(newOption.value.trim())
    newOption.value = ''
  }
}

function removeOption(index: number): void {
  cfForm.options.splice(index, 1)
}

function saveCf(): void {
  if (editingCf.value) {
    cfForm.put(`/tickets/settings/custom-fields/${editingCf.value.id}`, {
      preserveScroll: true,
      onSuccess: () => { cfDialog.value = false },
    })
  } else {
    cfForm.post('/tickets/settings/custom-fields', {
      preserveScroll: true,
      onSuccess: () => { cfDialog.value = false },
    })
  }
}

function deleteCf(cf: TicketCustomField): void {
  if (confirm(`Delete custom field "${cf.name}"?`)) {
    router.delete(`/tickets/settings/custom-fields/${cf.id}`, { preserveScroll: true })
  }
}

const priorityOptions = [
  { title: 'Low', value: 'low' },
  { title: 'Medium', value: 'medium' },
  { title: 'High', value: 'high' },
  { title: 'Urgent', value: 'urgent' },
]

const fieldTypeOptions = [
  { title: 'Text', value: 'text' },
  { title: 'Select', value: 'select' },
  { title: 'Checkbox', value: 'checkbox' },
  { title: 'Number', value: 'number' },
]

const staffOptions = props.staffUsers.map(u => ({ title: `${u.name} (${u.email})`, value: u.id }))
const slaPolicyOptions = props.slaPolicies.map(s => ({ title: s.name, value: s.id }))
const departmentOptions = props.departments.map(d => ({ title: d.name, value: d.id }))
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Ticket Settings
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Configure departments, SLA policies, tags, custom fields, and business hours
        </div>
      </div>
    </div>

    <VCard>
      <VTabs v-model="activeTab">
        <VTab value="departments">
          Departments
        </VTab>
        <VTab value="sla">
          SLA Policies
        </VTab>
        <VTab value="hours">
          Business Hours
        </VTab>
        <VTab value="tags">
          Tags
        </VTab>
        <VTab value="fields">
          Custom Fields
        </VTab>
      </VTabs>

      <VDivider />

      <VCardText>
        <VWindow v-model="activeTab">
          <!-- Departments Tab -->
          <VWindowItem value="departments">
            <div class="d-flex justify-end mb-4">
              <VBtn color="primary" @click="openDeptDialog(null)">
                <VIcon icon="tabler-plus" start />
                Add Department
              </VBtn>
            </div>
            <VTable density="comfortable" hover>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Slug</th>
                  <th>Email</th>
                  <th>Auto-Assign</th>
                  <th>SLA Policy</th>
                  <th>Order</th>
                  <th class="text-center">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="dept in departments" :key="dept.id">
                  <td class="text-body-2 font-weight-medium">
                    {{ dept.name }}
                  </td>
                  <td class="text-body-2 text-medium-emphasis">
                    {{ dept.slug }}
                  </td>
                  <td class="text-body-2">
                    {{ dept.email ?? '-' }}
                  </td>
                  <td class="text-body-2">
                    {{ dept.auto_assignee?.name ?? '-' }}
                  </td>
                  <td class="text-body-2">
                    {{ dept.sla_policy?.name ?? '-' }}
                  </td>
                  <td class="text-body-2">
                    {{ dept.sort_order }}
                  </td>
                  <td class="text-center">
                    <VBtn variant="text" size="small" color="primary" @click="openDeptDialog(dept)">
                      <VIcon icon="tabler-edit" size="18" />
                    </VBtn>
                    <VBtn variant="text" size="small" color="error" @click="deleteDept(dept)">
                      <VIcon icon="tabler-trash" size="18" />
                    </VBtn>
                  </td>
                </tr>
                <tr v-if="departments.length === 0">
                  <td colspan="7" class="text-center text-medium-emphasis py-6">
                    No departments configured.
                  </td>
                </tr>
              </tbody>
            </VTable>
          </VWindowItem>

          <!-- SLA Policies Tab -->
          <VWindowItem value="sla">
            <div class="d-flex justify-end mb-4">
              <VBtn color="primary" @click="openSlaDialog(null)">
                <VIcon icon="tabler-plus" start />
                Add SLA Policy
              </VBtn>
            </div>
            <VTable density="comfortable" hover>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Priority</th>
                  <th>First Response</th>
                  <th>Resolution</th>
                  <th>Business Hours</th>
                  <th class="text-center">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="sla in slaPolicies" :key="sla.id">
                  <td class="text-body-2 font-weight-medium">
                    {{ sla.name }}
                  </td>
                  <td class="text-body-2 text-capitalize">
                    {{ sla.priority }}
                  </td>
                  <td class="text-body-2">
                    {{ sla.first_response_hours }}h
                  </td>
                  <td class="text-body-2">
                    {{ sla.resolution_hours }}h
                  </td>
                  <td>
                    <VChip :color="sla.business_hours_only ? 'info' : 'warning'" size="small">
                      {{ sla.business_hours_only ? 'Business Hours' : '24/7' }}
                    </VChip>
                  </td>
                  <td class="text-center">
                    <VBtn variant="text" size="small" color="primary" @click="openSlaDialog(sla)">
                      <VIcon icon="tabler-edit" size="18" />
                    </VBtn>
                    <VBtn variant="text" size="small" color="error" @click="deleteSla(sla)">
                      <VIcon icon="tabler-trash" size="18" />
                    </VBtn>
                  </td>
                </tr>
                <tr v-if="slaPolicies.length === 0">
                  <td colspan="6" class="text-center text-medium-emphasis py-6">
                    No SLA policies configured.
                  </td>
                </tr>
              </tbody>
            </VTable>
          </VWindowItem>

          <!-- Business Hours Tab -->
          <VWindowItem value="hours">
            <div class="mb-4">
              <p class="text-body-2 text-medium-emphasis mb-4">
                Configure business hours for SLA calculations. Days marked as holiday will be excluded.
              </p>
              <VTable density="comfortable">
                <thead>
                  <tr>
                    <th>Day</th>
                    <th>Start Time</th>
                    <th>End Time</th>
                    <th>Holiday</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(hours, index) in businessHoursLocal" :key="index">
                    <td class="text-body-2 font-weight-medium">
                      {{ dayNames[hours.day_of_week] }}
                    </td>
                    <td>
                      <VTextField
                        v-model="hours.start_time"
                        type="time"
                        density="compact"
                        hide-details
                        :disabled="hours.is_holiday"
                        style="max-width: 160px;"
                      />
                    </td>
                    <td>
                      <VTextField
                        v-model="hours.end_time"
                        type="time"
                        density="compact"
                        hide-details
                        :disabled="hours.is_holiday"
                        style="max-width: 160px;"
                      />
                    </td>
                    <td>
                      <VCheckbox
                        v-model="hours.is_holiday"
                        hide-details
                        density="compact"
                      />
                    </td>
                  </tr>
                </tbody>
              </VTable>
              <div class="d-flex justify-end mt-4">
                <VBtn color="primary" :loading="savingHours" @click="saveBusinessHours">
                  Save Business Hours
                </VBtn>
              </div>
            </div>
          </VWindowItem>

          <!-- Tags Tab -->
          <VWindowItem value="tags">
            <div class="d-flex justify-end mb-4">
              <VBtn color="primary" @click="openTagDialog(null)">
                <VIcon icon="tabler-plus" start />
                Add Tag
              </VBtn>
            </div>
            <VTable density="comfortable" hover>
              <thead>
                <tr>
                  <th>Color</th>
                  <th>Name</th>
                  <th class="text-center">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="tag in tags" :key="tag.id">
                  <td>
                    <div
                      :style="{ backgroundColor: tag.color, width: '24px', height: '24px', borderRadius: '4px' }"
                    />
                  </td>
                  <td class="text-body-2 font-weight-medium">
                    <VChip :color="tag.color" size="small">
                      {{ tag.name }}
                    </VChip>
                  </td>
                  <td class="text-center">
                    <VBtn variant="text" size="small" color="primary" @click="openTagDialog(tag)">
                      <VIcon icon="tabler-edit" size="18" />
                    </VBtn>
                    <VBtn variant="text" size="small" color="error" @click="deleteTag(tag)">
                      <VIcon icon="tabler-trash" size="18" />
                    </VBtn>
                  </td>
                </tr>
                <tr v-if="tags.length === 0">
                  <td colspan="3" class="text-center text-medium-emphasis py-6">
                    No tags configured.
                  </td>
                </tr>
              </tbody>
            </VTable>
          </VWindowItem>

          <!-- Custom Fields Tab -->
          <VWindowItem value="fields">
            <div class="d-flex justify-end mb-4">
              <VBtn color="primary" @click="openCfDialog(null)">
                <VIcon icon="tabler-plus" start />
                Add Custom Field
              </VBtn>
            </div>
            <VTable density="comfortable" hover>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Type</th>
                  <th>Required</th>
                  <th>Department</th>
                  <th>Order</th>
                  <th class="text-center">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="cf in customFields" :key="cf.id">
                  <td class="text-body-2 font-weight-medium">
                    {{ cf.name }}
                  </td>
                  <td class="text-body-2 text-capitalize">
                    {{ cf.type }}
                  </td>
                  <td>
                    <VChip :color="cf.is_required ? 'error' : 'default'" size="small">
                      {{ cf.is_required ? 'Yes' : 'No' }}
                    </VChip>
                  </td>
                  <td class="text-body-2">
                    {{ cf.department?.name ?? 'All' }}
                  </td>
                  <td class="text-body-2">
                    {{ cf.sort_order }}
                  </td>
                  <td class="text-center">
                    <VBtn variant="text" size="small" color="primary" @click="openCfDialog(cf)">
                      <VIcon icon="tabler-edit" size="18" />
                    </VBtn>
                    <VBtn variant="text" size="small" color="error" @click="deleteCf(cf)">
                      <VIcon icon="tabler-trash" size="18" />
                    </VBtn>
                  </td>
                </tr>
                <tr v-if="customFields.length === 0">
                  <td colspan="6" class="text-center text-medium-emphasis py-6">
                    No custom fields configured.
                  </td>
                </tr>
              </tbody>
            </VTable>
          </VWindowItem>
        </VWindow>
      </VCardText>
    </VCard>

    <!-- Department Dialog -->
    <VDialog v-model="deptDialog" max-width="600" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          {{ editingDept ? 'Edit Department' : 'Add Department' }}
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          <VRow>
            <VCol cols="12" md="6">
              <VTextField
                v-model="deptForm.name"
                label="Name"
                :error-messages="deptForm.errors.name"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model="deptForm.slug"
                label="Slug"
                :error-messages="deptForm.errors.slug"
              />
            </VCol>
            <VCol cols="12">
              <VTextField
                v-model="deptForm.email"
                label="Email (optional)"
                type="email"
                :error-messages="deptForm.errors.email"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSelect
                v-model="deptForm.auto_assign_to"
                :items="staffOptions"
                label="Auto-Assign To"
                clearable
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSelect
                v-model="deptForm.sla_policy_id"
                :items="slaPolicyOptions"
                label="SLA Policy"
                clearable
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model.number="deptForm.sort_order"
                label="Sort Order"
                type="number"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" @click="deptDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="deptForm.processing" @click="saveDept">
            Save
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- SLA Policy Dialog -->
    <VDialog v-model="slaDialog" max-width="600" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          {{ editingSla ? 'Edit SLA Policy' : 'Add SLA Policy' }}
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          <VRow>
            <VCol cols="12">
              <VTextField
                v-model="slaForm.name"
                label="Name"
                :error-messages="slaForm.errors.name"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSelect
                v-model="slaForm.priority"
                :items="priorityOptions"
                label="Priority"
                :error-messages="slaForm.errors.priority"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VCheckbox
                v-model="slaForm.business_hours_only"
                label="Business Hours Only"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model.number="slaForm.first_response_hours"
                label="First Response (hours)"
                type="number"
                :error-messages="slaForm.errors.first_response_hours"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model.number="slaForm.resolution_hours"
                label="Resolution (hours)"
                type="number"
                :error-messages="slaForm.errors.resolution_hours"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" @click="slaDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="slaForm.processing" @click="saveSla">
            Save
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Tag Dialog -->
    <VDialog v-model="tagDialog" max-width="400" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          {{ editingTag ? 'Edit Tag' : 'Add Tag' }}
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          <VTextField
            v-model="tagForm.name"
            label="Name"
            :error-messages="tagForm.errors.name"
            class="mb-4"
          />
          <VTextField
            v-model="tagForm.color"
            label="Color (hex)"
            :error-messages="tagForm.errors.color"
            class="mb-2"
          >
            <template #prepend>
              <div
                :style="{ backgroundColor: tagForm.color, width: '32px', height: '32px', borderRadius: '4px', border: '1px solid #ccc' }"
              />
            </template>
          </VTextField>
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" @click="tagDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="tagForm.processing" @click="saveTag">
            Save
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Custom Field Dialog -->
    <VDialog v-model="cfDialog" max-width="600" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          {{ editingCf ? 'Edit Custom Field' : 'Add Custom Field' }}
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          <VRow>
            <VCol cols="12">
              <VTextField
                v-model="cfForm.name"
                label="Name"
                :error-messages="cfForm.errors.name"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSelect
                v-model="cfForm.type"
                :items="fieldTypeOptions"
                label="Type"
                :error-messages="cfForm.errors.type"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VSelect
                v-model="cfForm.department_id"
                :items="departmentOptions"
                label="Department (optional)"
                clearable
              />
            </VCol>
            <VCol cols="12" md="6">
              <VCheckbox
                v-model="cfForm.is_required"
                label="Required"
              />
            </VCol>
            <VCol cols="12" md="6">
              <VTextField
                v-model.number="cfForm.sort_order"
                label="Sort Order"
                type="number"
              />
            </VCol>
            <VCol v-if="cfForm.type === 'select'" cols="12">
              <div class="text-body-2 font-weight-medium mb-2">
                Options
              </div>
              <div class="d-flex ga-2 mb-2">
                <VTextField
                  v-model="newOption"
                  density="compact"
                  hide-details
                  placeholder="Add option..."
                  @keyup.enter="addOption"
                />
                <VBtn variant="tonal" size="small" @click="addOption">
                  Add
                </VBtn>
              </div>
              <VChip
                v-for="(opt, i) in cfForm.options"
                :key="i"
                closable
                class="me-1 mb-1"
                @click:close="removeOption(i)"
              >
                {{ opt }}
              </VChip>
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" @click="cfDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="cfForm.processing" @click="saveCf">
            Save
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
