<template>
  <!-- Modal Component -->
  <div
    class="modal fade"
    :class="{ show: isVisible, 'd-block': isVisible }"
    tabindex="-1"
    role="dialog"
    :aria-hidden="!isVisible"
  >
    <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
      <div class="modal-content">
        <!-- Header -->
        <div class="modal-header">
          <h5 class="modal-title">
            <i
              :class="
                isModification
                  ? 'fas fa-edit me-2'
                  : 'fas fa-map-marker-alt me-2'
              "
            ></i>
            {{
              isModification
                ? "Modifier la localisation"
                : "Ajouter une localisation"
            }}
          </h5>
          <button
            type="button"
            class="btn-close"
            aria-label="Close"
            :disabled="locationIsLoading"
            @click="closeModal"
          ></button>
        </div>

        <!-- Body -->
        <div class="modal-body">
          <!-- Error Alert -->
          <div v-if="generalError" class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ generalError }}
          </div>

          <form @submit.prevent="handleSubmit">
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">Nom de la localisation</label>
                <input
                  v-model="formData.name"
                  type="text"
                  class="form-control"
                  :class="{ 'is-invalid': errors.name }"
                  placeholder="Ex: Siège social"
                  maxlength="191"
                />
                <div v-if="errors.name" class="invalid-feedback">
                  {{ errors.name }}
                </div>
                <div class="form-text text-muted">
                  Optionnel - maximum 191 caractères
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">Type de localisation</label>
                <select
                  v-model="formData.location_type"
                  class="form-select"
                  :class="{ 'is-invalid': errors.location_type }"
                >
                  <option value="office">Bureau</option>
                  <option value="warehouse">Entrepôt</option>
                  <option value="store">Magasin</option>
                  <option value="other">Autre</option>
                </select>
                <div v-if="errors.location_type" class="invalid-feedback">
                  {{ errors.location_type }}
                </div>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Adresse ligne 1</label>
              <input
                v-model="formData.address_line1"
                type="text"
                class="form-control"
                :class="{ 'is-invalid': errors.address_line1 }"
                placeholder="Numéro et nom de rue"
                maxlength="255"
              />
              <div v-if="errors.address_line1" class="invalid-feedback">
                {{ errors.address_line1 }}
              </div>
              <div class="form-text text-muted">
                Optionnel - maximum 255 caractères
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Adresse ligne 2</label>
              <input
                v-model="formData.address_line2"
                type="text"
                class="form-control"
                :class="{ 'is-invalid': errors.address_line2 }"
                placeholder="Complément d'adresse"
                maxlength="255"
              />
              <div v-if="errors.address_line2" class="invalid-feedback">
                {{ errors.address_line2 }}
              </div>
              <div class="form-text text-muted">
                Optionnel - maximum 255 caractères
              </div>
            </div>

            <div class="row">
              <div class="col-md-4 mb-3">
                <label class="form-label">Code postal</label>
                <input
                  v-model="formData.postal_code"
                  type="text"
                  class="form-control"
                  :class="{ 'is-invalid': errors.postal_code }"
                  placeholder="Ex: 75001"
                  maxlength="20"
                />
                <div v-if="errors.postal_code" class="invalid-feedback">
                  {{ errors.postal_code }}
                </div>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">Ville</label>
                <input
                  v-model="formData.city"
                  type="text"
                  class="form-control"
                  :class="{ 'is-invalid': errors.city }"
                  placeholder="Ex: Paris"
                  maxlength="191"
                />
                <div v-if="errors.city" class="invalid-feedback">
                  {{ errors.city }}
                </div>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">Pays</label>
                <input
                  v-model="formData.country_code"
                  type="text"
                  class="form-control"
                  :class="{ 'is-invalid': errors.country_code }"
                  placeholder="Ex: FR"
                  maxlength="2"
                />
                <div v-if="errors.country_code" class="invalid-feedback">
                  {{ errors.country_code }}
                </div>
                <div class="form-text text-muted">
                  2 caractères (ex: FR, BE, DE)
                </div>
              </div>
            </div>

            <!-- Address Validation Alert -->
            <div
              v-if="showAddressWarning"
              class="alert alert-warning"
              role="alert"
            >
              <i class="fas fa-info-circle me-2"></i>
              Au moins un champ d'adresse (adresse, code postal ou ville) doit
              être renseigné.
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">Téléphone</label>
                <input
                  v-model="formData.phone"
                  type="tel"
                  class="form-control"
                  :class="{ 'is-invalid': errors.phone }"
                  placeholder="+33 1 23 45 67 89"
                />
                <div v-if="errors.phone" class="invalid-feedback">
                  {{ errors.phone }}
                </div>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">Email</label>
                <input
                  v-model="formData.email"
                  type="email"
                  class="form-control"
                  :class="{ 'is-invalid': errors.email }"
                  placeholder="contact@exemple.fr"
                />
                <div v-if="errors.email" class="invalid-feedback">
                  {{ errors.email }}
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">GPS Latitude</label>
                <input
                  v-model.number="formData.gps_lat"
                  type="number"
                  step="0.000001"
                  min="-90"
                  max="90"
                  class="form-control"
                  :class="{ 'is-invalid': errors.gps_lat }"
                  placeholder="Ex: 48.856614"
                />
                <div v-if="errors.gps_lat" class="invalid-feedback">
                  {{ errors.gps_lat }}
                </div>
                <div class="form-text text-muted">Entre -90 et 90</div>
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">GPS Longitude</label>
                <input
                  v-model.number="formData.gps_lng"
                  type="number"
                  step="0.000001"
                  min="-180"
                  max="180"
                  class="form-control"
                  :class="{ 'is-invalid': errors.gps_lng }"
                  placeholder="Ex: 2.352222"
                />
                <div v-if="errors.gps_lng" class="invalid-feedback">
                  {{ errors.gps_lng }}
                </div>
                <div class="form-text text-muted">Entre -180 et 180</div>
              </div>
            </div>



            <div class="form-check mb-3">
              <input
                id="isDefaultCheckbox"
                v-model="formData.is_default"
                class="form-check-input"
                type="checkbox"
                :class="{ 'is-invalid': errors.is_default }"
              />
              <label class="form-check-label" for="isDefaultCheckbox">
                Définir comme localisation par défaut
              </label>
              <div v-if="errors.is_default" class="invalid-feedback d-block">
                {{ errors.is_default }}
              </div>
            </div>
          </form>
        </div>

        <!-- Footer -->
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-outline-secondary"
            :disabled="locationIsLoading"
            @click="closeModal"
          >
            <i class="fas fa-times me-1"></i>
            Annuler
          </button>
          <button
            type="button"
            class="btn btn-primary"
            :disabled="locationIsLoading || !isFormValid"
            @click="handleSubmit"
          >
            <i class="fas fa-save me-1"></i>
            <span
              v-if="locationIsLoading"
              class="spinner-border spinner-border-sm me-2"
            ></span>
            {{
              locationIsLoading
                ? isModification
                  ? "Modification..."
                  : "Création..."
                : isModification
                ? "Modifier"
                : "Ajouter"
            }}
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Backdrop -->
  <div
    v-if="isVisible"
    class="modal-backdrop fade show"
    @click="closeModal"
  ></div>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted, onUnmounted } from "vue";
