<script setup>
import Dialog from "primevue/dialog";
import RadioButton from "primevue/radiobutton";
import Toast from "primevue/toast";
import { useToast } from "primevue/usetoast";
import { reactive, ref, onMounted } from "vue";
import { creatorApi } from "../../api/creator";
import { commonApi } from "../../api/common";

const toast = useToast();
const fileInput = ref(null);
const currentUploadType = ref("");
const showAddAccount = ref(false);
const payoutAccounts = ref([]);
const saveLoading = ref(false);
const isUploading = ref(false);
const uploadProgress = ref(0);

const newAccount = reactive({
  type: "bank",
  name: "",
  account: "",
  realname: "",
});

const form = reactive({
  name: "",
  bio: "",
  description: "",
  avatar: "",
  cover: "",
});

const fetchData = async () => {
  try {
    const [settings, accounts] = await Promise.all([
      creatorApi.getSettings(),
      creatorApi.listPayoutAccounts(),
    ]);
    if (settings) {
      Object.assign(form, settings);
      // Set defaults if empty
      if (!form.avatar)
        form.avatar = "https://api.dicebear.com/7.x/avataaars/svg?seed=Master1";
    }
    payoutAccounts.value = accounts || [];
  } catch (e) {
    console.error(e);
  }
};

onMounted(fetchData);

const triggerUpload = (type) => {
  currentUploadType.value = type;
  if (fileInput.value) {
    fileInput.value.accept = "image/*";
    fileInput.value.click();
  }
};

const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  isUploading.value = true;
  uploadProgress.value = 0;

  try {
    const task = commonApi.uploadWithProgress(file, "image", (p) => {
      uploadProgress.value = p;
    });
    const res = await task.promise;
    console.log("Upload response:", res);

    if (res && res.url) {
      if (currentUploadType.value === "avatar") {
        form.avatar = res.url;
      } else {
        form.cover = res.url;
      }
      toast.add({ severity: "success", summary: "上传成功", life: 2000 });
    } else {
      console.error("Invalid upload response:", res);
      toast.add({
        severity: "error",
        summary: "上传失败",
        detail: "服务器返回无效数据",
        life: 3000,
      });
    }
  } catch (e) {
    console.error(e);
    toast.add({
      severity: "error",
      summary: "上传失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    isUploading.value = false;
    uploadProgress.value = 0;
  }
  event.target.value = "";
};

const handleAddAccount = async () => {
  if (payoutAccounts.value.length >= 1) {
    toast.add({
      severity: "error",
      summary: "限制",
      detail: "仅支持一个收款账户",
      life: 3000,
    });
    return;
  }
  if (newAccount.type === "alipay") {
    newAccount.name = "支付宝";
  }
  if (!newAccount.name || !newAccount.account || !newAccount.realname) {
    toast.add({
      severity: "warn",
      summary: "提示",
      detail: "请填写完整信息",
      life: 3000,
    });
    return;
  }
  try {
    await creatorApi.addPayoutAccount(newAccount);
    showAddAccount.value = false;
    toast.add({
      severity: "success",
      summary: "添加成功",
      detail: "收款账户已添加",
      life: 3000,
    });
    fetchData();
    // Reset
    newAccount.name = "";
    newAccount.account = "";
    newAccount.realname = "";
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "添加失败",
      detail: e.message,
      life: 3000,
    });
  }
};

const removeAccount = async (id) => {
  if (!confirm("确定要删除此账户吗？")) return;
  try {
    await creatorApi.removePayoutAccount(id);
    toast.add({ severity: "success", summary: "删除成功", life: 3000 });
    fetchData();
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "删除失败",
      detail: e.message,
      life: 3000,
    });
  }
};

const saveSettings = async () => {
  if (!form.name) {
    toast.add({
      severity: "error",
      summary: "错误",
      detail: "频道名称不能为空",
      life: 3000,
    });
    return;
  }
  if (saveLoading.value) return;
  saveLoading.value = true;
  try {
    await creatorApi.updateSettings(form);
    toast.add({
      severity: "success",
      summary: "保存成功",
      detail: "设置已更新",
      life: 3000,
    });
  } catch (e) {
    toast.add({
      severity: "error",
      summary: "保存失败",
      detail: e.message,
      life: 3000,
    });
  } finally {
    saveLoading.value = false;
  }
};
</script>

