<template>
  <div class="layout-px-spacing">
    <teleport to="#breadcrumb">
      <ul class="navbar-nav flex-row">
        <li>
          <div class="page-header">
            <nav class="breadcrumb-one">
              <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="javascript:;">{{ $t("admin.config_empresa.breadcrumb_parent") }}</a></li>
                <li class="breadcrumb-item active">{{ $t("admin.config_empresa.breadcrumb_current") }}</li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div class="panel p-4">
          <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
            <div>
              <h4 class="mb-0">{{ $t("admin.config_empresa.title") }}</h4>
              <p class="text-muted small mb-0 mt-1">{{ $t("admin.config_empresa.subtitle") }}</p>
            </div>
            <div>
              <button type="button" class="btn btn-outline-secondary me-2" :disabled="loading || saving" @click="cargar">
                {{ $t("admin.config_empresa.reload") }}
              </button>
              <button type="button" class="btn btn-primary" :disabled="loading || saving" @click="guardar">
                {{ saving ? $t("admin.config_empresa.saving") : $t("admin.config_empresa.save") }}
              </button>
            </div>
          </div>

          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status"></div>
          </div>

          <template v-else>
            <div class="card mb-4">
              <div class="card-header">{{ $t("admin.config_empresa.section_branding") }}</div>
              <div class="card-body">
                <div class="row align-items-center">
                  <div class="col-md-4 text-center mb-3 mb-md-0">
                    <img :src="logoPreview" alt="Logo" class="img-fluid rounded border p-2" style="max-height: 140px" @error="onLogoPreviewError" />
                    <p class="small text-muted mt-2">{{ $t("admin.config_empresa.logo_hint") }}</p>
                  </div>
                  <div class="col-md-8">
                    <label class="form-label">{{ $t("admin.config_empresa.f_logo") }}</label>
                    <input type="file" class="form-control mb-2" accept="image/*" @change="onLogoSelected" />
                    <div class="d-flex flex-wrap gap-2">
                      <button type="button" class="btn btn-primary btn-sm" :disabled="!logoFile || uploadingLogo" @click="subirLogo">
                        {{ uploadingLogo ? $t("admin.config_empresa.uploading") : $t("admin.config_empresa.upload_logo") }}
                      </button>
                      <button type="button" class="btn btn-outline-danger btn-sm" :disabled="!configRow?.logo_url || uploadingLogo" @click="eliminarLogo">
                        {{ $t("admin.config_empresa.delete_logo") }}
                      </button>
                    </div>
                    <hr class="my-3" />
                    <label class="form-label">{{ $t("admin.config_empresa.f_favicon") }}</label>
                    <input type="file" class="form-control mb-2" accept="image/*" @change="onFaviconSelected" />
                    <button type="button" class="btn btn-outline-primary btn-sm" :disabled="!faviconFile || uploadingFavicon" @click="subirFavicon">
                      {{ uploadingFavicon ? $t("admin.config_empresa.uploading") : $t("admin.config_empresa.upload_favicon") }}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <form @submit.prevent="guardar">
              <div class="card mb-4">
                <div class="card-header">{{ $t("admin.config_empresa.section_general") }}</div>
                <div class="card-body row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_nombre_empresa") }} *</label>
                    <input v-model="form.nombre_empresa" class="form-control" maxlength="255" required />
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_nombre_corto") }} *</label>
                    <input v-model="form.nombre_corto" class="form-control" maxlength="50" required />
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_rfc") }}</label>
                    <input v-model="form.rfc" class="form-control" maxlength="13" />
                  </div>
                  <div class="col-12 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_nombre_largo") }} *</label>
                    <input v-model="form.nombre_largo" class="form-control" maxlength="500" required />
                  </div>
                  <div class="col-12 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_descripcion") }}</label>
                    <textarea v-model="form.descripcion" class="form-control" rows="2" maxlength="1000"></textarea>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_telefono") }}</label>
                    <input v-model="form.telefono" class="form-control" maxlength="20" />
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_email") }}</label>
                    <input v-model="form.email" type="email" class="form-control" maxlength="255" />
                  </div>
                  <div class="col-12 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_direccion") }}</label>
                    <input v-model="form.direccion" class="form-control" maxlength="500" />
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_codigo_postal") }}</label>
                    <input v-model="form.codigo_postal" class="form-control" maxlength="10" />
                  </div>
                  <div class="col-md-4 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_ciudad") }}</label>
                    <input v-model="form.ciudad" class="form-control" maxlength="100" />
                  </div>
                  <div class="col-md-3 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_estado") }}</label>
                    <input v-model="form.estado" class="form-control" maxlength="100" />
                  </div>
                  <div class="col-md-2 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_pais") }}</label>
                    <input v-model="form.pais" class="form-control" maxlength="100" />
                  </div>
                  <div class="col-12 mb-0">
                    <label class="form-label">{{ $t("admin.config_empresa.f_sitio_web") }}</label>
                    <input v-model="form.sitio_web" class="form-control" maxlength="255" placeholder="https://" />
                  </div>
                </div>
              </div>

              <div class="card mb-4">
                <div class="card-header">{{ $t("admin.config_empresa.section_welcome") }}</div>
                <div class="card-body row">
                  <div class="col-12 mb-3">
                    <label class="form-label">{{ $t("admin.config_empresa.f_bienvenida") }}</label>
                    <input v-model="form.bienvenida" class="form-control" maxlength="255" />
                  </div>
                  <div class="col-12 mb-0">
                    <label class="form-label">{{ $t("admin.config_empresa.f_politica") }}</label>
                    <textarea v-model="form.politica_privacidad" class="form-control" rows="3"></textarea>
                  </div>
                </div>
              </div>

              <button type="submit" class="btn btn-primary" :disabled="saving">
                {{ saving ? $t("admin.config_empresa.saving") : $t("admin.config_empresa.save") }}
              </button>
            </form>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import ApiService from "@/services/ApiService";