import { defineProps, defineEmits } from "vue";

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  clientId: {
    type: Number,
    required: true,
  },
  locationIsLoading: {
    type: Boolean,
    default: false,
  },
  isModification: {
    type: Boolean,
    default: false,
  },
  location: {
    type: Object,
    default: null,
  },
  errors: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits([
  "close",
  "location-created",
  "location-modified",
  "clear-errors",
]);

const formData = reactive({
  name: "",
  location_type: "office",
  address_line1: "",
  address_line2: "",
  postal_code: "",
  city: "",
  country_code: "FR",
  phone: "",
  email: "",
  gps_lat: null,
  gps_lng: null,
  is_default: false,
  client_id: props.clientId,
});

// Computed properties
const showAddressWarning = computed(() => {
  return !formData.address_line1 && !formData.postal_code && !formData.city;
});

const generalError = computed(() => {
  return props.errors.general || props.errors.client_id;
});

const isFormValid = computed(() => {
  return !showAddressWarning.value;
});

// Watchers
watch(
  () => props.clientId,
  (newVal) => {
    formData.client_id = newVal;
  }
);

watch(
  () => props.location,
  (newLocation) => {
    if (newLocation && props.isModification) {
      // Populate form with location data for modification
      formData.name = newLocation.name || "";
      formData.location_type = newLocation.location_type || "office";
      formData.address_line1 = newLocation.address?.line1 || "";
      formData.address_line2 = newLocation.address?.line2 || "";
      formData.postal_code = newLocation.address?.postal_code || "";
      formData.city = newLocation.address?.city || "";
      formData.country_code = newLocation.address?.country_code || "FR";
      formData.phone = newLocation.phone || "";
      formData.email = newLocation.email || "";
      formData.gps_lat = newLocation.gps_lat || null;
      formData.gps_lng = newLocation.gps_lng || null;
      formData.is_default = newLocation.is_default || false;
    }
  },
  { immediate: true }
);

