<script setup>
import Dialog from "primevue/dialog";
import Toast from "primevue/toast";
import { useToast } from "primevue/usetoast";
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { creatorApi } from "../../api/creator";
import { tenantPath } from "../../utils/tenant";

const route = useRoute();
const tenantRoute = (path) => tenantPath(path, route);
const toast = useToast();
const showWithdraw = ref(false);
const withdrawMethod = ref("wallet");
const withdrawAmount = ref("");
const payoutAccounts = ref([]);
const stats = ref({
  total_followers: { value: 0, trend: 0 },
  total_revenue: { value: 0, trend: 0 },
  pending_refunds: 0,
  new_messages: 0,
});

const hasPayoutAccount = computed(() => payoutAccounts.value.length > 0);

const metrics = computed(() => [
  {
    label: "总关注用户",
    value: stats.value.total_followers.value.toLocaleString(),
    trend: stats.value.total_followers.trend,
    subtext: "昨日数据", // Backend DTO doesn't have subtext yet, using static or simplified
  },
  {
    label: "累计总收益",
    value:
      "¥ " +
      stats.value.total_revenue.value.toLocaleString(undefined, {
        minimumFractionDigits: 2,
      }),
    trend: stats.value.total_revenue.trend,
    subtext: "近30天数据",
    canWithdraw: stats.value.total_revenue.value > 0,
  },
]);

const fetchData = async () => {
  try {
    const [dashboardRes, accountsRes] = await Promise.all([
      creatorApi.getDashboard(),
      creatorApi.listPayoutAccounts(),
    ]);
    if (dashboardRes) stats.value = dashboardRes;
    if (accountsRes) payoutAccounts.value = accountsRes;
  } catch (e) {
    console.error("Failed to fetch creator dashboard data:", e);
  }
};

onMounted(() => {
  fetchData();
});

const handleWithdraw = async () => {
  if (!withdrawAmount.value || withdrawAmount.value <= 0) {
    toast.add({
      severity: "warn",
      summary: "提示",
      detail: "请输入有效的提现金额",
      life: 3000,
    });
    return;
  }

  try {
    const accountId =
      withdrawMethod.value === "external" ? payoutAccounts.value[0]?.id : ""; // Default to first account for now if external

    await creatorApi.withdraw({
      amount: parseFloat(withdrawAmount.value),
      method: withdrawMethod.value,
      account_id: accountId,
    });

    showWithdraw.value = false;
    toast.add({
      severity: "success",
      summary: "提现成功",
      detail: "提现申请已提交",
      life: 3000,
    });
    withdrawAmount.value = ""; // Reset
    fetchData(); // Refresh balance/stats
  } catch (e) {
    console.error(e);
    toast.add({
      severity: "error",
      summary: "提现失败",
      detail: "请稍后重试",
      life: 3000,
    });
  }
};
</script>

