<template>
  <div>
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">{{ isEditMode ? 'Chỉnh sửa mặt bằng' : 'Tạo mặt bằng mới' }}</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);" @click="goBack">Mặt bằng</a></li>
          <li class="breadcrumb-item active" aria-current="page">{{ isEditMode ? 'Chỉnh sửa' : 'Tạo mới' }}</li>
        </ol>
      </div>
    </div>

    <div v-if="loading" class="row">
      <div class="col-12 text-center py-5">
        <span class="spinner-border spinner-border-sm"></span> Đang tải dữ liệu...
      </div>
    </div>

    <div v-else class="row row-sm">
      <div class="col-lg-12">
        <div class="row mb-3">
          <!-- Section 1: Thông tin mặt bằng -->
          <div class="col-lg-8">
            <div class="card shadow-none h-100 mb-0">
              <div class="card-header">
                <h5 class="card-title mb-0">
                  <i class="fas fa-info-circle me-2"></i>Thông tin mặt bằng
                </h5>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-4 mb-3">
                    <label>Mã mặt bằng <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" v-model="formData.Code" placeholder="VD: MB-HCM-001">
                  </div>
                  <div class="col-md-4 mb-3">
                    <label>Bưu cục</label>
                    <v-select
                      v-model="formData.AgencyId"
                      :options="agencies"
                      :reduce="a => a.Id"
                      label="Name"
                      placeholder="Chọn bưu cục"
                    >
                      <template #no-options>Không tìm thấy bưu cục</template>
                    </v-select>
                  </div>
                  <!-- Tỉnh/TP → Quận/Huyện → Phường/Xã -->
                  <div class="col-md-12 mb-3">
                    <CityDistrictWard
                      v-model:city-id="formData.CityId"
                      v-model:district-id="formData.DistrictId"
                      v-model:ward-id="formData.WardId"
                    />
                  </div>
                  <div class="col-md-12 mb-3">
                    <label>Địa chỉ chi tiết <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" v-model="formData.AddressDetail" placeholder="Số nhà, đường, phường, quận...">
                  </div>
                  <div class="col-md-4 mb-3">
                    <label>Vĩ độ (Latitude)</label>
                    <input type="number" class="form-control" v-model.number="formData.Latitude" step="0.000001" placeholder="VD: 10.762622">
                  </div>
                  <div class="col-md-4 mb-3">
                    <label>Kinh độ (Longitude)</label>
                    <input type="number" class="form-control" v-model.number="formData.Longitude" step="0.000001" placeholder="VD: 106.660172">
                  </div>
                  <div class="col-md-4 mb-3">
                    <label>Google Map URL</label>
                    <input type="text" class="form-control" v-model="formData.GoogleMapUrl" placeholder="https://maps.google.com/...">
                  </div>
                  <div class="col-md-12 mb-3">
                    <label>Mô tả</label>
                    <textarea class="form-control" v-model="formData.Description" rows="2" placeholder="Mô tả mặt bằng..."></textarea>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Section: Hình ảnh/Video -->
          <div class="col-lg-4">
            <div class="card shadow-none h-100 mb-0">
              <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="card-title mb-0">
                  <i class="fas fa-images me-2"></i>Hình ảnh/Video <span class="text-danger">*</span>
                </h5>
                <i class="fas fa-info-circle text-muted" style="cursor:help" title="Ảnh đầu tiên sẽ là ảnh bìa. Nhấn và giữ để di chuyển hình ảnh."></i>
              </div>
              <div class="card-body">
                <input
                  ref="mediaFileInputRef"
                  type="file"
                  class="d-none"
                  multiple
                  accept="image/*,video/*"
                  @change="onFilesSelected"
                >

                <div class="premise-media-grid">
                  <!-- Upload button -->
                  <div class="premise-media-upload-btn" @click="triggerFileInput">
                    <div class="premise-media-upload-inner">
                      <i class="fas fa-camera-retro"></i>
                      <span>Thêm ảnh</span>
                    </div>
                  </div>

                  <!-- Existing media -->
                  <div
                    v-for="(media, idx) in visibleExistingMedias"
                    :key="'existing-' + media.Id"
                    class="premise-media-item"
                    draggable="true"
                    @dragstart="onDragStart('existing', idx, $event)"
                    @dragover.prevent
                    @drop="onDrop('existing', idx, $event)"
                  >
                    <img :src="media.Url" :alt="getMediaTypeName(media.MediaType)">
                    <button
                      type="button"
                      class="premise-media-remove"
                      @click="markDeleteMedia(media.Id)"
                      title="Xóa"
                    >
                      <i class="fe fe-x"></i>
                    </button>
                    <span v-if="idx === 0 && newMediaFiles.length === 0" class="premise-media-cover-badge">Ảnh bìa</span>
                  </div>

                  <!-- New media files -->
                  <div
                    v-for="(item, idx) in newMediaFiles"
                    :key="'new-' + idx"
                    class="premise-media-item"
                    draggable="true"
                    @dragstart="onDragStart('new', idx, $event)"
                    @dragover.prevent
                    @drop="onDrop('new', idx, $event)"
                  >
                    <img :src="item.previewUrl" alt="Ảnh mới">
                    <button
                      type="button"
                      class="premise-media-remove"
                      @click="removeNewMedia(idx)"
                      title="Xóa"
                    >
                      <i class="fe fe-x"></i>
                    </button>
                    <span v-if="idx === 0 && visibleExistingMedias.length === 0" class="premise-media-cover-badge">Ảnh bìa</span>
                  </div>
                </div>

                <div v-if="deleteMediaIds.length > 0" class="mt-2">
                  <small class="text-danger"><i class="fe fe-alert-triangle me-1"></i>{{ deleteMediaIds.length }} ảnh sẽ bị xóa khi lưu</small>
                </div>
                <div class="mt-2">
                  <small class="text-muted fst-italic"><i class="fe fe-move me-1"></i>Nhấn và giữ để di chuyển hình ảnh</small>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-lg-7 mb-3">
            <!-- Section 2: Liên hệ & Tài chính -->
            <div class="card shadow-none h-100 mb-0">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">
              <i class="fas fa-address-book me-2"></i>Liên hệ & Tài chính
            </h5>
            <button type="button" class="btn btn-sm btn-outline-primary" @click="addContact">
              <i class="fe fe-plus me-1"></i>Thêm liên hệ
            </button>
          </div>
          <div class="card-body">
            <!-- Liên hệ -->
            <div v-if="formData.Contacts.length === 0" class="text-center text-muted py-3">
              Chưa có liên hệ nào. Nhấn "Thêm liên hệ" để bắt đầu.
            </div>
            <div v-for="(contact, index) in formData.Contacts" :key="index" class="border rounded p-3 mb-3">
              <div class="d-flex justify-content-between mb-2">
                <strong class="text-primary">Liên hệ #{{ index + 1 }}</strong>
                <button type="button" class="btn btn-sm btn-outline-danger" @click="removeContact(index)">
                  <i class="fe fe-trash-2"></i>
                </button>
              </div>
              <div class="row">
                <div class="col-md-4 mb-2">
                  <label>Họ tên <span class="text-danger">*</span></label>
                  <input type="text" class="form-control form-control-sm" v-model="contact.FullName" placeholder="Họ và tên">
                </div>
                <div class="col-md-3 mb-2">
                  <label>Số điện thoại <span class="text-danger">*</span></label>
                  <input type="text" class="form-control form-control-sm" v-model="contact.PhoneNumber" placeholder="0901234567">
                </div>
                <div class="col-md-2 mb-2">
                  <label>Vai trò</label>
                  <select class="form-select form-select-sm" v-model="contact.Role">
                    <option :value="1">Chủ nhà</option>
                    <option :value="2">Môi giới</option>
                    <option :value="3">Người ủy quyền</option>
                  </select>
                </div>
                <div class="col-md-3 mb-2">
                  <label>Ghi chú</label>
                  <input type="text" class="form-control form-control-sm" v-model="contact.Note" placeholder="Ghi chú">
                </div>
              </div>
            </div>

            <!-- Divider -->
            <hr class="my-3">

            <!-- Tài chính -->
            <h6 class="mb-3"><i class="fas fa-money-bill-wave me-2"></i>Thông tin tài chính</h6>
            <div class="row">
              <div class="col-md-4 mb-3">
                <label>Giá thuê yêu cầu (VNĐ)</label>
                <input type="number" class="form-control" v-model.number="formData.Financial.AskingRent" placeholder="VD: 8000000">
              </div>
              <div class="col-md-4 mb-3">
                <label>Giá thuê thỏa thuận (VNĐ)</label>
                <input type="number" class="form-control" v-model.number="formData.Financial.NegotiatedRent" placeholder="VD: 7000000">
              </div>
              <div class="col-md-4 mb-3">
                <label>Số tháng đặt cọc</label>
                <input type="number" class="form-control" v-model.number="formData.Financial.DepositMonths" placeholder="VD: 3">
              </div>
              <div class="col-md-4 mb-3">
                <label>Kỳ thanh toán (tháng)</label>
                <input type="number" class="form-control" v-model.number="formData.Financial.PaymentPeriodMonths" placeholder="VD: 6">
              </div>
              <div class="col-md-4 mb-3">
                <label>Ngày miễn phí setup</label>
                <input type="number" class="form-control" v-model.number="formData.Financial.FreeFitOutDays" placeholder="VD: 30">
              </div>
              <div class="col-md-4 mb-3">
                <label>Ngày có thể nhận MB</label>
                <input type="date" class="form-control" v-model="formData.Financial.AvailableFromDate">
              </div>
              <div class="col-md-4 mb-3 d-flex align-items-end">
                <div class="form-check">
                  <input type="checkbox" class="form-check-input" id="canVat" v-model="formData.Financial.CanProvideVatInvoice">
                  <label class="form-check-label" for="canVat">Xuất hóa đơn VAT</label>
                </div>
              </div>
              <div class="col-md-12 mb-3">
                <label>Ghi chú pháp lý</label>
                <textarea class="form-control" v-model="formData.Financial.LegalNote" rows="2" placeholder="Ghi chú về hợp đồng, pháp lý..."></textarea>
              </div>
            </div>
          </div>
        </div>
          </div>

          <div class="col-lg-5 mb-3">
            <!-- Section 3: Chấm điểm -->
            <div class="card shadow-none h-100 mb-0">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fas fa-star me-2"></i>Chấm điểm mặt bằng
            </h5>
          </div>
          <div class="card-body">
            <div v-if="loadingCriteria" class="text-center py-3">
              <span class="spinner-border spinner-border-sm"></span> Đang tải tiêu chí...
            </div>
            <div v-else-if="criteriaList.length === 0" class="text-center text-muted py-3">
              Chưa có tiêu chí chấm điểm nào. Vui lòng cấu hình tiêu chí trước.
            </div>
            <div v-else>
              <div v-for="criteria in criteriaList" :key="criteria.Id" class="border rounded p-3 mb-3">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <div>
                    <strong>{{ criteria.Name }}</strong>
                    <span :class="['badge ms-2', criteria.CriteriaType === 1 ? 'bg-info' : 'bg-warning']">
                      {{ criteria.CriteriaType === 1 ? 'Option' : 'Range' }}
                    </span>
                    <div v-if="criteria.Description" class="small text-muted mt-1">{{ criteria.Description }}</div>
                  </div>
                  <div v-if="getScoreForCriteria(criteria.Id) > 0" class="text-end">
                    <span class="badge bg-success">{{ getScoreForCriteria(criteria.Id) }} điểm</span>
                  </div>
                </div>

                <!-- Type Option: Radio buttons -->
                <div v-if="criteria.CriteriaType === 1">
                  <div v-for="opt in criteria.Options" :key="opt.Id" class="form-check mb-1">
                    <input
                      class="form-check-input"
                      type="radio"
                      :name="'criteria_' + criteria.Id"
                      :value="opt.Id"
                      v-model="scoreSelections[criteria.Id].SelectedOptionId"
                      :id="'opt_' + opt.Id"
                    >
                    <label class="form-check-label" :for="'opt_' + opt.Id">
                      {{ opt.Label }}
                      <span class="text-muted ms-1">({{ opt.Score }} điểm)</span>
                    </label>
                  </div>
                </div>

                <!-- Type Range: Number input -->
                <div v-if="criteria.CriteriaType === 2">
                  <div class="row align-items-center">
                    <div class="col-md-3">
                      <label class="form-label">Giá trị</label>
                      <input
                        type="number"
                        class="form-control form-control-sm"
                        v-model.number="scoreSelections[criteria.Id].NumericValue"
                        step="0.01"
                        placeholder="Nhập giá trị"
                      >
                    </div>
                    <div class="col-md-9">
                      <label class="form-label">Khoảng tham chiếu:</label>
                      <div class="d-flex flex-wrap gap-2">
                        <span v-for="opt in criteria.Options" :key="opt.Id" class="badge bg-light text-dark">
                          {{ opt.Label }} ({{ opt.MinValue }}-{{ opt.MaxValue }}: {{ opt.Score }}đ)
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Note for this criteria -->
                <div class="mt-2">
                  <input
                    type="text"
                    class="form-control form-control-sm"
                    v-model="scoreSelections[criteria.Id].Note"
                    placeholder="Ghi chú cho tiêu chí này..."
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
          </div>
        </div>

        <!-- Action Buttons -->
        <div class="d-flex justify-content-end gap-2 mb-4">
          <button type="button" class="btn btn-secondary" @click="goBack">
            <i class="fe fe-x me-1"></i>Hủy
          </button>
          <button type="button" class="btn btn-primary" @click="onSubmit" :disabled="saving">
            <span v-if="saving" class="spinner-border spinner-border-sm me-1"></span>
            <i v-else class="fe fe-save me-1"></i>
            {{ isEditMode ? 'Cập nhật' : 'Lưu' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import premiseService from '@/services/premiseService';
import premiseScoringService from '@/services/premiseScoringService';
import agencyService from '@/services/agencyService';
import CityDistrictWard from '@/components/locations/CityDistrictWard.vue';
import { useToast } from 'vue-toastification';

const props = defineProps({
  id: {
    type: [Number, String],
    default: null
  }
});

const router = useRouter();
const route = useRoute();
const toast = useToast();

//#region DATA
const loading = ref(false);
const saving = ref(false);
const loadingCriteria = ref(false);
const isEditMode = ref(false);
const agencies = ref([]);
const criteriaList = ref([]);
const scoreSelections = reactive({}); // { criteriaId: { SelectedOptionId, NumericValue, Note } }

// Media state
const mediaFileInputRef = ref(null);
const newMediaFiles = ref([]); // [{ file, mediaType, previewUrl }]
const existingMedias = ref([]); // [{ Id, MediaType, Url }] — ảnh hiện có từ API
const deleteMediaIds = ref([]); // Danh sách Id ảnh cũ cần xóa

const formData = reactive({
  Id: 0,
  Code: '',
  AgencyId: null,
  CityId: null,
  DistrictId: null,
  WardId: null,
  AddressDetail: '',
  Latitude: null,
  Longitude: null,
  GoogleMapUrl: '',
  Description: '',
  Contacts: [],
  Financial: {
    AskingRent: null,
    NegotiatedRent: null,
    DepositMonths: null,
    PaymentPeriodMonths: null,
    FreeFitOutDays: null,
    AvailableFromDate: null,
    CanProvideVatInvoice: false,
    LegalNote: '',
  },
});
const dragState = ref({ type: null, index: null });
const visibleExistingMedias = computed(() => existingMedias.value.filter(m => !deleteMediaIds.value.includes(m.Id)));
//#endregion

//#region LIFECYCLE
onMounted(async () => {
  loading.value = true;
  await Promise.all([
    loadAgencies(),
    loadCriteria(),
  ]);

  const premiseId = props.id || route.params.id;
  if (premiseId && Number(premiseId) > 0) {
    isEditMode.value = true;
    await loadPremise(Number(premiseId));
  }
  loading.value = false;
});
//#endregion

//#region LOAD LOOKUPS
async function loadAgencies() {
  try {
    const searchModel = {
      Pagination: { PageIndex: 1, PageSize: 999 },
      Sort: { Predicate: 'Name', Reverse: false },
      Search: { PredicateObject: {} }
    };
    const result = await agencyService.search(searchModel);
    if (result && result.Items) {
      agencies.value = result.Items;
    }
  } catch (error) {
    console.error('Error loading agencies:', error);
  }
}



async function loadCriteria() {
  loadingCriteria.value = true;
  try {
    const result = await premiseScoringService.getAllActive();
    if (result && Array.isArray(result)) {
      criteriaList.value = result;
      // Init score selections
      result.forEach(c => {
        scoreSelections[c.Id] = {
          CriteriaId: c.Id,
          SelectedOptionId: null,
          NumericValue: null,
          Note: '',
        };
      });
    }
  } catch (error) {
    console.error('Error loading criteria:', error);
  } finally {
    loadingCriteria.value = false;
  }
}
//#endregion

//#region LOAD PREMISE
async function loadPremise(id) {
  try {
    const result = await premiseService.getById(id);
    if (result && result.Result === 1) {
      formData.Id = result.Id;
      formData.Code = result.Code;
      formData.AgencyId = result.AgencyId;
      formData.CityId = result.CityId || null;
      formData.DistrictId = result.DistrictId || null;
      formData.WardId = result.WardId || null;
      formData.AddressDetail = result.AddressDetail;
      formData.Latitude = result.Latitude;
      formData.Longitude = result.Longitude;
      formData.GoogleMapUrl = result.GoogleMapUrl || '';
      formData.Description = result.Description || '';

      // Load contacts
      formData.Contacts.splice(0, formData.Contacts.length);
      if (result.Contacts && result.Contacts.length > 0) {
        result.Contacts.forEach(c => {
          formData.Contacts.push({
            Id: c.Id,
            FullName: c.FullName,
            PhoneNumber: c.PhoneNumber,
            Role: c.Role,
            Note: c.Note || '',
          });
        });
      }

      // Load scores
      if (result.Scores && result.Scores.length > 0) {
        result.Scores.forEach(s => {
          if (scoreSelections[s.CriteriaId]) {
            scoreSelections[s.CriteriaId].SelectedOptionId = s.SelectedOptionId;
            scoreSelections[s.CriteriaId].NumericValue = s.NumericValue;
            scoreSelections[s.CriteriaId].Note = s.Note || '';
          }
        });
      }

      // Load medias
      existingMedias.value = result.Medias || [];
      deleteMediaIds.value = [];
      newMediaFiles.value = [];

      // Load financial
      if (result.Financial) {
        formData.Financial.AskingRent = result.Financial.AskingRent;
        formData.Financial.NegotiatedRent = result.Financial.NegotiatedRent;
        formData.Financial.DepositMonths = result.Financial.DepositMonths;
        formData.Financial.PaymentPeriodMonths = result.Financial.PaymentPeriodMonths;
        formData.Financial.FreeFitOutDays = result.Financial.FreeFitOutDays;
        formData.Financial.AvailableFromDate = result.Financial.AvailableFromDate ? result.Financial.AvailableFromDate.substring(0, 10) : null;
        formData.Financial.CanProvideVatInvoice = result.Financial.CanProvideVatInvoice || false;
        formData.Financial.LegalNote = result.Financial.LegalNote || '';
      }
    } else {
      toast.error('Không tìm thấy mặt bằng');
      goBack();
    }
  } catch (error) {
    console.error('Error loading premise:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu');
    goBack();
  }
}
//#endregion

//#region CONTACTS
function addContact() {
  formData.Contacts.push({
    Id: 0,
    FullName: '',
    PhoneNumber: '',
    Role: 1,
    Note: '',
  });
}

function removeContact(index) {
  formData.Contacts.splice(index, 1);
}
//#endregion

//#region MEDIA HELPERS
function triggerFileInput() {
  mediaFileInputRef.value.value = '';
  mediaFileInputRef.value.click();
}

function onFilesSelected(event) {
  const files = Array.from(event.target.files);
  files.forEach(file => {
    const previewUrl = URL.createObjectURL(file);
    newMediaFiles.value.push({ file, mediaType: 1, previewUrl });
  });
}

function removeNewMedia(index) {
  const item = newMediaFiles.value[index];
  if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
  newMediaFiles.value.splice(index, 1);
}

function markDeleteMedia(id) {
  if (!deleteMediaIds.value.includes(id)) {
    deleteMediaIds.value.push(id);
  }
}

function getMediaTypeName(type) {
  const map = { 1: 'Mặt tiền', 2: 'Bên trong', 3: 'Đường', 4: 'Video', 5: 'Pháp lý' };
  return map[type] || `Loại ${type}`;
}
function onDragStart(type, index, event) {
  dragState.value = { type, index };
  event.dataTransfer.effectAllowed = 'move';
}

function onDrop(targetType, targetIndex) {
  const src = dragState.value;
  if (!src || src.type === null) return;

  // Only allow reordering within same list
  if (src.type === targetType) {
    const list = src.type === 'new' ? newMediaFiles.value : existingMedias.value;
    if (src.index !== targetIndex) {
      const [moved] = list.splice(src.index, 1);
      list.splice(targetIndex, 0, moved);
    }
  }
  dragState.value = { type: null, index: null };
}
//#endregion

//#region SCORING HELPERS
function getScoreForCriteria(criteriaId) {
  const sel = scoreSelections[criteriaId];
  if (!sel) return 0;

  const criteria = criteriaList.value.find(c => c.Id === criteriaId);
  if (!criteria) return 0;

  if (criteria.CriteriaType === 1 && sel.SelectedOptionId) {
    const opt = criteria.Options.find(o => o.Id === sel.SelectedOptionId);
    return opt ? opt.Score : 0;
  }

  if (criteria.CriteriaType === 2 && sel.NumericValue !== null) {
    const opt = criteria.Options.find(o =>
      sel.NumericValue >= o.MinValue && sel.NumericValue <= o.MaxValue
    );
    return opt ? opt.Score : 0;
  }

  return 0;
}
//#endregion

//#region SUBMIT
async function onSubmit() {
  // Validate required fields
  if (!formData.Code || !formData.Code.trim()) {
    toast.error('Vui lòng nhập mã mặt bằng');
    return;
  }
  if (!formData.AddressDetail || !formData.AddressDetail.trim()) {
    toast.error('Vui lòng nhập địa chỉ chi tiết');
    return;
  }

  // Validate contacts
  for (let i = 0; i < formData.Contacts.length; i++) {
    const c = formData.Contacts[i];
    if (!c.FullName || !c.FullName.trim()) {
      toast.error(`Liên hệ #${i + 1}: Vui lòng nhập họ tên`);
      return;
    }
    if (!c.PhoneNumber || !c.PhoneNumber.trim()) {
      toast.error(`Liên hệ #${i + 1}: Vui lòng nhập số điện thoại`);
      return;
    }
  }

  saving.value = true;
  try {
    // Build scores array from selections
    const scores = [];
    for (const criteriaId in scoreSelections) {
      const sel = scoreSelections[criteriaId];
      if (sel.SelectedOptionId || sel.NumericValue !== null) {
        scores.push({
          CriteriaId: Number(criteriaId),
          SelectedOptionId: sel.SelectedOptionId || null,
          NumericValue: sel.NumericValue,
          Note: sel.Note || null,
        });
      }
    }

    // Get user info
    let updatedBy = 0;
    let updatedByUserName = '';
    if (localStorage.user) {
      const curUser = JSON.parse(localStorage.user);
      updatedBy = curUser.UserId || curUser.Id || 0;
      updatedByUserName = curUser.UserName || curUser.FullName || '';
    }

    // Build FormData (multipart/form-data)
    const fd = new FormData();
    fd.append('Id', formData.Id);
    fd.append('Code', formData.Code || '');
    if (formData.AgencyId != null) fd.append('AgencyId', formData.AgencyId);
    if (formData.CityId != null) fd.append('CityId', formData.CityId);
    if (formData.DistrictId != null) fd.append('DistrictId', formData.DistrictId);
    if (formData.WardId != null) fd.append('WardId', formData.WardId);
    fd.append('AddressDetail', formData.AddressDetail || '');
    if (formData.Latitude != null) fd.append('Latitude', formData.Latitude);
    if (formData.Longitude != null) fd.append('Longitude', formData.Longitude);
    fd.append('GoogleMapUrl', formData.GoogleMapUrl || '');
    fd.append('Description', formData.Description || '');
    fd.append('UpdatedBy', updatedBy);
    fd.append('UpdatedByUserName', updatedByUserName);

    // Contacts
    formData.Contacts.forEach((c, i) => {
      fd.append(`Contacts[${i}].Id`, c.Id || 0);
      fd.append(`Contacts[${i}].FullName`, c.FullName);
      fd.append(`Contacts[${i}].PhoneNumber`, c.PhoneNumber);
      fd.append(`Contacts[${i}].Role`, c.Role);
      if (c.Note) fd.append(`Contacts[${i}].Note`, c.Note);
    });

    // Scores
    scores.forEach((s, i) => {
      fd.append(`Scores[${i}].CriteriaId`, s.CriteriaId);
      if (s.SelectedOptionId != null) fd.append(`Scores[${i}].SelectedOptionId`, s.SelectedOptionId);
      if (s.NumericValue != null) fd.append(`Scores[${i}].NumericValue`, s.NumericValue);
      if (s.Note) fd.append(`Scores[${i}].Note`, s.Note);
    });

    // New media files
    newMediaFiles.value.forEach(item => {
      fd.append('NewMediaFiles', item.file);
      fd.append('NewMediaTypes', item.mediaType);
    });

    // Delete existing media IDs
    deleteMediaIds.value.forEach(id => {
      fd.append('DeleteMediaIds', id);
    });

    // Financial (optional)
    const fin = formData.Financial;
    if (fin.AskingRent != null) fd.append('Financial.AskingRent', fin.AskingRent);
    if (fin.NegotiatedRent != null) fd.append('Financial.NegotiatedRent', fin.NegotiatedRent);
    if (fin.DepositMonths != null) fd.append('Financial.DepositMonths', fin.DepositMonths);
    if (fin.PaymentPeriodMonths != null) fd.append('Financial.PaymentPeriodMonths', fin.PaymentPeriodMonths);
    if (fin.FreeFitOutDays != null) fd.append('Financial.FreeFitOutDays', fin.FreeFitOutDays);
    if (fin.AvailableFromDate) fd.append('Financial.AvailableFromDate', fin.AvailableFromDate);
    fd.append('Financial.CanProvideVatInvoice', fin.CanProvideVatInvoice);
    if (fin.LegalNote) fd.append('Financial.LegalNote', fin.LegalNote);

    const result = await premiseService.createOrUpdate(fd);
    if (result && result.Result === 1) {
      toast.success(isEditMode.value ? 'Cập nhật mặt bằng thành công' : 'Tạo mặt bằng thành công');
      goBack();
    } else {
      toast.error(result.Message || 'Không thể lưu mặt bằng');
    }
  } catch (error) {
    console.error('Error saving premise:', error);
    toast.error('Có lỗi xảy ra khi lưu mặt bằng');
  } finally {
    saving.value = false;
  }
}
//#endregion

//#region NAVIGATION
function goBack() {
  router.push({ name: 'premise-list' });
}
//#endregion
</script>

<style scoped>
.premise-media-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.premise-media-upload-btn {
  width: 110px;
  height: 110px;
  border: 2px dashed #e5a800;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #fffbea;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.premise-media-upload-btn:hover {
  border-color: #d49a00;
  background: #fff3c4;
  transform: scale(1.03);
}

.premise-media-upload-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  color: #e5a800;
  font-size: 0.8rem;
  font-weight: 600;
}

.premise-media-upload-inner i {
  font-size: 1.5rem;
}

.premise-media-item {
  width: 110px;
  height: 110px;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
  cursor: grab;
  flex-shrink: 0;
  border: 2px solid transparent;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.premise-media-item:hover {
  border-color: #e5a800;
  box-shadow: 0 2px 8px rgba(0,0,0,0.12);
}

.premise-media-item:active {
  cursor: grabbing;
}

.premise-media-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.premise-media-remove {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: none;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  padding: 0;
  transition: background 0.2s;
  z-index: 2;
}

.premise-media-remove:hover {
  background: rgba(220, 53, 69, 0.9);
}

.premise-media-cover-badge {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.55);
  color: #fff;
  font-size: 0.7rem;
  font-weight: 600;
  text-align: center;
  padding: 3px 0;
  z-index: 2;
}
</style>
