import type { SuggestionDraft, ActivityDraft, MutualAidDraft, UserBranch } from "../types";
import { normalizeDisplayText, pickKV, parseDateToOffset, parseFirstNumber } from "./formatters";
import { detectMutualAidType } from "./intent";

function parseBranchFromText(text: string, branches: UserBranch[]) {
  const normalized = normalizeDisplayText(text);
  for (const branch of branches) {
    if (normalized.includes(branch.name)) {
      return branch;
    }
  }
  return null;
}

export function applySuggestionDraft(prev: SuggestionDraft, text: string, branches: UserBranch[]) {
  const next: SuggestionDraft = { ...prev };
  const lines = normalizeDisplayText(text).split(/\n+/).map((x) => x.trim()).filter(Boolean);
  for (const line of lines) {
    const kv = pickKV(line);
    if (!kv) continue;
    if (kv.key.includes("标题")) next.title = kv.value;
    else if (kv.key.includes("摘要")) next.summary = kv.value;
    else if (kv.key.includes("正文")) next.body = kv.value;
    else if (kv.key.includes("分会")) {
      const branch = parseBranchFromText(kv.value, branches);
      if (branch) {
        next.branchIds = [branch.id];
        next.branchName = branch.name;
      }
    }
  }
  if (!next.branchIds || next.branchIds.length === 0) {
    const branch = parseBranchFromText(text, branches);
    if (branch) {
      next.branchIds = [branch.id];
      next.branchName = branch.name;
    }
  }
  return next;
}

export function applyActivityDraft(prev: ActivityDraft, text: string, branches: UserBranch[]) {
  const next: ActivityDraft = { ...prev };
  const lines = normalizeDisplayText(text).split(/\n+/).map((x) => x.trim()).filter(Boolean);
  for (const line of lines) {
    const kv = pickKV(line);
    if (!kv) continue;
    const key = kv.key;
    const value = kv.value;
    if (key.includes("标题")) next.title = value;
    else if (key.includes("简介") || key.includes("描述")) next.description = value;
    else if (key.includes("地点")) next.location = value;
    else if (key.includes("开始")) next.startsAt = parseDateToOffset(value) || next.startsAt;
    else if (key.includes("结束")) next.endsAt = parseDateToOffset(value) || next.endsAt;
    else if (key.includes("截止")) next.registerDeadline = parseDateToOffset(value) || next.registerDeadline;
    else if (key.includes("人数")) {
      const count = parseFirstNumber(value);
      if (count > 0) next.capacity = count;
    } else if (key.includes("分会")) {
      const branch = parseBranchFromText(value, branches);
      if (branch) {
        next.branchIds = [branch.id];
        next.branchName = branch.name;
      }
    }
  }
  return next;
}

export function applyMutualAidDraft(prev: MutualAidDraft, text: string, branches: UserBranch[]) {
  const next: MutualAidDraft = { ...prev };
  const lines = normalizeDisplayText(text).split(/\n+/).map((x) => x.trim()).filter(Boolean);
  const type = detectMutualAidType(text);
  if (type) next.postType = type;
  for (const line of lines) {
    const kv = pickKV(line);
    if (!kv) continue;
    const key = kv.key;
    const value = kv.value;
    if (key.includes("类型")) {
      const detected = detectMutualAidType(value);
      if (detected) next.postType = detected;
    } else if (key.includes("标题")) next.title = value;
    else if (key.includes("描述") || key.includes("详情")) next.description = value;
    else if (key.includes("电话")) next.contactPhone = value;
    else if (key.includes("微信")) next.contactWechat = value;
    else if (key.includes("标签")) next.tagsText = value;
    else if (key.includes("身份")) next.publisherTitle = value;
    else if (key.includes("分会")) {
      const branch = parseBranchFromText(value, branches);
      if (branch) {
        next.branchId = branch.id;
        next.branchName = branch.name;
      }
    }
  }
  return next;
}

export function suggestionMissing(draft: SuggestionDraft) {
  const missing: string[] = [];
  if (!draft.title) missing.push("标题");
  if (!draft.summary) missing.push("摘要");
  if (!draft.body) missing.push("正文");
  if (!draft.branchIds || draft.branchIds.length === 0) missing.push("分会");
  return missing;
}

export function activityMissing(draft: ActivityDraft) {
  const missing: string[] = [];
  if (!draft.title) missing.push("活动标题");
  if (!draft.location) missing.push("活动地点");
  if (!draft.startsAt) missing.push("开始时间");
  if (!draft.endsAt) missing.push("结束时间");
  if (!draft.branchIds || draft.branchIds.length === 0) missing.push("分会");
  return missing;
}

export function mutualAidMissing(draft: MutualAidDraft) {
  const missing: string[] = [];
  if (!draft.postType) missing.push("互助类型");
  if (!draft.title) missing.push("标题");
  if (!draft.description) missing.push("详情描述");
  if (!draft.branchId) missing.push("分会");
  return missing;
}

export function validateSuggestionDraft(draft: SuggestionDraft) {
  const issues: string[] = [];
  if (draft.summary && draft.summary.length < 5) issues.push("摘要至少 5 个字");
  if (draft.body && draft.body.length < 10) issues.push("正文至少 10 个字");
  return issues;
}

export function validateActivityDraft(draft: ActivityDraft) {
  const issues: string[] = [];
  if (draft.capacity !== undefined && (!Number.isFinite(draft.capacity) || draft.capacity <= 0)) {
    issues.push("参与人数上限必须大于 0");
  }
  const start = toTimestamp(draft.startsAt);
  const end = toTimestamp(draft.endsAt);
  const deadline = toTimestamp(draft.registerDeadline);
  if (draft.startsAt && !start) issues.push("开始时间格式应为 YYYY-MM-DD HH:mm");
  if (draft.endsAt && !end) issues.push("结束时间格式应为 YYYY-MM-DD HH:mm");
  if (draft.registerDeadline && !deadline) issues.push("报名截止时间格式应为 YYYY-MM-DD HH:mm");
  if (start && end && end <= start) issues.push("结束时间必须晚于开始时间");
  if (deadline && start && deadline >= start) issues.push("报名截止时间必须早于开始时间");
  return issues;
}

export function validateMutualAidDraft(draft: MutualAidDraft) {
  const issues: string[] = [];
  if (draft.description && draft.description.length < 10) issues.push("详情描述至少 10 个字");
  if (draft.contactPhone) {
    const digits = draft.contactPhone.replace(/\D/g, "");
    if (digits.length > 0 && digits.length < 11) issues.push("联系电话至少包含 11 位手机号");
  }
  return issues;
}

function toTimestamp(text?: string) {
  if (!text) return 0;
  const normalized = text.replace("+08:00", "").replace("T", " ");
  const safe = normalized.length === 16 ? `${normalized}:00` : normalized;
  const value = Date.parse(safe.replace(" ", "T") + "+08:00");
  return Number.isFinite(value) ? value : 0;
}