watch(
  () => props.isVisible,
  (newVal) => {
    if (newVal) {
      emit("clear-errors");
      if (!props.isModification) {
        resetForm();
      }
    }
  }
);

// Methods
const resetForm = () => {
  Object.assign(formData, {
    name: "",
    location_type: "office",
    address_line1: "",
    address_line2: "",
    postal_code: "",
    city: "",
    country_code: "FR",
    phone: "",
    email: "",
    gps_lat: null,
    gps_lng: null,
    is_default: false,
    client_id: props.clientId,
  });
};

const closeModal = () => {
  resetForm();
  emit("close");
};

const handleSubmit = async () => {
  if (!isFormValid.value) {
    return;
  }

  // Validate GPS coordinates if provided
  if (formData.gps_lat !== null) {
    const lat = parseFloat(formData.gps_lat);
    if (isNaN(lat) || lat < -90 || lat > 90) {
      emit("clear-errors");
      emit(props.isModification ? "location-modified" : "location-created", {
        ...formData,
        errors: { gps_lat: "La latitude doit être comprise entre -90 et 90." },
      });
      return;
    }
  }

  if (formData.gps_lng !== null) {
    const lng = parseFloat(formData.gps_lng);
    if (isNaN(lng) || lng < -180 || lng > 180) {
      emit("clear-errors");
      emit(props.isModification ? "location-modified" : "location-created", {
        ...formData,
        errors: {
          gps_lng: "La longitude doit être comprise entre -180 et 180.",
        },
      });
      return;
    }
  }

  // Validate country code if provided
  if (formData.country_code && formData.country_code.length !== 2) {
    emit("clear-errors");
    emit(props.isModification ? "location-modified" : "location-created", {
      ...formData,
      errors: {
        country_code: "Le code pays doit contenir exactement 2 caractères.",
      },
    });
    return;
  }

  // Clean up data before sending
  const submitData = {
    ...formData,
    gps_lat: formData.gps_lat || null,
    gps_lng: formData.gps_lng || null,
    name: formData.name || null,
    address_line1: formData.address_line1 || null,
    address_line2: formData.address_line2 || null,
    postal_code: formData.postal_code || null,
    city: formData.city || null,
    country_code: formData.country_code || "FR",
  };

  if (props.isModification && props.location) {
    submitData.id = props.location.id;
    emit("location-modified", submitData);
  } else {
    emit("location-created", submitData);
  }
};

// Keyboard event listener for ESC key
const handleKeydown = (event) => {
  if (event.key === "Escape" && props.isVisible) {
    closeModal();
  }
};

// Add event listener when component is mounted
onMounted(() => {
  document.addEventListener("keydown", handleKeydown);
});
onUnmounted(() => {
  document.removeEventListener("keydown", handleKeydown);
});
</script>

<style scoped>
.modal {
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  border: none;
  border-radius: 0.5rem;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}

.modal-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  border-top-left-radius: 0.5rem;
  border-top-right-radius: 0.5rem;
}

.modal-title {
  color: #495057;
  font-weight: 600;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  border-top: 1px solid #e9ecef;
  background-color: #f8f9fa;
  border-bottom-left-radius: 0.5rem;
  border-bottom-right-radius: 0.5rem;
}

.form-label {
  font-weight: 500;
  color: #495057;
  margin-bottom: 0.5rem;
}

.form-control,
.form-select {
  border: 1px solid #dce1e6;
  border-radius: 0.375rem;
  padding: 0.5rem 0.75rem;
  transition: all 0.2s ease;
}

.form-control:focus,
.form-select:focus {
  border-color: #cb0c9f;
  box-shadow: 0 0 0 0.2rem rgba(203, 12, 159, 0.25);
}

.btn-primary {
  background-color: #cb0c9f;
  border-color: #cb0c9f;
  border-radius: 0.375rem;
}

.btn-primary:hover:not(:disabled) {
  background-color: #a90982;
  border-color: #a90982;
  transform: translateY(-1px);
}

.btn-outline-secondary {
  border-radius: 0.375rem;
}

.invalid-feedback {
  font-size: 0.875rem;
}

.alert {
  border: none;
  border-radius: 0.375rem;
  padding: 0.75rem 1rem;
}

.fade {
  transition: opacity 0.15s linear;
}

.modal-backdrop {
  opacity: 0.5;
}

.form-text {
  font-size: 0.75rem;
}

.btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>