<template>
  <div>
    <div class="flex items-center justify-between mb-8">
      <h1 class="text-2xl font-bold text-slate-900">管理概览</h1>
      <div class="flex gap-4">
        <router-link
          :to="tenantRoute('/creator/contents/new')"
          class="px-6 py-2.5 bg-primary-600 text-white rounded-lg font-bold hover:bg-primary-700 transition-colors shadow-sm shadow-primary-200 cursor-pointer active:scale-95 flex items-center gap-2"
        >
          <i class="pi pi-plus"></i> 发布新内容
        </router-link>
      </div>
    </div>

    <!-- Key Metrics -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <div
        v-for="metric in metrics"
        :key="metric.label"
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-100 hover:shadow-md transition-shadow relative"
      >
        <div class="text-sm text-slate-500 mb-2">{{ metric.label }}</div>
        <div class="flex items-baseline gap-2">
          <span class="text-3xl font-bold text-slate-900">{{
            metric.value
          }}</span>
          <span
            class="text-xs font-bold"
            :class="metric.trend > 0 ? 'text-green-600' : 'text-red-600'"
          >
            <i
              class="pi"
              :class="metric.trend > 0 ? 'pi-arrow-up' : 'pi-arrow-down'"
              style="font-size: 0.7rem"
            ></i>
            {{ Math.abs(metric.trend) }}%
          </span>
        </div>
        <div class="text-xs text-slate-400 mt-2">{{ metric.subtext }}</div>

        <!-- Withdraw Button for Revenue Card -->
        <button
          v-if="metric.label === '累计总收益' && metric.canWithdraw"
          @click="showWithdraw = true"
          class="absolute top-6 right-6 px-3 py-1.5 bg-green-50 text-green-700 text-xs font-bold rounded-lg hover:bg-green-100 transition-colors"
        >
          提现
        </button>
      </div>
    </div>

    <!-- Pending Orders (Quick Access) -->
    <div class="bg-white p-6 rounded-xl shadow-sm border border-slate-100">
      <h3 class="font-bold text-slate-900 mb-4">待处理事项</h3>
      <div class="flex gap-4">
        <div
          class="flex-1 p-4 bg-orange-50 border border-orange-100 rounded-xl flex items-center justify-between cursor-pointer hover:bg-orange-100 transition-colors"
          @click="$router.push(tenantRoute('/creator/orders'))"
        >
          <div class="flex items-center gap-3">
            <div
              class="w-10 h-10 rounded-full bg-orange-200 text-orange-700 flex items-center justify-center"
            >
              <i class="pi pi-refresh"></i>
            </div>
            <div>
              <div class="font-bold text-slate-900">退款申请</div>
              <div class="text-xs text-orange-600">需要处理</div>
            </div>
          </div>
          <div class="text-2xl font-bold text-orange-700">
            {{ stats.pending_refunds }}
          </div>
        </div>
        <div
          class="flex-1 p-4 bg-blue-50 border border-blue-100 rounded-xl flex items-center justify-between cursor-pointer hover:bg-blue-100 transition-colors"
        >
          <div class="flex items-center gap-3">
            <div
              class="w-10 h-10 rounded-full bg-blue-200 text-blue-700 flex items-center justify-center"
            >
              <i class="pi pi-comments"></i>
            </div>
            <div>
              <div class="font-bold text-slate-900">新私信</div>
              <div class="text-xs text-blue-600">粉丝互动</div>
            </div>
          </div>
          <div class="text-2xl font-bold text-blue-700">
            {{ stats.new_messages }}
          </div>
        </div>
      </div>
    </div>

    <!-- Withdraw Dialog -->
    <Dialog
      v-model:visible="showWithdraw"
      modal
      header="收益提现"
      :style="{ width: '35rem' }"
    >
      <div class="space-y-6 pt-2">
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-3"
            >提现方式</label
          >
          <div class="grid grid-cols-1 gap-3">
            <label
              class="flex items-center gap-4 p-4 border rounded-xl cursor-pointer hover:border-primary-500 hover:bg-slate-50 transition-all"
              :class="
                withdrawMethod === 'external'
                  ? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
                  : 'border-slate-200'
              "
            >
              <input
                type="radio"
                v-model="withdrawMethod"
                value="external"
                class="hidden"
              />
              <div
                class="w-10 h-10 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center"
              >
                <i class="pi pi-credit-card text-xl"></i>
              </div>
              <div class="flex-1">
                <div class="font-bold text-slate-900">提现至银行卡/支付宝</div>
                <div class="text-xs text-slate-500" v-if="hasPayoutAccount">
                  已绑定：{{ payoutAccounts[0].name }} ({{
                    payoutAccounts[0].account.slice(-4)
                  }})
                </div>
                <div
                  class="text-xs text-orange-600 font-bold flex items-center gap-1"
                  v-else
                >
                  <i class="pi pi-exclamation-circle"></i> 未配置收款账户
                  <router-link
                    :to="tenantRoute('/creator/settings')"
                    class="underline hover:text-orange-800 ml-1"
                    >去配置</router-link
                  >
                </div>
              </div>
              <i
                v-if="withdrawMethod === 'external'"
                class="pi pi-check-circle text-primary-600 text-xl"
              ></i>
            </label>

            <label
              class="flex items-center gap-4 p-4 border rounded-xl cursor-pointer hover:border-primary-500 hover:bg-slate-50 transition-all"
              :class="
                withdrawMethod === 'wallet'
                  ? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
                  : 'border-slate-200'
              "
            >
              <input
                type="radio"
                v-model="withdrawMethod"
                value="wallet"
                class="hidden"
              />
              <div
                class="w-10 h-10 rounded-full bg-green-100 text-green-600 flex items-center justify-center"
              >
                <i class="pi pi-wallet text-xl"></i>
              </div>
              <div class="flex-1">
                <div class="font-bold text-slate-900">转入个人钱包余额</div>
                <div class="text-xs text-slate-500">
                  实时到账，可用于平台消费
                </div>
              </div>
              <i
                v-if="withdrawMethod === 'wallet'"
                class="pi pi-check-circle text-primary-600 text-xl"
              ></i>
            </label>
          </div>
        </div>

        <div>
          <label class="block text-sm font-bold text-slate-700 mb-2"
            >提现金额 (¥)</label
          >
          <input
            type="number"
            v-model="withdrawAmount"
            placeholder="请输入金额"
            class="w-full h-12 px-4 border border-slate-200 rounded-lg text-lg font-bold outline-none focus:border-primary-500 transition-colors"
          />
          <div class="text-xs text-slate-400 mt-2 flex justify-between">
            <span
              >可提现收益: ¥
              {{
                stats.total_revenue.value.toLocaleString(undefined, {
                  minimumFractionDigits: 2,
                })
              }}</span
            >
            <button
              class="text-primary-600 hover:underline"
              @click="withdrawAmount = stats.total_revenue.value"
            >
              全部提现
            </button>
          </div>
        </div>
      </div>
      <template #footer>
        <button
          @click="showWithdraw = false"
          class="px-4 py-2 text-slate-500 hover:text-slate-700 text-sm font-bold"
        >
          取消
        </button>
        <button
          @click="handleWithdraw"
          class="px-6 py-2 bg-primary-600 text-white rounded-lg text-sm font-bold hover:bg-primary-700 shadow-sm"
          :disabled="withdrawMethod === 'external' && !hasPayoutAccount"
          :class="{
            'opacity-50 cursor-not-allowed':
              withdrawMethod === 'external' && !hasPayoutAccount,
          }"
        >
          确认提现
        </button>
      </template>
    </Dialog>

    <Toast />
  </div>
</template>
