<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAdminLocale } from '../../composables/useAdminLocale';
import { resolveFormError } from '../../i18n/form-validation';
import api from '../../api';
import AdminSubNav from '../../components/AdminSubNav.vue';
import CountryFlagSelect from '../../components/outright/CountryFlagSelect.vue';
import LogoUrlField from '../../components/LogoUrlField.vue';
import LeagueMatchesPanel from './LeagueMatchesPanel.vue';
import { getBuiltinCountry } from '../../data/builtinCountries';
import {
  emptyMatchForm,
  buildPlatformPayload,
  fillBuiltinTeam,
  clearBuiltinTeam,
  type MatchCreateForm,
} from '../match-form';

defineOptions({ name: 'AdminLeagueMatches' });

const route = useRoute();
const { t } = useAdminLocale();

const leagueId = computed(() => String(route.params.leagueId ?? ''));
const filterStatus = computed(() => String(route.query.status ?? ''));
const filterKeyword = computed(() => String(route.query.keyword ?? ''));
const leagueTitle = computed(() => {
  const title = String(route.query.title ?? '').trim();
  return title || `#${leagueId.value}`;
});

const panelRef = ref<{ reload: () => void } | null>(null);
const createVisible = ref(false);
const createLoading = ref(false);
const form = ref<MatchCreateForm>(emptyMatchForm());

function openCreateFixture() {
  form.value = emptyMatchForm();
  form.value.leagueId = leagueId.value;
  createVisible.value = true;
}

function onTeamCodeChange(side: 'home' | 'away', code: string) {
  if (!code?.trim()) {
    clearBuiltinTeam(form.value, side);
    return;
  }
  const country = getBuiltinCountry(code);
  if (country) fillBuiltinTeam(form.value, side, country);
}

async function submitCreate() {
  let payload: ReturnType<typeof buildPlatformPayload>;
  try {
    payload = buildPlatformPayload(form.value);
  } catch (e) {
    ElMessage.warning(resolveFormError(e, t));
    return;
  }
  createLoading.value = true;
  try {
    await api.post('/admin/matches', payload);
    ElMessage.success(t('msg.match_created_draft'));
    createVisible.value = false;
    panelRef.value?.reload();
  } catch (e: unknown) {
    const err = e as { response?: { data?: { error?: string } } };
    ElMessage.error(err.response?.data?.error ?? t('msg.create_failed'));
  } finally {
    createLoading.value = false;
  }
}

watch(leagueId, () => {
  form.value.leagueId = leagueId.value;
}, { immediate: true });
</script>

<template>
  <div class="admin-list-page league-matches-page">
    <AdminSubNav
      :title="leagueTitle"
      :subtitle="t('match.league_fixtures_subtitle')"
    >
      <template #extra>
        <el-button type="primary" @click="openCreateFixture">
          {{ t('match.create_fixture_btn') }}
        </el-button>
      </template>
    </AdminSubNav>

    <section class="list-panel">
      <LeagueMatchesPanel
        ref="panelRef"
        :league-id="leagueId"
        :filter-status="filterStatus"
        :keyword="filterKeyword"
      />
    </section>

    <el-dialog
      v-model="createVisible"
      :title="t('match.dialog.create_fixture')"
      width="860px"
      destroy-on-close
    >
      <el-form label-width="96px">
        <el-form-item :label="t('match.col.league')">
          <span class="league-readonly">{{ leagueTitle }}</span>
        </el-form-item>
        <el-form-item :label="t('match.field.kickoff')" required>
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :placeholder="t('matchEditor.ph.kickoff')"
            style="width: 100%"
          />
          <p class="field-hint schedule-timezone-hint">{{ t('match.timezone.platform_hint') }}</p>
        </el-form-item>
        <div class="teams-row">
          <div class="team-col">
            <div class="team-col-title">{{ t('match.field.home_team') }}</div>
            <el-form-item :label="t('match.field.home_team')" required>
              <CountryFlagSelect
                v-model="form.homeTeamCode"
                size="default"
                class="team-country-select"
                @update:model-value="onTeamCodeChange('home', $event)"
              />
            </el-form-item>
            <el-form-item :label="t('match.field.home_en')" label-width="108px">
              <el-input v-model="form.homeTeamEn" :placeholder="t('match.ph.home_en')" />
            </el-form-item>
            <el-form-item :label="t('match.field.home_zh')" label-width="108px">
              <el-input v-model="form.homeTeamZh" :placeholder="t('match.ph.home_zh')" />
            </el-form-item>
            <el-form-item :label="t('match.field.home_ms')" label-width="108px">
              <el-input v-model="form.homeTeamMs" :placeholder="t('match.ph.home_ms')" />
            </el-form-item>
            <el-form-item :label="t('matchEditor.field.home_logo')" label-width="108px">
              <LogoUrlField v-model="form.homeTeamLogoUrl" :team-code="form.homeTeamCode" upload-category="teams" />
            </el-form-item>
          </div>
          <div class="team-col">
            <div class="team-col-title">{{ t('match.field.away_team') }}</div>
            <el-form-item :label="t('match.field.away_team')" required>
              <CountryFlagSelect
                v-model="form.awayTeamCode"
                size="default"
                class="team-country-select"
                @update:model-value="onTeamCodeChange('away', $event)"
              />
            </el-form-item>
            <el-form-item :label="t('match.field.away_en')" label-width="108px">
              <el-input v-model="form.awayTeamEn" :placeholder="t('match.ph.away_en')" />
            </el-form-item>
            <el-form-item :label="t('match.field.away_zh')" label-width="108px">
              <el-input v-model="form.awayTeamZh" :placeholder="t('match.ph.away_zh')" />
            </el-form-item>
            <el-form-item :label="t('match.field.away_ms')" label-width="108px">
              <el-input v-model="form.awayTeamMs" :placeholder="t('match.ph.away_ms')" />
            </el-form-item>
            <el-form-item :label="t('matchEditor.field.away_logo')" label-width="108px">
              <LogoUrlField v-model="form.awayTeamLogoUrl" :team-code="form.awayTeamCode" upload-category="teams" />
            </el-form-item>
          </div>
        </div>
        <el-form-item :label="t('match.field.featured')">
          <el-switch v-model="form.isHot" />
        </el-form-item>
        <p class="field-hint">{{ t('match.hint.create_draft') }}</p>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" :loading="createLoading" @click="submitCreate">
          {{ t('user.btn.create') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.league-matches-page {
  display: flex;
  flex-direction: column;
  gap: 0;
  height: 100%;
  min-height: 0;
}

.league-matches-page :deep(.admin-subnav) {
  flex-shrink: 0;
  margin-bottom: 14px;
}

.league-matches-page .list-panel {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: none;
  background: transparent;
  padding: 0;
  box-shadow: none;
}

.team-country-select {
  width: 100%;
}

.teams-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 20px;
}

.team-col {
  display: flex;
  flex-direction: column;
  min-width: 0;
  padding: 12px;
  border: 1px solid var(--border-soft);
  border-radius: 8px;
  background: #fbfaf7;
}

.team-col-title {
  font-size: 14px;
  font-weight: 750;
  color: var(--text);
  margin-bottom: 10px;
  padding-bottom: 6px;
  border-bottom: 1px solid var(--border-soft);
}

.field-hint {
  font-size: 12px;
  color: var(--text-muted);
  margin: 0;
  line-height: 1.5;
}

.schedule-timezone-hint {
  margin-top: 4px;
}

.league-readonly {
  color: var(--success-text);
  font-weight: 700;
}

@media (max-width: 760px) {
  .teams-row {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}
</style>
