import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessage } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import {
  getInviteActivityList,
  getInviteActivityDetail,
  createInviteActivity,
  updateInviteActivity,
  deleteInviteActivity,
  publishInviteActivity,
  pauseInviteActivity,
  resumeInviteActivity
} from "@/api/invite";
import { getAvailableCoupons } from "@/api/coupon";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { onMounted, reactive, ref, toRaw } from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElDatePicker,
  ElInputNumber,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
  ElSelect,
  ElOption,
  ElCard,
  ElDivider
} from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  resetPagination,
  updatePaginationData
} from "@/utils/paginationHelper";
import type { InviteActivityFormProps, InviteActivitySearchFormProps } from "./types";

interface SearchFormProps extends InviteActivitySearchFormProps {}

export function useInviteActivity() {
  const form = reactive<SearchFormProps>({
    name: "",
    status: undefined,
    startTime: "",
    endTime: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>(initPagination());

  // 优惠券模板列表（从后端API获取）
  const couponTemplateList = ref<{ id: number; name: string; value: number; minAmount: number }[]>([]);

  async function fetchCouponTemplates() {
    try {
      const { data } = await getAvailableCoupons();
      couponTemplateList.value = (data || []).map((t: any) => ({
        id: t.id,
        name: t.couponName,
        value: t.discountValue,
        minAmount: t.minAmount || 0
      }));
    } catch {
      couponTemplateList.value = [];
    }
  }

  type TagType = "success" | "primary" | "warning" | "info" | "danger";

  const statusMap: Record<number, { text: string; type: TagType }> = {
    0: { text: "草稿", type: "info" },
    1: { text: "已发布", type: "primary" },
    2: { text: "进行中", type: "success" },
    3: { text: "已暂停", type: "warning" },
    4: { text: "已结束", type: "info" }
  };

  const rewardRuleTypeMap: Record<number, { text: string; type: TagType }> = {
    1: { text: "固定奖励", type: "primary" },
    2: { text: "阶梯奖励", type: "success" }
  };

  const columns: TableColumnList = [
    {
      label: "活动ID",
      prop: "id",
      width: 80
    },
    {
      label: "活动名称",
      prop: "activityName",
      minWidth: 150
    },
    {
      label: "活动类型",
      prop: "activityType",
      minWidth: 100,
      cellRenderer: () => <ElTag type="warning">邀请有礼</ElTag>
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <ElTag type={item.type}>{item.text}</ElTag>;
      }
    },
    {
      label: "时间范围",
      prop: "timeRange",
      minWidth: 280,
      formatter: ({ startTime, endTime }) =>
        `${dayjs(startTime).format("YYYY-MM-DD HH:mm")} ~ ${dayjs(endTime).format("YYYY-MM-DD HH:mm")}`
    },
    {
      label: "总邀请数",
      prop: "totalInviteCount",
      width: 100,
      formatter: ({ totalInviteCount }) => totalInviteCount || 0
    },
    {
      label: "有效邀请数",
      prop: "validInviteCount",
      width: 100,
      formatter: ({ validInviteCount }) => validInviteCount || 0
    },
    {
      label: "奖励发放数",
      prop: "rewardIssuedCount",
      width: 100,
      formatter: ({ rewardIssuedCount }) => rewardIssuedCount || 0
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 320,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      if (form.name) searchParams.activityName = form.name;
      if (form.status !== undefined) searchParams.status = form.status;
      if (form.startTime && form.endTime) {
        searchParams.startTime = form.startTime;
        searchParams.endTime = form.endTime;
      }

      const { data } = await getInviteActivityList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        updatePaginationData(pagination, data);
      }
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  }

  async function handleDelete(row) {
    const { code } = await deleteInviteActivity(row.id);
    if (code === 200) {
      message("删除成功", { type: "success" });
      onSearch();
    }
  }

  async function handlePublish(row) {
    const { code } = await publishInviteActivity(row.id);
    if (code === 200) {
      message("发布成功", { type: "success" });
      onSearch();
    }
  }

  async function handlePause(row) {
    const { code } = await pauseInviteActivity(row.id);
    if (code === 200) {
      message("暂停成功", { type: "success" });
      onSearch();
    }
  }

  async function handleResume(row) {
    const { code } = await resumeInviteActivity(row.id);
    if (code === 200) {
      message("恢复成功", { type: "success" });
      onSearch();
    }
  }

  function handleViewDetail(row) {
    addDialog({
      title: "邀请活动详情",
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <div>
          <ElDescriptions column={2} border>
            <ElDescriptionsItem label="活动名称">{row.activityName}</ElDescriptionsItem>
            <ElDescriptionsItem label="活动类型">
              <ElTag type="warning">邀请有礼</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="状态">
              <ElTag type={statusMap[row.status]?.type}>{statusMap[row.status]?.text}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="奖励规则">
              <ElTag type={rewardRuleTypeMap[row.rewardRuleType]?.type}>{rewardRuleTypeMap[row.rewardRuleType]?.text}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="开始时间">{dayjs(row.startTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="结束时间">{dayjs(row.endTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="邀请人奖励">¥{row.inviterRewardAmount || 0}</ElDescriptionsItem>
            <ElDescriptionsItem label="被邀请人奖励">¥{row.inviteeRewardAmount || 0}</ElDescriptionsItem>
            <ElDescriptionsItem label="每人最大邀请次数">{row.maxInviteCount || "不限"}</ElDescriptionsItem>
            <ElDescriptionsItem label="首充最低金额">¥{row.inviteeFirstChargeMinAmount || 0}</ElDescriptionsItem>
            <ElDescriptionsItem label="创建时间">{dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="活动说明" span={2}>{row.activityDesc || "暂无说明"}</ElDescriptionsItem>
          </ElDescriptions>

          {/* 双向优惠券配置展示 */}
          <div class="mt-4">
            <h4 class="mb-3 text-base font-semibold">🎁 优惠券奖励配置</h4>
            <ElDescriptions column={1} border>
              <ElDescriptionsItem label="邀请人优惠券">
                {row.inviterCouponTemplateId ? (
                  <ElTag type="danger">已配置（ID: {row.inviterCouponTemplateId}）</ElTag>
                ) : (
                  <span class="text-gray-400">未配置</span>
                )}
                <span class="ml-2 text-xs text-gray-500">被邀请人完成首单后发放</span>
              </ElDescriptionsItem>
              <ElDescriptionsItem label="被邀请人优惠券">
                {row.inviteeCouponTemplateId ? (
                  <ElTag type="warning">已配置（ID: {row.inviteeCouponTemplateId}）</ElTag>
                ) : (
                  <span class="text-gray-400">未配置</span>
                )}
                <span class="ml-2 text-xs text-gray-500">注册绑定时即时发放</span>
              </ElDescriptionsItem>
            </ElDescriptions>
          </div>

          <div class="mt-4">
            <h4 class="mb-2">统计数据</h4>
            <ElDescriptions column={3}>
              <ElDescriptionsItem label="总邀请数">{row.totalInviteCount || 0}</ElDescriptionsItem>
              <ElDescriptionsItem label="有效邀请数">{row.validInviteCount || 0}</ElDescriptionsItem>
              <ElDescriptionsItem label="奖励发放数">{row.rewardIssuedCount || 0}</ElDescriptionsItem>
            </ElDescriptions>
          </div>
        </div>
      )
    });
  }

  function renderForm(formData: InviteActivityFormProps) {
    return (
      <div class="invite-form">
        {/* 基本信息 */}
        <div class="form-block">
          <div class="block-title">基本信息</div>
          <ElForm label-width="100px" size="default">
            <div class="form-grid-2">
              <ElFormItem label="活动名称" required>
                <ElInput v-model={formData.activityName} placeholder="请输入活动名称" clearable maxlength={50} showWordLimit />
              </ElFormItem>
              <ElFormItem label="奖励规则类型" required>
                <ElSelect v-model={formData.rewardRuleType} placeholder="请选择" class="w-full">
                  <ElOption label="固定奖励" value={1} />
                  <ElOption label="阶梯奖励" value={2} />
                </ElSelect>
              </ElFormItem>
            </div>

            <ElFormItem label="活动时间" required>
              <div class="time-range">
                <ElDatePicker v-model={formData.startTime} type="datetime" placeholder="开始时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
                <span class="time-sep">至</span>
                <ElDatePicker v-model={formData.endTime} type="datetime" placeholder="结束时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </ElFormItem>

            <ElFormItem label="活动说明">
              <ElInput v-model={formData.activityDesc} type="textarea" rows={2} placeholder="请输入活动说明（可选）" maxlength={500} showWordLimit />
            </ElFormItem>
          </ElForm>
        </div>

        {/* 邀请规则 */}
        <div class="form-block">
          <div class="block-title">邀请规则</div>
          <ElForm label-width="140px" size="default">
            <div class="form-grid-2">
              <ElFormItem label="邀请人奖励金额" required>
                <ElInputNumber v-model={formData.inviterRewardAmount} min={0} precision={2} class="w-full" placeholder="每成功邀请一人获得的奖励" />
              </ElFormItem>
              <ElFormItem label="被邀请人奖励金额" required>
                <ElInputNumber v-model={formData.inviteeRewardAmount} min={0} precision={2} class="w-full" placeholder="被邀请人获得的奖励" />
              </ElFormItem>
            </div>
            <div class="form-grid-2">
              <ElFormItem label="首充最低金额">
                <ElInputNumber v-model={formData.inviteeFirstChargeMinAmount} min={0} precision={2} class="w-full" placeholder="被邀请人首次充值最低金额（元）" />
              </ElFormItem>
              <ElFormItem label="每人最大邀请次数">
                <ElInputNumber v-model={formData.maxInviteCount} min={1} class="w-full" placeholder="不填则不限制" />
              </ElFormItem>
            </div>
          </ElForm>
        </div>

        {/* 双向优惠券配置 - 双卡片布局 */}
        <ElDivider content-position="left">
          <span style={{ fontSize: '16px', fontWeight: 'bold' }}>🎁 奖励配置（优惠券）</span>
        </ElDivider>

        <div class="reward-cards-container">
          {/* 卡片1：邀请人奖励配置 */}
          <ElCard shadow="hover" class="reward-card">
            {{
              header: () => (
                <div class="card-header">
                  <span class="card-title">🎁 邀请人奖励配置</span>
                  <ElTag type="danger" size="small" effect="dark">必填</ElTag>
                </div>
              ),
              default: () => (
                <div class="card-content">
                  <p class="card-description text-gray-500 text-sm mb-3">
                    被邀请人完成首单后发放给邀请人的优惠券
                  </p>
                  <ElForm label-width="120px" size="default">
                    <ElFormItem label="优惠券模板" required>
                      <ElSelect
                        v-model={formData.inviterCouponTemplateId}
                        placeholder="请选择邀请人优惠券模板"
                        clearable
                        class="w-full"
                      >
                        {couponTemplateList.value.map(template => (
                          <ElOption
                            key={template.id}
                            label={`${template.name}（满${template.minAmount}减${template.value}元）`}
                            value={template.id}
                          />
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElForm>
                  <div class="tip-box mt-2">
                    <el-icon class="mr-1"><InfoFilled /></el-icon>
                    <span class="text-xs text-gray-400">选择后将自动关联该优惠券模板，被邀请人首单完成后系统将自动发放给邀请人</span>
                  </div>
                </div>
              )
            }}
          </ElCard>

          {/* 卡片2：被邀请人奖励配置 */}
          <ElCard shadow="hover" class="reward-card invitee-card">
            {{
              header: () => (
                <div class="card-header">
                  <span class="card-title">🎊 被邀请人奖励配置</span>
                  <ElTag type="warning" size="small" effect="plain">可选</ElTag>
                </div>
              ),
              default: () => (
                <div class="card-content">
                  <p class="card-description text-gray-500 text-sm mb-3">
                    注册绑定时即时发放给被邀请人的优惠券
                  </p>
                  <ElForm label-width="120px" size="default">
                    <ElFormItem label="优惠券模板">
                      <ElSelect
                        v-model={formData.inviteeCouponTemplateId}
                        placeholder="请选择被邀请人优惠券模板（可选）"
                        clearable
                        class="w-full"
                      >
                        {couponTemplateList.value.map(template => (
                          <ElOption
                            key={template.id}
                            label={`${template.name}（满${template.minAmount}减${template.value}元）`}
                            value={template.id}
                          />
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElForm>
                  <div class="tip-box mt-2">
                    <el-icon class="mr-1"><InfoFilled /></el-icon>
                    <span class="text-xs text-gray-400">可选配置，用于提升新用户注册转化率，注册成功后立即发放</span>
                  </div>
                </div>
              )
            }}
          </ElCard>
        </div>
      </div>
    );
  }

  function validateForm(formData: InviteActivityFormProps): boolean {
    if (!formData.activityName) {
      message("请输入活动名称", { type: "warning" });
      return false;
    }
    if (!formData.rewardRuleType) {
      message("请选择奖励规则类型", { type: "warning" });
      return false;
    }
    if (!formData.startTime) {
      message("请选择开始时间", { type: "warning" });
      return false;
    }
    if (!formData.endTime) {
      message("请选择结束时间", { type: "warning" });
      return false;
    }
    if (!formData.inviterRewardAmount || formData.inviterRewardAmount <= 0) {
      message("请输入有效的邀请人奖励金额", { type: "warning" });
      return false;
    }
    if (!formData.inviteeRewardAmount || formData.inviteeRewardAmount <= 0) {
      message("请输入有效的被邀请人奖励金额", { type: "warning" });
      return false;
    }

    // 联动校验：至少需要配置一组优惠券奖励
    if (!formData.inviterCouponTemplateId && !formData.inviteeCouponTemplateId) {
      ElMessage.warning('至少需要配置一组优惠券奖励（邀请人或被邀请人）');
      return false;
    }

    // 校验邀请人优惠券（必填）
    if (!formData.inviterCouponTemplateId) {
      ElMessage.warning('请配置邀请人优惠券模板（必填项）');
      return false;
    }

    return true;
  }

  function handleEdit(row) {
    const formData = reactive<InviteActivityFormProps>({
      id: row.id,
      activityName: row.activityName,
      activityType: row.activityType || 10, // 固定为邀请有礼类型
      activityDesc: row.activityDesc || "",
      startTime: row.startTime,
      endTime: row.endTime,
      status: row.status,
      maxInviteCount: row.maxInviteCount,
      rewardRuleType: row.rewardRuleType || 1,
      inviterRewardAmount: row.inviterRewardAmount,
      inviteeRewardAmount: row.inviteeRewardAmount,
      inviteeFirstChargeMinAmount: row.inviteeFirstChargeMinAmount,
      // 双向优惠券配置
      inviterCouponTemplateId: row.inviterCouponTemplateId || null,
      inviteeCouponTemplateId: row.inviteeCouponTemplateId || null
    });

    addDialog({
      title: "编辑邀请活动",
      width: "900px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => renderForm(formData),
      beforeSure: async (done) => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await updateInviteActivity(formData.id!, toRaw(formData));
          if (code === 200) {
            message("编辑成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("编辑失败", { type: "error" });
        }
      }
    });
  }

  function handleAdd() {
    const formData = reactive<InviteActivityFormProps>({
      activityName: "",
      activityType: 10, // 固定为邀请有礼类型
      activityDesc: "",
      startTime: "",
      endTime: "",
      status: 0,
      maxInviteCount: undefined,
      rewardRuleType: 1,
      inviterRewardAmount: null,
      inviteeRewardAmount: null,
      inviteeFirstChargeMinAmount: undefined,
      // 双向优惠券配置
      inviterCouponTemplateId: null,
      inviteeCouponTemplateId: null
    });

    addDialog({
      title: "新增邀请活动",
      width: "900px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => renderForm(formData),
      beforeSure: async (done) => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await createInviteActivity(toRaw(formData));
          if (code === 200) {
            message("新增成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("新增失败", { type: "error" });
        }
      }
    });
  }

  function handleSizeChange(val: number) {
    handlePageSizeChange(val, pagination, onSearch);
  }

  function handleCurrentChange(val: number) {
    handleCurrentPageChange(val, pagination, onSearch);
  }

  onMounted(() => {
    onSearch();
    fetchCouponTemplates();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    statusMap,
    rewardRuleTypeMap,
    onSearch,
    resetForm,
    handleAdd,
    handleEdit,
    handleViewDetail,
    handleDelete,
    handlePublish,
    handlePause,
    handleResume,
    handleSizeChange,
    handleCurrentChange
  };
}