<template>
  <div>
    <h1 class="text-2xl font-bold text-slate-900 mb-8">频道设置</h1>

    <div class="space-y-8">
      <!-- 0. Tips -->
      <div
        class="bg-blue-50 p-6 rounded-xl border border-blue-100 text-sm text-blue-700 flex items-start gap-4"
      >
        <i class="pi pi-info-circle text-xl mt-0.5"></i>
        <div>
          <h4 class="font-bold mb-1">频道设置须知</h4>
          <ul class="list-disc list-inside space-y-1 opacity-90">
            <li>建议封面图尺寸 1280x320px，重点内容居中。</li>
            <li>频道名称修改后需人工审核，审核期间原名称仍可见。</li>
          </ul>
        </div>
      </div>

      <!-- 1. Basic Info & Visuals -->
      <div class="bg-white rounded-xl shadow-sm border border-slate-100 p-8">
        <h2
          class="text-lg font-bold text-slate-900 mb-6 pb-4 border-b border-slate-100"
        >
          基本信息
        </h2>

        <div class="space-y-8">
          <!-- Avatar & Name -->
          <div class="flex items-start gap-6">
            <div
              class="relative group cursor-pointer flex-shrink-0"
              @click="triggerUpload('avatar')"
            >
              <div
                class="w-24 h-24 rounded-full border-4 border-slate-50 shadow-sm overflow-hidden bg-slate-100 relative"
              >
                <img :src="form.avatar" class="w-full h-full object-cover" />
                <div
                  class="absolute inset-0 bg-black/40 flex items-center justify-center transition-opacity"
                  :class="{
                    'opacity-100':
                      currentUploadType === 'avatar' && isUploading,
                    'opacity-0 group-hover:opacity-100': !(
                      currentUploadType === 'avatar' && isUploading
                    ),
                  }"
                >
                  <i
                    v-if="currentUploadType === 'avatar' && isUploading"
                    class="pi pi-spin pi-spinner text-white text-2xl"
                  ></i>
                  <i v-else class="pi pi-camera text-white text-2xl"></i>
                </div>
              </div>
            </div>
            <div class="flex-1 space-y-4">
              <div>
                <label class="block text-sm font-bold text-slate-700 mb-2"
                  >频道名称</label
                >
                <input
                  v-model="form.name"
                  type="text"
                  class="w-full h-11 px-4 border border-slate-200 rounded-lg focus:border-primary-500 outline-none transition-colors"
                  placeholder="给您的频道起个名字"
                />
              </div>
              <div>
                <label class="block text-sm font-bold text-slate-700 mb-2"
                  >一句话简介</label
                >
                <input
                  v-model="form.bio"
                  type="text"
                  class="w-full h-11 px-4 border border-slate-200 rounded-lg focus:border-primary-500 outline-none transition-colors"
                  placeholder="介绍一下您的频道特色..."
                />
              </div>
            </div>
          </div>

          <!-- Cover Image (Moved Here) -->
          <div>
            <label class="block text-sm font-bold text-slate-700 mb-3"
              >频道头图 (Cover)</label
            >
            <div
              class="aspect-[4/1] rounded-xl bg-slate-50 border-2 border-dashed border-slate-300 relative overflow-hidden group cursor-pointer hover:border-primary-400 transition-all"
              @click="triggerUpload('cover')"
            >
              <img
                v-if="form.cover"
                :src="form.cover"
                class="w-full h-full object-cover"
              />
              <div
                class="absolute inset-0 flex flex-col items-center justify-center text-slate-400 bg-white/50 opacity-100 group-hover:bg-white/80 transition-all"
                v-else
              >
                <i class="pi pi-image text-3xl mb-2"></i>
                <span class="text-sm font-medium"
                  >点击上传 (建议尺寸 1280x320)</span
                >
              </div>
              <!-- Hover Overlay -->
              <div
                v-if="
                  form.cover || (currentUploadType === 'cover' && isUploading)
                "
                class="absolute inset-0 bg-black/40 flex flex-col items-center justify-center transition-opacity"
                :class="{
                  'opacity-100': currentUploadType === 'cover' && isUploading,
                  'opacity-0 group-hover:opacity-100': !(
                    currentUploadType === 'cover' && isUploading
                  ),
                }"
              >
                <template v-if="currentUploadType === 'cover' && isUploading">
                  <i class="pi pi-spin pi-spinner text-white text-3xl mb-2"></i>
                  <span class="text-white text-sm font-bold"
                    >上传中 {{ Math.round(uploadProgress) }}%</span
                  >
                </template>
                <span v-else class="text-white font-bold"
                  ><i class="pi pi-refresh mr-2"></i>更换封面</span
                >
              </div>
            </div>
          </div>

          <!-- Intro Detail -->
          <div>
            <label class="block text-sm font-bold text-slate-700 mb-2"
              >详细介绍</label
            >
            <textarea
              v-model="form.description"
              rows="4"
              class="w-full p-4 border border-slate-200 rounded-lg focus:border-primary-500 outline-none transition-colors resize-none"
              placeholder="详细描述您的履历、师承或频道内容规划..."
            ></textarea>
          </div>

          <!-- Save Button -->
          <div class="pt-6 border-t border-slate-100 flex justify-end">
            <button
              @click="saveSettings"
              :disabled="saveLoading"
              class="px-8 py-3 bg-primary-600 text-white rounded-lg font-bold hover:bg-primary-700 shadow-lg shadow-primary-200 cursor-pointer active:scale-95 flex items-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
            >
              <i v-if="saveLoading" class="pi pi-spin pi-spinner"></i>
              <i v-else class="pi pi-check"></i>
              {{ saveLoading ? "保存中..." : "保存修改" }}
            </button>
          </div>
        </div>
      </div>

      <!-- 2. Payout Settings -->
      <div class="bg-white rounded-xl shadow-sm border border-slate-100 p-8">
        <div
          class="flex items-center justify-between mb-6 pb-4 border-b border-slate-100"
        >
          <h2 class="text-lg font-bold text-slate-900">收款账户</h2>
          <button
            @click="showAddAccount = true"
            v-if="payoutAccounts.length === 0"
            class="text-sm font-bold text-primary-600 hover:text-primary-700 cursor-pointer flex items-center gap-1 px-3 py-1.5 rounded hover:bg-primary-50 transition-colors"
          >
            <i class="pi pi-plus"></i> 添加账户
          </button>
          <span v-else class="text-xs text-slate-400"
            >仅支持一个收款账户，删除后可更换</span
          >
        </div>

        <div class="grid grid-cols-1 gap-4">
          <div
            v-for="acc in payoutAccounts"
            :key="acc.id"
            class="p-4 border border-slate-200 rounded-xl flex items-center gap-4 bg-white relative group hover:border-primary-200 transition-colors"
          >
            <div
              class="w-10 h-10 rounded-full flex items-center justify-center text-xl"
              :class="
                acc.type === 'alipay'
                  ? 'bg-blue-50 text-blue-600'
                  : 'bg-red-50 text-red-600'
              "
            >
              <i
                class="pi"
                :class="acc.type === 'alipay' ? 'pi-mobile' : 'pi-briefcase'"
              ></i>
            </div>
            <div>
              <div class="font-bold text-slate-900">{{ acc.name }}</div>
              <div class="text-sm text-slate-500">
                {{ acc.type === "alipay" ? "支付宝" : "银行卡" }} ({{
                  acc.account.slice(-4)
                }})
              </div>
            </div>
            <button
              @click="removeAccount(acc.id)"
              class="absolute top-4 right-4 text-slate-300 hover:text-red-500 cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity p-2"
            >
              <i class="pi pi-trash"></i>
            </button>
          </div>

          <!-- Empty State -->
          <div
            v-if="payoutAccounts.length === 0"
            class="col-span-full py-8 text-center text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200"
          >
            <i class="pi pi-wallet text-2xl mb-2"></i>
            <p>暂无收款账户，请添加</p>
          </div>
        </div>
      </div>
    </div>

    <input
      type="file"
      ref="fileInput"
      class="hidden"
      @change="handleFileChange"
    />

    <!-- Add Account Dialog -->
    <Dialog
      v-model:visible="showAddAccount"
      modal
      header="添加收款账户"
      :style="{ width: '25rem' }"
    >
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-bold text-slate-700 mb-2"
            >账户类型</label
          >
          <div class="flex gap-4">
            <label
              class="flex items-center gap-2 cursor-pointer p-2 border border-transparent rounded hover:bg-slate-50"
            >
              <RadioButton v-model="newAccount.type" value="bank" />
              <span>银行卡</span>
            </label>
            <label
              class="flex items-center gap-2 cursor-pointer p-2 border border-transparent rounded hover:bg-slate-50"
            >
              <RadioButton v-model="newAccount.type" value="alipay" />
              <span>支付宝</span>
            </label>
          </div>
        </div>

        <div v-if="newAccount.type === 'bank'">
          <label class="block text-sm font-bold text-slate-700 mb-2"
            >银行名称</label
          >
          <input
            type="text"
            v-model="newAccount.name"
            class="w-full h-10 px-3 border border-slate-200 rounded-lg outline-none focus:border-primary-500"
            placeholder="如：招商银行"
          />
        </div>

        <div>
          <label class="block text-sm font-bold text-slate-700 mb-2">{{
            newAccount.type === "bank" ? "银行卡号" : "支付宝账号"
          }}</label>
          <input
            type="text"
            v-model="newAccount.account"
            class="w-full h-10 px-3 border border-slate-200 rounded-lg outline-none focus:border-primary-500"
            placeholder="请输入账号"
          />
        </div>

        <div>
          <label class="block text-sm font-bold text-slate-700 mb-2"
            >真实姓名</label
          >
          <input
            type="text"
            v-model="newAccount.realname"
            class="w-full h-10 px-3 border border-slate-200 rounded-lg outline-none focus:border-primary-500"
            placeholder="需与实名认证一致"
          />
        </div>
      </div>
      <template #footer>
        <button
          @click="showAddAccount = false"
          class="px-4 py-2 text-slate-500 hover:text-slate-700 text-sm font-bold cursor-pointer"
        >
          取消
        </button>
        <button
          @click="handleAddAccount"
          class="px-6 py-2 bg-primary-600 text-white rounded-lg text-sm font-bold hover:bg-primary-700 cursor-pointer shadow-sm"
        >
          保存
        </button>
      </template>
    </Dialog>

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