<template>
  <div class="px-3" style="background-color: #f3f6f9;">
    <!-- Loading -->
    <div v-if="loading" class="text-center py-5">
      <span class="spinner-border spinner-border-sm"></span> Đang tải dữ liệu...
    </div>

    <template v-if="!loading && premise">
      <!-- Status Bar -->
      <div class="row row-sm mb-3 mt-3">
        <div class="col-lg-12">
          <div class="card shadow-none mb-0">
            <div class="card-body py-3">
              <div class="d-flex flex-wrap align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-3">
                  <h5 class="mb-0">
                    <span class="badge bg-dark me-2">{{ premise.Code }}</span>
                    <span :class="['badge', getStatusBadge(premise.Status)]">
                      {{ getStatusText(premise.Status) }}
                    </span>
                  </h5>
                  <span v-if="premise.TotalScore" class="badge bg-warning text-dark">
                    <i class="fas fa-star me-1"></i>{{ premise.TotalScore }} điểm
                  </span>
                </div>
                <div class="d-flex gap-2 mt-2 mt-md-0">
                  <!-- Status change buttons based on current status -->
                  <template v-if="premise.Status === 1">
                    <button class="btn btn-sm btn-primary" @click="changeStatus(2)" :disabled="changingStatus">
                      <i class="fas fa-arrow-right me-1"></i>Hoàn thành khảo sát
                    </button>
                  </template>
                  <template v-if="premise.Status === 2">
                    <button class="btn btn-sm btn-success" @click="changeStatus(3)" :disabled="changingStatus">
                      <i class="fas fa-check me-1"></i>Duyệt → Đàm phán
                    </button>
                    <button class="btn btn-sm btn-danger" @click="changeStatus(6)" :disabled="changingStatus">
                      <i class="fas fa-times me-1"></i>Từ chối
                    </button>
                  </template>
                  <template v-if="premise.Status === 3">
                    <button class="btn btn-sm btn-success" @click="changeStatus(4)" :disabled="changingStatus">
                      <i class="fas fa-check-double me-1"></i>Phê duyệt
                    </button>
                  </template>
                  <template v-if="premise.Status === 4">
                    <button class="btn btn-sm btn-success" @click="changeStatus(5)" :disabled="changingStatus">
                      <i class="fas fa-handshake me-1"></i>Đã thuê
                    </button>
                  </template>
                  <button class="btn btn-sm btn-outline-primary" @click="editPremise">
                    <i class="fe fe-edit-2 me-1"></i>Sửa
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="row row-sm">
        <!-- Left Column: Info -->
        <div class="col-lg-8">
          <!-- Thông tin cơ bản + Ảnh cùng hàng -->
          <div class="card shadow-none mb-3">
            <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">
                <!-- Thông tin: col-9 -->
                <div class="col-9">
                  <div class="row">
                    <div class="col-md-6 mb-2">
                      <strong class="text-muted">Bưu cục:</strong>
                      <div>{{ premise.AgencyName || '—' }}</div>
                    </div>
                    <div class="col-md-6 mb-2">
                      <strong class="text-muted">Khu vực:</strong>
                      <div>
                        <span v-if="premise.CityName">{{ premise.CityName }}</span>
                        <span v-if="premise.DistrictName"> - {{ premise.DistrictName }}</span>
                        <span v-if="premise.WardName"> - {{ premise.WardName }}</span>
                        <span v-if="!premise.CityName && !premise.DistrictName && !premise.WardName">—</span>
                      </div>
                    </div>
                    <div class="col-md-12 mb-2">
                      <strong class="text-muted">Địa chỉ:</strong>
                      <div>{{ premise.AddressDetail }}</div>
                    </div>
                    <div class="col-md-6 mb-2" v-if="premise.Latitude">
                      <strong class="text-muted">Tọa độ:</strong>
                      <div>{{ premise.Latitude }}, {{ premise.Longitude }}</div>
                    </div>
                    <div class="col-md-6 mb-2" v-if="premise.GoogleMapUrl">
                      <strong class="text-muted">Google Maps:</strong>
                      <div><a :href="premise.GoogleMapUrl" target="_blank" class="text-primary">Xem bản đồ <i class="fas fa-external-link-alt"></i></a></div>
                    </div>
                    <div class="col-md-12 mb-2" v-if="premise.Description">
                      <strong class="text-muted">Mô tả:</strong>
                      <div>{{ premise.Description }}</div>
                    </div>
                    <div class="col-md-12 mb-2">
                      <strong class="text-muted">Người tạo:</strong>
                      <div>{{ premise.CreatedByUserName }} — {{ formatDateTime(premise.CreatedTime) }}</div>
                    </div>
                  </div>
                </div>

                <!-- Ảnh mặt bằng: col-3 -->
                <div class="col-3">
                  <small class="text-muted d-block mb-2"><i class="fas fa-images me-1"></i>Ảnh mặt bằng</small>
                  <div v-if="!premise.Medias || premise.Medias.length === 0" class="text-center text-muted py-3 border rounded" style="font-size:0.8rem">
                    Chưa có ảnh
                  </div>
                  <div v-else class="row g-1">
                    <div v-for="media in premise.Medias" :key="media.Id" class="col-6">
                      <div class="position-relative border rounded overflow-hidden" style="aspect-ratio:1">
                        <img :src="media.Url" class="w-100 h-100" style="object-fit:cover" :alt="getMediaTypeName(media.MediaType)">
                        <div class="position-absolute top-0 start-0 w-100">
                          <span class="badge bg-dark opacity-75" style="font-size:0.55rem;border-radius:0">{{ getMediaTypeName(media.MediaType) }}</span>
                        </div>
                        <button
                          type="button"
                          class="btn btn-danger btn-sm position-absolute top-0 end-0 p-0 d-flex align-items-center justify-content-center"
                          style="width:18px;height:18px;border-radius:0 0 0 4px;top:0!important;right:0!important"
                          :disabled="deletingMediaId === media.Id"
                          @click="deleteMedia(media.Id)"
                          title="Xóa ảnh"
                        >
                          <span v-if="deletingMediaId === media.Id" class="spinner-border spinner-border-sm" style="width:8px;height:8px"></span>
                          <i v-else class="fe fe-x" style="font-size:10px"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-6 mb-3">
              <!-- Liên hệ -->
              <div class="card shadow-none h-100 mb-0">
            <div class="card-header">
              <h5 class="card-title mb-0"><i class="fas fa-address-book me-2"></i>Liên hệ</h5>
            </div>
            <div class="card-body p-0">
              <div v-if="!premise.Contacts || premise.Contacts.length === 0" class="text-center text-muted py-3">
                Chưa có thông tin liên hệ
              </div>
              <table v-else class="table table-sm mb-0">
                <thead class="table-light">
                  <tr>
                    <th>Họ tên</th>
                    <th>Số điện thoại</th>
                    <th>Vai trò</th>
                    <th>Ghi chú</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="c in premise.Contacts" :key="c.Id">
                    <td><strong>{{ c.FullName }}</strong></td>
                    <td>
                      <a :href="'tel:' + c.PhoneNumber">{{ c.PhoneNumber }}</a>
                    </td>
                    <td>
                      <span :class="['badge', getContactRoleBadge(c.Role)]">
                        {{ getContactRoleText(c.Role) }}
                      </span>
                    </td>
                    <td>{{ c.Note || '—' }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
              </div>
            </div>

            <div class="col-lg-6 mb-3">
              <!-- Bảng 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>Bảng chấm điểm</h5>
            </div>
            <div class="card-body p-0">
              <div v-if="!premise.Scores || premise.Scores.length === 0" class="text-center text-muted py-3">
                Chưa có điểm chấm
              </div>
              <table v-else class="table table-sm mb-0">
                <thead class="table-light">
                  <tr>
                    <th>Tiêu chí</th>
                    <th>Loại</th>
                    <th>Lựa chọn / Giá trị</th>
                    <th class="text-end">Điểm</th>
                    <th>Ghi chú</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="s in premise.Scores" :key="s.Id">
                    <td><strong>{{ s.CriteriaName }}</strong></td>
                    <td>
                      <span :class="['badge', s.CriteriaType === 1 ? 'bg-info' : 'bg-warning']">
                        {{ s.CriteriaType === 1 ? 'Option' : 'Range' }}
                      </span>
                    </td>
                    <td>
                      <span v-if="s.SelectedOptionLabel">{{ s.SelectedOptionLabel }}</span>
                      <span v-else-if="s.NumericValue !== null">{{ s.NumericValue }}</span>
                      <span v-else class="text-muted">—</span>
                    </td>
                    <td class="text-end">
                      <strong class="text-success">{{ s.Score }}</strong>
                    </td>
                    <td>{{ s.Note || '—' }}</td>
                  </tr>
                  <tr class="table-dark">
                    <td colspan="3"><strong>Tổng điểm</strong></td>
                    <td class="text-end"><strong>{{ premise.TotalScore }}</strong></td>
                    <td></td>
                  </tr>
                </tbody>
              </table>
            </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Right Column: Financial -->
        <div class="col-lg-4">
          <div class="card shadow-none mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="card-title mb-0"><i class="fas fa-money-bill-wave me-2"></i>Tài chính</h5>
              <button
                v-if="premise.Status >= 3"
                class="btn btn-sm btn-outline-primary"
                @click="toggleFinancialEdit"
              >
                <i :class="['fe', editingFinancial ? 'fe-x' : 'fe-edit-2']"></i>
              </button>
            </div>
            <div class="card-body">
              <template v-if="!editingFinancial">
                <!-- Read-only financial info -->
                <div v-if="premise.Financial">
                  <div class="mb-2">
                    <small class="text-muted">Giá thuê yêu cầu</small>
                    <div class="fw-bold">{{ formatCurrency(premise.Financial.AskingRent) }}</div>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">Giá thuê thỏa thuận</small>
                    <div class="fw-bold text-success">{{ formatCurrency(premise.Financial.NegotiatedRent) }}</div>
                  </div>
                  <hr>
                  <div class="mb-2">
                    <small class="text-muted">Đặt cọc</small>
                    <div>{{ premise.Financial.DepositMonths }} tháng</div>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">Kỳ thanh toán</small>
                    <div>{{ premise.Financial.PaymentPeriodMonths }} tháng</div>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">Ngày miễn phí setup</small>
                    <div>{{ premise.Financial.FreeFitOutDays }} ngày</div>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">Có thể nhận từ</small>
                    <div>{{ formatDate(premise.Financial.AvailableFromDate) || '—' }}</div>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">Xuất hóa đơn VAT</small>
                    <div>
                      <span :class="['badge', premise.Financial.CanProvideVatInvoice ? 'bg-success' : 'bg-secondary']">
                        {{ premise.Financial.CanProvideVatInvoice ? 'Có' : 'Không' }}
                      </span>
                    </div>
                  </div>
                  <div v-if="premise.Financial.LegalNote" class="mb-2">
                    <small class="text-muted">Ghi chú pháp lý</small>
                    <div>{{ premise.Financial.LegalNote }}</div>
                  </div>
                </div>
                <div v-else class="text-center text-muted py-3">
                  <p>Chưa có thông tin tài chính</p>
                  <button v-if="premise.Status >= 3" class="btn btn-sm btn-primary" @click="toggleFinancialEdit">
                    <i class="fe fe-plus me-1"></i>Thêm thông tin
                  </button>
                </div>
              </template>

              <!-- Editable financial form -->
              <template v-else>
                <div class="mb-2">
                  <label class="form-label">Giá thuê yêu cầu</label>
                  <input type="number" class="form-control form-control-sm" v-model.number="financialForm.AskingRent">
                </div>
                <div class="mb-2">
                  <label class="form-label">Giá thuê thỏa thuận</label>
                  <input type="number" class="form-control form-control-sm" v-model.number="financialForm.NegotiatedRent">
                </div>
                <div class="mb-2">
                  <label class="form-label">Số tháng đặt cọc</label>
                  <input type="number" class="form-control form-control-sm" v-model.number="financialForm.DepositMonths">
                </div>
                <div class="mb-2">
                  <label class="form-label">Kỳ thanh toán (tháng)</label>
                  <input type="number" class="form-control form-control-sm" v-model.number="financialForm.PaymentPeriodMonths">
                </div>
                <div class="mb-2">
                  <label class="form-label">Ngày miễn phí setup</label>
                  <input type="number" class="form-control form-control-sm" v-model.number="financialForm.FreeFitOutDays">
                </div>
                <div class="mb-2">
                  <label class="form-label">Ngày có thể nhận</label>
                  <input type="date" class="form-control form-control-sm" v-model="financialForm.AvailableFromDate">
                </div>
                <div class="mb-2">
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" v-model="financialForm.CanProvideVatInvoice" id="vatCheck">
                    <label class="form-check-label" for="vatCheck">Xuất hóa đơn VAT</label>
                  </div>
                </div>
                <div class="mb-3">
                  <label class="form-label">Ghi chú pháp lý</label>
                  <textarea class="form-control form-control-sm" v-model="financialForm.LegalNote" rows="2"></textarea>
                </div>
                <div class="d-flex gap-2">
                  <button class="btn btn-sm btn-secondary flex-fill" @click="toggleFinancialEdit">Hủy</button>
                  <button class="btn btn-sm btn-primary flex-fill" @click="saveFinancial" :disabled="savingFinancial">
                    <span v-if="savingFinancial" class="spinner-border spinner-border-sm me-1"></span>
                    Lưu
                  </button>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import premiseService from '@/services/premiseService';
import { useToast } from 'vue-toastification';
import moment from 'moment';

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

const emit = defineEmits(['cancel']);

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

onMounted(async () => {
  if (props.id) {
    await loadPremise(Number(props.id));
  }
});

watch(() => props.id, async (newVal) => {
  if (newVal) {
    await loadPremise(Number(newVal));
  }
});

//#region DATA
const loading = ref(false);
const changingStatus = ref(false);
const savingFinancial = ref(false);
const editingFinancial = ref(false);
const premise = ref(null);
const deletingMediaId = ref(null);

const financialForm = reactive({
  Id: 0,
  PremiseId: 0,
  AskingRent: null,
  NegotiatedRent: null,
  DepositMonths: null,
  PaymentPeriodMonths: null,
  FreeFitOutDays: null,
  AvailableFromDate: null,
  CanProvideVatInvoice: false,
  LegalNote: '',
});
//#endregion

//#region FORMATTING
function formatDateTime(value) {
  if (!value) return '';
  return moment(value).format('DD/MM/YYYY HH:mm');
}

function formatDate(value) {
  if (!value) return '';
  return moment(value).format('DD/MM/YYYY');
}

function formatCurrency(value) {
  if (value == null || value == undefined) return '—';
  return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value);
}
//#endregion

