<template>
  <Teleport to="body">
    <div
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
      @click.self="handleBackdropClick"
    >
      <div
        class="relative w-full max-w-lg mx-4 rounded-2xl bg-[#04151F] border border-white/10 shadow-2xl shadow-black/40 overflow-hidden"
      >
        <!-- Header -->
        <div class="flex items-center justify-between px-6 py-4 border-b border-white/10">
          <h3 class="text-lg font-semibold text-white">
            {{ isEditing ? t('company.settingsModalTitle') : t('company.companyDataTitle') }}
          </h3>
          <button
            @click="$emit('close')"
            class="p-1 rounded-lg text-white/50 hover:text-white hover:bg-white/10 transition-colors"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <!-- Body -->
        <div class="px-6 py-4 space-y-4 max-h-[70vh] overflow-y-auto">
          <!-- Loading -->
          <div v-if="isLoading" class="flex items-center justify-center py-8">
            <svg class="animate-spin h-8 w-8 text-[#00E5A0]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          </div>

          <template v-else>
            <!-- Company Name -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsName') }}</label>
              <input
                v-if="isEditing"
                v-model="form.name"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.name || '—' }}</p>
            </div>

            <!-- Full Company Name -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsFullName') }}</label>
              <input
                v-if="isEditing"
                v-model="form.full_name"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.full_name || '—' }}</p>
            </div>

            <!-- Display Name -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsDisplayName') }}</label>
              <input
                v-if="isEditing"
                v-model="form.display_name"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.display_name || '—' }}</p>
            </div>

            <!-- Tax Number (DISABLED in edit mode too) -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsTaxNumber') }}</label>
              <input
                v-if="isEditing"
                v-model="form.tax_number"
                type="text"
                disabled
                class="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white/50 text-sm cursor-not-allowed"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.tax_number || '—' }}</p>
            </div>

            <!-- Separator -->
            <div class="border-t border-white/10 my-2"></div>
            <p class="text-sm font-medium text-white/70 mb-2">{{ t('company.addressTitle') || 'Address' }}</p>

            <!-- ZIP Code -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsAddressZip') }}</label>
              <input
                v-if="isEditing"
                v-model="form.address_zip"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.address_zip || '—' }}</p>
            </div>

            <!-- City -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsAddressCity') }}</label>
              <input
                v-if="isEditing"
                v-model="form.address_city"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.address_city || '—' }}</p>
            </div>

            <!-- Street -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsAddressStreet') }}</label>
              <input
                v-if="isEditing"
                v-model="form.address_street_name"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.address_street_name || '—' }}</p>
            </div>

            <!-- House Number -->
            <div>
              <label class="block text-sm font-medium text-white/70 mb-1">{{ t('company.settingsAddressHouseNumber') }}</label>
              <input
                v-if="isEditing"
                v-model="form.address_house_number"
                type="text"
                class="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white text-sm focus:outline-none focus:border-[#00E5A0] placeholder-white/30"
              />
              <p v-else class="text-sm text-white/90 px-1">{{ org?.address_house_number || '—' }}</p>
            </div>
          </template>
        </div>

        <!-- Footer -->
        <div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-white/10">
          <button
            @click="isEditing ? cancelEdit() : $emit('close')"
            class="px-4 py-2 rounded-lg text-sm text-white/70 hover:text-white hover:bg-white/10 transition-colors"
          >
            {{ isEditing ? t('profile.cancel') : t('company.close') || t('header.close') }}
          </button>

          <!-- Edit button (read-only mode) -->
          <button
            v-if="!isEditing"
            @click="startEdit"
            class="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-sm transition-colors"
          >
            {{ t('profile.edit') }}
          </button>

          <!-- Save button (edit mode) -->
          <button
            v-else
            @click="handleSave"
            :disabled="isSaving"
            class="px-4 py-2 rounded-lg bg-[#00E5A0] hover:bg-[#00E5A0]/80 text-[#04151F] font-semibold text-sm transition-all duration-200 disabled:opacity-50"
          >
            <span v-if="isSaving" class="flex items-center gap-2">
              <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {{ t('company.submitting') }}
            </span>
            <span v-else>{{ t('profile.save') }}</span>
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import api from '@/api/axios'
import type { OrganizationItem } from '@/types/organization'

const { t } = useI18n()
const route = useRoute()
const authStore = useAuthStore()

const emit = defineEmits<{
  close: []
  saved: []
}>()

// ── State ───────────────────────────────────────────────────────────────────

const isLoading = ref(false)
const isSaving = ref(false)
const isEditing = ref(false)
const org = ref<OrganizationItem | null>(null)

const form = reactive({
  name: '',
  full_name: '',
  display_name: '',
  tax_number: '',
  address_zip: '',
  address_city: '',
  address_street_name: '',
  address_house_number: '',
})

// ── Lifecycle ───────────────────────────────────────────────────────────────

onMounted(async () => {
  const orgId = Number(route.params.id)
  if (!orgId) return

  // Find org from store
  const found = authStore.myOrganizations.find((o) => o.organization_id === orgId)
  if (found) {
    org.value = found
    prefillForm(found)
  } else {
    // Try to fetch fresh data
    isLoading.value = true
    try {
      await authStore.fetchMyOrganizations()
      const refound = authStore.myOrganizations.find((o) => o.organization_id === orgId)
      if (refound) {
        org.value = refound
        prefillForm(refound)
      }
    } catch (err) {
      console.error('Failed to load organization:', err)
    } finally {
      isLoading.value = false
    }
  }
})

// ── Helpers ─────────────────────────────────────────────────────────────────

function prefillForm(data: OrganizationItem) {
  form.name = data.name || ''
  form.full_name = data.full_name || ''
  form.display_name = data.display_name || ''
  form.tax_number = data.tax_number || ''
  // Address fields may come from a nested address object or flat fields
  // We use type-safe access with optional chaining
  form.address_zip = (data as any).address_zip || ''
  form.address_city = (data as any).address_city || ''
  form.address_street_name = (data as any).address_street_name || ''
  form.address_house_number = (data as any).address_house_number || ''
}

function startEdit() {
  // Re-populate form from current org data
  if (org.value) {
    prefillForm(org.value)
  }
  isEditing.value = true
}

function cancelEdit() {
  isEditing.value = false
  // Reset form to original values
  if (org.value) {
    prefillForm(org.value)
  }
}

function handleBackdropClick() {
  if (isEditing.value) {
    cancelEdit()
  } else {
    emit('close')
  }
}

// ── Save Handler ────────────────────────────────────────────────────────────

async function handleSave() {
  const orgId = Number(route.params.id)
  if (!orgId) return

  isSaving.value = true
  try {
    // Build payload with only non-empty fields
    const payload: Record<string, string> = {}
    for (const [key, value] of Object.entries(form)) {
      if (value.trim()) {
        payload[key] = value.trim()
      }
    }

    await api.patch(`/organizations/${orgId}`, payload)

    // Refresh org data in store
    await authStore.fetchMyOrganizations()

    // Update local org reference
    const updated = authStore.myOrganizations.find((o) => o.organization_id === orgId)
    if (updated) {
      org.value = updated
    }

    isEditing.value = false
    emit('saved')
  } catch (err: any) {
    console.error('Failed to save organization data:', err)
    alert(t('company.settingsSaveError'))
  } finally {
    isSaving.value = false
  }
}
</script>