import { useConfiguracionEmpresaStore } from "@/store/ConfiguracionEmpresaStore";

const { t } = useI18n();
const configuracionStore = useConfiguracionEmpresaStore();

const defaultLogo = "/logo-rancho.svg";
const loading = ref(true);
const saving = ref(false);
const uploadingLogo = ref(false);
const uploadingFavicon = ref(false);
const configRow = ref(null);
const logoFile = ref(null);
const faviconFile = ref(null);
const logoPreviewOverride = ref(null);

const UPDATE_FIELDS = [
  "nombre_empresa", "nombre_corto", "nombre_largo", "rfc", "descripcion",
  "telefono", "email", "direccion", "codigo_postal", "ciudad", "estado", "pais", "sitio_web",
  "politica_privacidad", "bienvenida",
];

const form = ref({
  nombre_empresa: "",
  nombre_corto: "",
  nombre_largo: "",
  rfc: "",
  descripcion: "",
  telefono: "",
  email: "",
  direccion: "",
  codigo_postal: "",
  ciudad: "",
  estado: "",
  pais: "México",
  sitio_web: "",
  politica_privacidad: "",
  bienvenida: "",
});

const logoPreview = computed(() => {
  if (logoPreviewOverride.value) return logoPreviewOverride.value;
  return configRow.value?.logo_url || defaultLogo;
});

function toast(msg, icon) {
  window.Swal?.fire({ icon, title: msg, timer: icon === "success" ? 2200 : undefined, showConfirmButton: icon !== "success" });
}

function mapFromApi(data) {
  if (!data) return;
  configRow.value = data;
  const next = { ...form.value };
  for (const key of UPDATE_FIELDS) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      next[key] = data[key] ?? "";
    }
  }
  form.value = next;
}

function buildPayload() {
  const o = {};
  for (const key of UPDATE_FIELDS) {
    let v = form.value[key];
    if (key === "sitio_web" && typeof v === "string" && v.trim() === "") v = null;
    o[key] = v;
  }
  return o;
}

async function cargar() {
  loading.value = true;
  try {
    const res = await ApiService.get("configuracion-empresa");
    mapFromApi(res.data?.data);
  } catch {
    toast(t("admin.config_empresa.load_error"), "error");
  } finally {
    loading.value = false;
  }
}

async function guardar() {
  saving.value = true;
  try {
    await configuracionStore.actualizarConfiguracion(buildPayload());
    mapFromApi(configuracionStore.configuracion);
    toast(t("admin.config_empresa.saved"), "success");
  } catch (e) {
    const err = e.response?.data;
    toast(err?.message || t("admin.config_empresa.save_error"), "error");
  } finally {
    saving.value = false;
  }
}

function onLogoSelected(e) {
  const file = e.target.files?.[0];
  logoFile.value = file || null;
  if (file) {
    logoPreviewOverride.value = URL.createObjectURL(file);
  }
}

function onFaviconSelected(e) {
  faviconFile.value = e.target.files?.[0] || null;
}

function onLogoPreviewError(e) {
  e.target.src = defaultLogo;
}

async function subirLogo() {
  if (!logoFile.value) return;
  uploadingLogo.value = true;
  try {
    const fd = new FormData();
    fd.append("logo", logoFile.value);
    const res = await configuracionStore.subirLogo(fd);
    mapFromApi(res.data);
    logoPreviewOverride.value = null;
    logoFile.value = null;
    toast(t("admin.config_empresa.logo_uploaded"), "success");
  } catch {
    toast(t("admin.config_empresa.logo_upload_error"), "error");
  } finally {
    uploadingLogo.value = false;
  }
}

async function eliminarLogo() {
  uploadingLogo.value = true;
  try {
    const res = await configuracionStore.eliminarLogo();
    mapFromApi(res.data);
    logoPreviewOverride.value = null;
    toast(t("admin.config_empresa.logo_deleted"), "success");
  } catch {
    toast(t("admin.config_empresa.logo_upload_error"), "error");
  } finally {
    uploadingLogo.value = false;
  }
}

async function subirFavicon() {
  if (!faviconFile.value) return;
  uploadingFavicon.value = true;
  try {
    const fd = new FormData();
    fd.append("favicon", faviconFile.value);
    const res = await configuracionStore.subirFavicon(fd);
    mapFromApi(res.data);
    faviconFile.value = null;
    toast(t("admin.config_empresa.favicon_uploaded"), "success");
  } catch {
    toast(t("admin.config_empresa.favicon_upload_error"), "error");
  } finally {
    uploadingFavicon.value = false;
  }
}

onMounted(cargar);
</script>