//#region HELPERS
function getStatusText(status) {
  switch (status) {
    case 1: return 'Đang khảo sát';
    case 2: return 'Chờ đánh giá';
    case 3: return 'Đang đàm phán';
    case 4: return 'Đã duyệt';
    case 5: return 'Đã thuê';
    case 6: return 'Từ chối';
    case 7: return 'Đã đóng';
    default: return `#${status}`;
  }
}

function getStatusBadge(status) {
  switch (status) {
    case 1: return 'bg-info';
    case 2: return 'bg-warning';
    case 3: return 'bg-primary';
    case 4: return 'bg-success';
    case 5: return 'bg-success';
    case 6: return 'bg-danger';
    case 7: return 'bg-secondary';
    default: return 'bg-secondary';
  }
}

function getContactRoleText(role) {
  switch (role) {
    case 1: return 'Chủ nhà';
    case 2: return 'Môi giới';
    case 3: return 'Ủy quyền';
    default: return `#${role}`;
  }
}

function getContactRoleBadge(role) {
  switch (role) {
    case 1: return 'bg-primary';
    case 2: return 'bg-info';
    case 3: return 'bg-secondary';
    default: return 'bg-light text-dark';
  }
}
//#endregion

//#region LOAD DATA
async function loadPremise(id) {
  loading.value = true;
  try {
    const result = await premiseService.getById(id);
    if (result && result.Result === 1) {
      premise.value = result;

      // Pre-populate financial form
      if (result.Financial) {
        Object.assign(financialForm, {
          Id: result.Financial.Id || 0,
          PremiseId: result.Id,
          AskingRent: result.Financial.AskingRent,
          NegotiatedRent: result.Financial.NegotiatedRent,
          DepositMonths: result.Financial.DepositMonths,
          PaymentPeriodMonths: result.Financial.PaymentPeriodMonths,
          FreeFitOutDays: result.Financial.FreeFitOutDays,
          AvailableFromDate: result.Financial.AvailableFromDate ? moment(result.Financial.AvailableFromDate).format('YYYY-MM-DD') : null,
          CanProvideVatInvoice: result.Financial.CanProvideVatInvoice,
          LegalNote: result.Financial.LegalNote || '',
        });
      } else {
        financialForm.PremiseId = result.Id;
      }
    } 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();
  } finally {
    loading.value = false;
  }
}
//#endregion

