<template>
  <view class="page">
    <view class="header-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="top-bar">
        <view class="top-left" />
        <view class="top-center">
          <text class="page-title">{{ t('login.selectStore') }}</text>
          <text class="page-sub">{{ t('login.welcomeUser') }} {{ userName }}</text>
        </view>
        <view class="top-right" />
      </view>
    </view>

    <view v-if="isAdminUser" class="scope-panel">
      <view class="scope-section">
        <text class="scope-label">{{ t('login.scopeCompany') }} *</text>
        <view v-if="scopeLoading && !companies.length" class="scope-hint">
          <text class="scope-hint-text">{{ t('login.scopeLoading') }}</text>
        </view>
        <view v-else-if="!companies.length" class="scope-hint">
          <text class="scope-hint-text">{{ t('login.scopeNoCompanies') }}</text>
        </view>
        <view v-else class="scope-chips">
          <view
            v-for="c in companies"
            :key="c.id"
            class="scope-chip"
            :class="{ active: selectedPartnerId === c.id }"
            @click="onSelectCompany(c.id)"
          >
            <text class="scope-chip-text">{{ c.partnerName }}</text>
          </view>
        </view>
      </view>

      <view v-if="selectedPartnerId" class="scope-section">
        <text class="scope-label">{{ t('login.scopeRegion') }} *</text>
        <view v-if="regionsLoading" class="scope-hint">
          <text class="scope-hint-text">{{ t('login.scopeLoading') }}</text>
        </view>
        <view v-else-if="!regions.length" class="scope-hint">
          <text class="scope-hint-text">{{ t('login.scopeNoRegions') }}</text>
        </view>
        <view v-else class="scope-chips">
          <view
            v-for="r in regions"
            :key="r.id"
            class="scope-chip"
            :class="{ active: selectedGroupId === r.id }"
            @click="onSelectRegion(r.id)"
          >
            <text class="scope-chip-text">{{ r.groupName }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="list">
      <view v-if="isAdminUser && !selectedGroupId" class="empty-hint">
        <text class="empty-text">{{ t('login.selectCompanyRegionFirst') }}</text>
      </view>
      <view v-else-if="!loading && stores.length === 0" class="empty-hint">
        <text class="empty-text">{{ t('login.noStoresBound') }}</text>
      </view>
      <view
        v-for="store in stores"
        :key="store.id"
        class="card"
        :class="{ selected: selectedStore === store.id }"
        @click="selectedStore = store.id"
      >
        <view class="card-icon" :class="{ selected: selectedStore === store.id }">
          <AppIcon name="mapPin" size="md" :color="selectedStore === store.id ? 'white' : 'gray'" />
        </view>
        <view class="card-content">
          <text class="card-title">{{ store.locationName }}</text>
          <view class="info-row">
            <AppIcon name="mapPin" size="sm" color="gray" />
            <text class="info">{{ store.fullAddress }}</text>
          </view>
          <text v-if="store.locationCode" class="info muted">{{ store.locationCode }}</text>
        </view>
        <view class="card-check">
          <AppIcon
            v-if="selectedStore === store.id"
            name="check"
            size="sm"
            color="white"
          />
          <AppIcon
            v-else
            name="chevronRight"
            size="sm"
            color="gray"
          />
        </view>
      </view>
    </view>

    <view class="bottom-bar" :style="{ paddingBottom: (bottomSafeArea + 24) + 'px' }">
      <view class="bottom-actions-row">
        <view class="back-btn" @click="handleBackToLogin">
          <text class="back-btn-text">{{ t('login.backToSignIn') }}</text>
        </view>
        <view
          class="confirm-btn"
          :class="{ disabled: !canConfirm }"
          @click="handleConfirm"
        >
          <text class="confirm-btn-text">{{ loading || confirming ? '…' : t('common.confirm') }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { onShow } from '@dcloudio/uni-app'
import AppIcon from '../../components/AppIcon.vue'
import { getStatusBarHeight, getBottomSafeArea } from '../../utils/statusBar'
import {
  usAppFetchAdminScopeCompanies,
  usAppFetchAdminScopeLocations,
  usAppFetchAdminScopeRegions,
  usAppFetchMyLocations,
  usAppFetchMyProfile,
  usAppSelectAdminScopeLocation,
} from '../../services/usAppAuth'
import type { AuthScopeCompanyOption, AuthScopeRegionOption } from '../../types/usAppAdminScope'
import type { UsAppBoundLocationDto } from '../../types/usAppBound'
import { isUsAppSessionExpiredError } from '../../utils/usAppApiRequest'
import { isAppAdminUser } from '../../utils/appAdminRole'
import { setBoundLocations, getBoundLocations, clearAuthSession } from '../../utils/authSession'
import { switchStore } from '../../utils/stores'

const { t } = useI18n()
const statusBarHeight = getStatusBarHeight()
const bottomSafeArea = getBottomSafeArea()
const userName = computed(() => uni.getStorageSync('userName') || 'Employee')
const selectedStore = ref('')
const stores = ref<UsAppBoundLocationDto[]>([])
const loading = ref(false)
const confirming = ref(false)

const isAdminUser = ref(false)
const scopeLoading = ref(false)
const regionsLoading = ref(false)
const companies = ref<AuthScopeCompanyOption[]>([])
const regions = ref<AuthScopeRegionOption[]>([])
const selectedPartnerId = ref('')
const selectedGroupId = ref('')

function applyList(list: UsAppBoundLocationDto[]) {
  const enabled = list.filter((s) => s.state !== false)
  stores.value = enabled
  setBoundLocations(enabled)
}

async function refreshEmployeeStores() {
  loading.value = true
  try {
    const list = await usAppFetchMyLocations()
    applyList(list)
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    applyList(getBoundLocations())
    uni.showToast({ title: t('login.refreshStoresFail'), icon: 'none' })
  } finally {
    loading.value = false
  }
}

async function loadCompanies() {
  scopeLoading.value = true
  try {
    companies.value = await usAppFetchAdminScopeCompanies()
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    companies.value = []
    uni.showToast({ title: t('login.scopeLoadFail'), icon: 'none' })
  } finally {
    scopeLoading.value = false
  }
}

async function loadRegions(partnerId: string) {
  regionsLoading.value = true
  regions.value = []
  try {
    regions.value = await usAppFetchAdminScopeRegions(partnerId)
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    regions.value = []
    uni.showToast({ title: t('login.scopeLoadFail'), icon: 'none' })
  } finally {
    regionsLoading.value = false
  }
}

async function loadAdminLocations(partnerId: string, groupId: string) {
  loading.value = true
  selectedStore.value = ''
  try {
    const list = await usAppFetchAdminScopeLocations(partnerId, groupId)
    applyList(
      list.map((x) => ({
        id: x.id,
        locationCode: x.locationCode,
        locationName: x.locationName,
        fullAddress: x.fullAddress,
        state: x.state,
      })),
    )
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    applyList([])
    uni.showToast({ title: t('login.scopeLoadFail'), icon: 'none' })
  } finally {
    loading.value = false
  }
}

function onSelectCompany(partnerId: string) {
  const id = partnerId.trim()
  if (selectedPartnerId.value === id) return
  selectedPartnerId.value = id
  selectedGroupId.value = ''
  selectedStore.value = ''
  stores.value = []
  regions.value = []
  if (id) loadRegions(id)
}

function onSelectRegion(groupId: string) {
  const gid = groupId.trim()
  if (selectedGroupId.value === gid) return
  selectedGroupId.value = gid
  selectedStore.value = ''
  if (gid && selectedPartnerId.value) {
    loadAdminLocations(selectedPartnerId.value, gid)
  } else {
    stores.value = []
  }
}

async function initPage() {
  loading.value = true
  try {
    const profile = await usAppFetchMyProfile()
    isAdminUser.value = isAppAdminUser(profile)
    if (isAdminUser.value) {
      applyList([])
      await loadCompanies()
    } else {
      await refreshEmployeeStores()
    }
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    isAdminUser.value = false
    applyList(getBoundLocations())
    await refreshEmployeeStores()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  applyList(getBoundLocations())
  initPage()
})

onShow(() => {
  if (!isAdminUser.value) {
    applyList(getBoundLocations())
  }
})

const canConfirm = computed(() => {
  if (loading.value || confirming.value || !selectedStore.value) return false
  if (isAdminUser.value) {
    return !!(selectedPartnerId.value && selectedGroupId.value)
  }
  return stores.value.length > 0
})

const handleBackToLogin = () => {
  clearAuthSession()
  uni.redirectTo({ url: '/pages/login/login' })
}

const handleConfirm = async () => {
  if (!canConfirm.value) {
    if (!selectedStore.value) {
      uni.showToast({ title: t('login.selectStoreError'), icon: 'none' })
    } else if (isAdminUser.value && (!selectedPartnerId.value || !selectedGroupId.value)) {
      uni.showToast({ title: t('login.selectCompanyRegionFirst'), icon: 'none' })
    }
    return
  }
  const store = stores.value.find((s) => s.id === selectedStore.value)
  if (!store) return

  confirming.value = true
  try {
    if (isAdminUser.value) {
      const res = await usAppSelectAdminScopeLocation({
        partnerId: selectedPartnerId.value,
        groupId: selectedGroupId.value,
        locationId: store.id,
      })
      const loc = res.location ?? store
      setBoundLocations([loc])
      switchStore(loc.id, loc.locationName, loc.locationCode)
    } else {
      switchStore(store.id, store.locationName, store.locationCode)
    }
    uni.showToast({ title: t('login.storeSelected'), icon: 'success' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/index/index' })
    }, 400)
  } catch (e: unknown) {
    if (isUsAppSessionExpiredError(e)) return
    const msg = e instanceof Error ? e.message : String(e)
    uni.showToast({ title: msg || t('login.scopeSelectFail'), icon: 'none' })
  } finally {
    confirming.value = false
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
}

.header-hero {
  flex-shrink: 0;
  background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
  padding: 16rpx 32rpx 32rpx;
}

.top-bar {
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.top-left,
.top-right {
  width: 64rpx;
  height: 64rpx;
}

.top-center {
  flex: 1;
  text-align: center;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
  display: block;
  margin-bottom: 4rpx;
}

.page-sub {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.85);
}

.scope-panel {
  flex-shrink: 0;
  padding: 24rpx 32rpx 0;
  background: #f9fafb;
}

.scope-section {
  margin-bottom: 20rpx;
}

.scope-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #374151;
  display: block;
  margin-bottom: 12rpx;
}

.scope-hint {
  padding: 16rpx 0;
}

.scope-hint-text {
  font-size: 26rpx;
  color: #9ca3af;
}

.scope-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx 16rpx;
}

.scope-chip {
  display: inline-block;
  padding: 16rpx 28rpx;
  background: #fff;
  border-radius: 999rpx;
  border: 2rpx solid #e5e7eb;
}

.scope-chip.active {
  border-color: var(--theme-primary);
  background: var(--theme-primary-light);
}

.scope-chip-text {
  font-size: 26rpx;
  color: #111827;
}

.scope-chip.active .scope-chip-text {
  color: var(--theme-primary);
  font-weight: 600;
}

.list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 24rpx 32rpx;
  padding-bottom: 24rpx;
}

