<script setup>
const props = defineProps({
  modelValue: Boolean,
  selectedRowData: Object,
  isMobile: Boolean,
  columns: {
    type: [Array, Object],
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'save-user'])

const isEditMode = ref(false)
const editedData = ref({})

watch(() => props.modelValue, (newVal) => {
  if (newVal && props.selectedRowData) {
    editedData.value = { ...props.selectedRowData }
  }
})

const handleEnterKey = () => {
  if (isEditMode.value) {
    saveChanges()
  }
}

const closeDialog = () => {
  isEditMode.value = false
  emit('update:modelValue', false)
}

const toggleEditMode = () => {
  if (!isEditMode.value) {
    editedData.value = { ...props.selectedRowData }
  }
  isEditMode.value = !isEditMode.value
}

const saveChanges = () => {
  emit('save-user', editedData.value)
  isEditMode.value = false
}

const cancelEdit = () => {
  editedData.value = { ...props.selectedRowData }
  isEditMode.value = false
}

const formatDate = (dateValue) => {
  if (!dateValue) return 'N/A'

  const date = new Date(dateValue)
  if (isNaN(date.getTime())) return 'Invalid Date'

  const day = date.getDate().toString().padStart(2, '0')
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const year = date.getFullYear()

  return `${day}/${month}/${year}`
}

const formatDateForInput = (dateValue) => {
  if (!dateValue) return ''
  const date = new Date(dateValue)
  if (isNaN(date.getTime())) return ''
  return date.toISOString().split('T')[0]
}

const formatSalary = (salaryValue) => {
  if (!salaryValue) return 'N/A'
  const intValue = Math.floor(Number(salaryValue))
  return `$${intValue.toLocaleString()}`
}

const getStatusLabel = (statusValue) => {
  const statusMap = {
    0: 'Applied',
    1: 'Current',
    2: 'Professional',
    3: 'Rejected',
    4: 'Resigned'
  }
  return statusMap[statusValue] || 'Applied'
}

const getStatusColor = (statusValue) => {
  const colorMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'error',
    4: 'warning'
  }
  return colorMap[statusValue] || 'grey'
}

const statusOptions = [
  { value: 0, title: 'Applied', color: 'info' },
  { value: 1, title: 'Current', color: 'primary' },
  { value: 2, title: 'Professional', color: 'success' },
  { value: 3, title: 'Rejected', color: 'error' },
  { value: 4, title: 'Resigned', color: 'warning' }
]

const getFieldIcon = (field) => {
  const iconMap = {
    name: 'tabler-user',
    email: 'tabler-mail',
    startDate: 'tabler-calendar',
    salary: 'tabler-currency-dollar',
    age: 'tabler-hourglass',
    status: 'tabler-badge'
  }
  return iconMap[field] || 'tabler-info-circle'
}

const visibleColumns = computed(() => {
  const list = Array.isArray(props.columns) ? props.columns : (props.columns?.value || [])
  return list.filter(c => c.field && c.field !== 'action')
})
</script>