//#region STATUS CHANGE
async function changeStatus(newStatus) {
  const statusNames = {
    2: 'Chờ đánh giá',
    3: 'Đang đàm phán',
    4: 'Đã duyệt',
    5: 'Đã thuê',
    6: 'Từ chối',
  };

  if (!confirm(`Bạn có chắc muốn chuyển trạng thái sang "${statusNames[newStatus]}"?`)) {
    return;
  }

  changingStatus.value = true;
  try {
    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 || '';
    }

    const result = await premiseService.changeStatus({
      Id: premise.value.Id,
      Status: newStatus,
      UpdatedBy: updatedBy,
      UpdatedByUserName: updatedByUserName,
    });

    if (result && result.Result === 1) {
      toast.success(`Chuyển trạng thái thành công`);
      await loadPremise(premise.value.Id);
    } else {
      toast.error(result.Message || 'Không thể chuyển trạng thái');
    }
  } catch (error) {
    console.error('Error changing status:', error);
    toast.error('Có lỗi xảy ra khi chuyển trạng thái');
  } finally {
    changingStatus.value = false;
  }
}
//#endregion

//#region FINANCIAL
function toggleFinancialEdit() {
  editingFinancial.value = !editingFinancial.value;
}

async function saveFinancial() {
  savingFinancial.value = true;
  try {
    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 || '';
    }

    const model = {
      ...financialForm,
      UpdatedBy: updatedBy,
      UpdatedByUserName: updatedByUserName,
    };

    const result = await premiseService.updateFinancial(model);
    if (result && result.Result === 1) {
      toast.success('Cập nhật thông tin tài chính thành công');
      editingFinancial.value = false;
      await loadPremise(premise.value.Id);
    } else {
      toast.error(result.Message || 'Không thể cập nhật thông tin tài chính');
    }
  } catch (error) {
    console.error('Error saving financial:', error);
    toast.error('Có lỗi xảy ra khi lưu thông tin tài chính');
  } finally {
    savingFinancial.value = false;
  }
}
//#endregion

//#region MEDIA
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}`;
}

async function deleteMedia(id) {
  if (!confirm('Bạn có chắc muốn xóa ảnh này?')) return;

  deletingMediaId.value = id;
  try {
    const result = await premiseService.deleteMedia(id);
    if (result && result.Result === 1) {
      toast.success('Xóa ảnh thành công');
      // Xóa ảnh khỏi danh sách hiện tại mà không cần reload toàn bộ
      if (premise.value && premise.value.Medias) {
        premise.value.Medias = premise.value.Medias.filter(m => m.Id !== id);
      }
    } else {
      toast.error(result.Message || 'Không thể xóa ảnh');
    }
  } catch (error) {
    console.error('Error deleting media:', error);
    toast.error('Có lỗi xảy ra khi xóa ảnh');
  } finally {
    deletingMediaId.value = null;
  }
}
//#endregion

//#region NAVIGATION
function goBack() {
  emit('cancel');
}

function editPremise() {
  emit('cancel');
  setTimeout(() => {
    router.push({ name: 'premise-edit', params: { id: premise.value.Id } });
  }, 200);
}
//#endregion
</script>
