import { parseJsonColumn } from "@/lib/utils/parse-json-column";
import { ruleMatches } from "@/lib/utils/survey-logic";
import type { ThankYouScreenConfig, ThankYouVariant } from "@/types";
import type { FillerAnswerValue, FillerQuestion } from "@/types/filler";
import type { BuilderQuestion } from "@/types/builder";

export const DEFAULT_THANK_YOU_EMOJI = "✅";
export const DEFAULT_THANK_YOU_TITLE = "Thank you!";
export const DEFAULT_THANK_YOU_DESCRIPTION =
  "Your response has been recorded.";

export const THANK_YOU_EMOJI_CHOICES = [
  "✅",
  "🎉",
  "🙏",
  "😊",
  "😄",
  "😍",
  "😔",
  "😞",
  "🤔",
  "💙",
  "⭐",
  "👍",
  "👎",
  "❤️",
  "👏",
  "🌱",
];

export interface ResolvedThankYou {
  emoji: string;
  title: string;
  description: string;
}

export function newThankYouVariantId(): string {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    return crypto.randomUUID();
  }
  return `ty-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}

export function normalizeThankYouConfig(raw: unknown): ThankYouScreenConfig {
  const obj =
    parseJsonColumn<ThankYouScreenConfig>(raw) ??
    (raw && typeof raw === "object" ? (raw as ThankYouScreenConfig) : null);

  const variants = Array.isArray(obj?.variants)
    ? obj.variants
        .filter((v) => v && typeof v === "object" && typeof v.questionId === "string")
        .map((v) => ({
          id: typeof v.id === "string" && v.id ? v.id : newThankYouVariantId(),
          questionId: v.questionId,
          conditionType: (v.conditionType === "not_equals" ||
          v.conditionType === "any_answer"
            ? v.conditionType
            : "equals") as ThankYouVariant["conditionType"],
          conditionValue:
            typeof v.conditionValue === "string" ? v.conditionValue : null,
          emoji: (v.emoji ?? DEFAULT_THANK_YOU_EMOJI).slice(0, 16),
          title: (v.title ?? DEFAULT_THANK_YOU_TITLE).slice(0, 200),
          description: (v.description ?? DEFAULT_THANK_YOU_DESCRIPTION).slice(
            0,
            2000
          ),
        }))
    : [];

  return {
    emoji: (obj?.emoji ?? DEFAULT_THANK_YOU_EMOJI).slice(0, 16),
    title: obj?.title?.trim() ? obj.title.slice(0, 200) : DEFAULT_THANK_YOU_TITLE,
    description: obj?.description?.trim()
      ? obj.description.slice(0, 2000)
      : DEFAULT_THANK_YOU_DESCRIPTION,
    variants,
  };
}

/** First matching rule wins; otherwise the default ending. */
export function resolveThankYouScreen(
  config: ThankYouScreenConfig | null | undefined,
  answers: Record<string, FillerAnswerValue>
): ResolvedThankYou {
  const normalized = normalizeThankYouConfig(config);

  for (const variant of normalized.variants ?? []) {
    const answer = answers[variant.questionId] ?? null;
    const matches = ruleMatches(
      {
        id: variant.id,
        conditionType: variant.conditionType,
        conditionValue: variant.conditionValue,
        action: "end_survey",
        targetQuestionId: null,
      },
      answer
    );
    if (matches) {
      return {
        emoji: variant.emoji || DEFAULT_THANK_YOU_EMOJI,
        title: variant.title || DEFAULT_THANK_YOU_TITLE,
        description: variant.description || DEFAULT_THANK_YOU_DESCRIPTION,
      };
    }
  }

  return {
    emoji: normalized.emoji || DEFAULT_THANK_YOU_EMOJI,
    title: normalized.title || DEFAULT_THANK_YOU_TITLE,
    description: normalized.description || DEFAULT_THANK_YOU_DESCRIPTION,
  };
}

export function getThankYouConditionOptions(
  question: BuilderQuestion | FillerQuestion | undefined
): { value: string; label: string }[] {
  if (!question) return [];

  if (
    question.type === "multiple_choice" ||
    question.type === "checkbox" ||
    question.type === "dropdown"
  ) {
    return (question.optionsConfig?.choices ?? []).map((c) => ({
      value: c,
      label: c,
    }));
  }

  if (question.type === "nps") {
    return [
      { value: "9-10", label: "Promoter (9–10) — happy" },
      { value: "7-8", label: "Passive (7–8)" },
      { value: "0-6", label: "Detractor (0–6) — unhappy" },
    ];
  }

  if (question.type === "rating") {
    const min = question.optionsConfig?.minRating ?? 1;
    const max = question.optionsConfig?.maxRating ?? 5;
    const mid = Math.floor((min + max) / 2);
    const options: { value: string; label: string }[] = [];
    if (max - min >= 2) {
      options.push({
        value: `${min}-${mid}`,
        label: `Low (${min}–${mid}) — negative`,
      });
      if (mid + 1 <= max) {
        options.push({
          value: `${mid + 1}-${max}`,
          label: `High (${mid + 1}–${max}) — positive`,
        });
      }
    }
    for (let n = min; n <= max; n += 1) {
      options.push({
        value: String(n),
        label: `${n} star${n === 1 ? "" : "s"}`,
      });
    }
    return options;
  }

  return [];
}

/** One-click Good vs Bad endings from the first NPS or rating question. */
export function buildGoodBadThankYouVariants(
  questions: BuilderQuestion[]
): ThankYouVariant[] {
  const scored =
    questions.find((q) => q.type === "nps") ??
    questions.find((q) => q.type === "rating");
  if (!scored) return [];

  if (scored.type === "nps") {
    return [
      {
        id: newThankYouVariantId(),
        questionId: scored.id,
        conditionType: "equals",
        conditionValue: "9-10",
        emoji: "🎉",
        title: "We're so glad you loved it!",
        description:
          "Thanks for the kind words. We'll keep working to earn this score.",
      },
      {
        id: newThankYouVariantId(),
        questionId: scored.id,
        conditionType: "equals",
        conditionValue: "0-6",
        emoji: "😔",
        title: "Thanks for the honest feedback",
        description:
          "We're sorry it wasn't a great experience. Your notes help us improve.",
      },
    ];
  }

  const min = scored.optionsConfig?.minRating ?? 1;
  const max = scored.optionsConfig?.maxRating ?? 5;
  const mid = Math.floor((min + max) / 2);

  return [
    {
      id: newThankYouVariantId(),
      questionId: scored.id,
      conditionType: "equals",
      conditionValue: `${mid + 1}-${max}`,
      emoji: "🎉",
      title: "We're so glad you loved it!",
      description:
        "Thanks for the kind words. We'll keep working to earn this score.",
    },
    {
      id: newThankYouVariantId(),
      questionId: scored.id,
      conditionType: "equals",
      conditionValue: `${min}-${mid}`,
      emoji: "😔",
      title: "Thanks for the honest feedback",
      description:
        "We're sorry it wasn't a great experience. Your notes help us improve.",
    },
  ];
}

export function emptyThankYouVariant(
  questionId: string,
  question?: BuilderQuestion
): ThankYouVariant {
  const options = getThankYouConditionOptions(question);
  const first = options[0];
  return {
    id: newThankYouVariantId(),
    questionId,
    conditionType: "equals",
    conditionValue: first?.value ?? null,
    emoji: "😊",
    title: "Thank you!",
    description: "Your response has been recorded.",
  };
}