<template>
  <v-dialog :model-value="modelValue" @update:model-value="closeDialog" :max-width="isMobile ? '95%' : '700px'" persistent>
    <v-card 
      class="elevation-12" 
      rounded="lg"
      :style="{
        background: 'rgba(var(--v-theme-surface), 0.15)',
        backdropFilter: 'blur(20px)',
        webkitBackdropFilter: 'blur(20px)',
        border: '1px solid rgba(var(--v-theme-outline), 0.2)',
        boxShadow: '0 25px 45px rgba(0,0,0,0.1)'
      }"
    >
      <v-card-title class="bg-primary text-white pa-4">
        <div class="d-flex justify-space-between align-center w-100">
          <div class="d-flex align-center">
            <v-icon icon="tabler-user-circle" size="28" class="me-3" />
            <span class="text-h5">{{ isEditMode ? 'Edit User' : 'User Details' }}</span>
          </div>

          <div class="d-flex align-center gap-2">
            <template v-if="!isEditMode">
              <v-btn
                icon="tabler-edit"
                variant="text"
                size="small"
                color="white"
                :disabled="!selectedRowData"
                @click="toggleEditMode"
                title="Edit"
              />
              <v-btn
                icon="tabler-x"
                variant="text"
                size="small"
                color="white"
                @click="closeDialog"
                title="Close"
              />
            </template>
            <template v-else>
              <v-btn
                icon="tabler-x"
                variant="text"
                size="small"
                color="white"
                @click="cancelEdit"
                title="Cancel"
              />
              <v-btn
                icon="tabler-check"
                variant="text"
                size="small"
                color="white"
                @click="saveChanges"
                title="Save"
              />
            </template>
          </div>
        </div>
      </v-card-title>

      <v-card-text class="pa-6" v-if="selectedRowData">
        <v-form @keyup.enter="handleEnterKey">
          <v-container fluid class="pa-0">
            <v-row>
              <v-col
                v-for="col in visibleColumns"
                :key="col.field"
                cols="12" sm="6" class="mb-2"
              >
                <v-card variant="outlined" class="pa-4 h-100" color="surface-variant">
                  <div class="d-flex align-center">
                    <v-avatar 
                      class="me-4" 
                      size="40"
                      :style="{
                        background: 'rgba(var(--v-theme-primary), 0.2)',
                        backdropFilter: 'blur(10px)',
                        webkitBackdropFilter: 'blur(10px)',
                        border: '1px solid rgba(var(--v-theme-primary), 0.3)'
                      }"
                    >
                      <v-icon :icon="getFieldIcon(col.field)" color="primary" />
                    </v-avatar>
                    <div class="flex-grow-1">
                      <v-card-subtitle class="pa-0 text-caption text-medium-emphasis">{{ col.headerName || col.field }}</v-card-subtitle>
                      <template v-if="!isEditMode">
                        <v-card-title class="pa-0 text-body-1 text-high-emphasis">
                          {{ Array.isArray(selectedRowData[col.field]) || typeof selectedRowData[col.field] === 'object' ? JSON.stringify(selectedRowData[col.field]) : (selectedRowData[col.field] ?? 'N/A') }}
                        </v-card-title>
                      </template>
                      <template v-else>
                        <v-text-field
                          v-if="col.editable !== false && col.field !== 'status'"
                          v-model="editedData[col.field]"
                          variant="outlined"
                          density="compact"
                          hide-details
                          class="mt-1"
                          :type="col.field.toLowerCase().includes('date') ? 'date' : (typeof selectedRowData[col.field] === 'number' ? 'number' : 'text')"
                        />
                        <v-select
                          v-else-if="col.field === 'status'"
                          v-model="editedData.status"
                          :items="statusOptions"
                          variant="outlined"
                          density="compact"
                          hide-details
                          class="mt-1"
                        />
                      </template>
                    </div>
                  </div>
                </v-card>
              </v-col>
            </v-row>

            <v-row class="mt-4">
              <v-col cols="12">
                <v-alert type="info" variant="tonal" class="mb-0" icon="tabler-info-circle">
                  <v-alert-title class="text-body-1 font-weight-medium">Summary Information</v-alert-title>
                  <div class="mt-2 text-body-2">
                    Employee
                    <strong>{{ (isEditMode ? editedData.fullName : selectedRowData.fullName) || 'Unknown' }}</strong>
                    {{ (isEditMode ? editedData.age : selectedRowData.age) ? `(${isEditMode ? editedData.age : selectedRowData.age} years old)` : '' }}
                    has been with the company since
                    <strong>{{ formatDate(isEditMode ? editedData.startDate : selectedRowData.startDate) }}</strong>
                    with a current status of
                    <strong>{{ getStatusLabel(isEditMode ? editedData.status : selectedRowData.status) }}</strong>.
                  </div>
                </v-alert>
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>

      <v-divider />
    </v-card>
  </v-dialog>
</template>