.empty-hint {
  padding: 48rpx 24rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #6b7280;
}

.card {
  padding: 32rpx;
  background: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  gap: 24rpx;
  border: 3rpx solid #e5e7eb;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.card.selected {
  border-color: var(--theme-primary);
  background: var(--theme-primary-light);
}

.card-icon {
  width: 80rpx;
  height: 80rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.card-icon.selected {
  background: var(--theme-primary);
}

.card-content {
  flex: 1;
  min-width: 0;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 12rpx;
}

.info-row {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  margin-bottom: 6rpx;
}

.info {
  font-size: 26rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 6rpx;
}

.info.muted {
  color: #9ca3af;
  font-size: 24rpx;
}

.card-check {
  width: 44rpx;
  height: 44rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background: transparent;
}

.card.selected .card-check {
  background: var(--theme-primary);
}

.bottom-bar {
  flex-shrink: 0;
  padding: 24rpx 48rpx;
  background: #ffffff;
  border-top: 1rpx solid #e5e7eb;
}

.bottom-actions-row {
  display: flex;
  align-items: stretch;
  gap: 24rpx;
}

.back-btn {
  flex: 1;
  height: 96rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid var(--theme-primary);
  background: #ffffff;
  box-sizing: border-box;
}

.back-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--theme-primary);
  line-height: 1;
}

.bottom-actions-row .confirm-btn {
  flex: 1;
}

.confirm-btn {
  width: 100%;
  height: 96rpx;
  background: var(--theme-primary);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-btn.disabled {
  opacity: 0.5;
}

.confirm-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  line-height: 1;
}
</style>
