import { INSTITUTION_TYPES } from "./constants";

/** One-time implementation/setup fee for every new subscription. */
export const SETUP_FEE_BDT = 5000;

export type BillingCycle = "MONTHLY" | "YEARLY";
export type BillingBasis = "PER_STUDENT_MONTH" | "PER_STUDENT_YEAR";

export interface EducationPattern {
  /** stable id — also stored on the PackagePlan row (educationPattern) */
  id: string;
  name: string;
  nameBn: string;
  /** Government tiers / private tiers / open to any sector */
  sector: "GOVT" | "PRIVATE" | "ANY";
  /** institution types this pattern can serve */
  types: (typeof INSTITUTION_TYPES)[number][];
  basis: BillingBasis;
  /** ৳ per student, per basis unit (month or year) */
  rate: number;
  /** % off when paying yearly (null → yearly discount not offered) */
  yearlyDiscountPct: number | null;
  /** billing cycles the institution may choose from */
  cycles: BillingCycle[];
  /** display grouping + accent tone for the pricing cards */
  group: "GOVERNMENT" | "SCHOOLS" | "HIGHER" | "SPECIAL";
  tone: "govt" | "teal" | "violet" | "amber";
  features: string[];
  featuresBn: string[];
}

const f = (features: string[], featuresBn: string[]) => ({ features, featuresBn });

/** The 8 pricing tiers — one per education pattern. */
export const EDUCATION_PATTERNS: EducationPattern[] = [
  {
    id: "GOVT_SCHOOL",
    name: "Govt. Institution (Primary & High School)",
    nameBn: "সরকারি প্রতিষ্ঠান (প্রাথমিক ও উচ্চ বিদ্যালয়)",
    sector: "GOVT",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    basis: "PER_STUDENT_MONTH",
    rate: 3,
    yearlyDiscountPct: null,
    cycles: ["MONTHLY"],
    group: "GOVERNMENT",
    tone: "govt",
    ...f(
      ["Only ৳3 per student / month", "Full EMS suite for every class & section", "Unlimited students & branches", "Dedicated government onboarding support"],
      ["মাত্র ৳৩ প্রতি শিক্ষার্থী / মাস", "সব শ্রেণি ও শাখার জন্য সম্পূর্ণ EMS", "অসীম শিক্ষার্থী ও শাখা", "সরকারি প্রতিষ্ঠানের জন্য নিবেদিত সাপোর্ট"]
    ),
  },
  {
    id: "PRIMARY",
    name: "Primary School",
    nameBn: "প্রাথমিক বিদ্যালয়",
    sector: "PRIVATE",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    basis: "PER_STUDENT_MONTH",
    rate: 7,
    yearlyDiscountPct: 10,
    cycles: ["MONTHLY", "YEARLY"],
    group: "SCHOOLS",
    tone: "teal",
    ...f(
      ["৳7 per student / month", "Pay yearly & save 10%", "Results, fees, attendance & guardians portal", "Unlimited students & branches"],
      ["৳৭ প্রতি শিক্ষার্থী / মাস", "বছরে পরিশোধে ১০% ছাড়", "ফলাফল, ফি, উপস্থিতি ও অভিভাবক পোর্টাল", "অসীম শিক্ষার্থী ও শাখা"]
    ),
  },
  {
    id: "HIGH_SCHOOL",
    name: "High School",
    nameBn: "উচ্চ বিদ্যালয়",
    sector: "PRIVATE",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    basis: "PER_STUDENT_MONTH",
    rate: 7,
    yearlyDiscountPct: 10,
    cycles: ["MONTHLY", "YEARLY"],
    group: "SCHOOLS",
    tone: "teal",
    ...f(
      ["৳7 per student / month", "Pay yearly & save 10%", "Exam routines, marks tabulation & merit lists", "Unlimited students & branches"],
      ["৳৭ প্রতি শিক্ষার্থী / মাস", "বছরে পরিশোধে ১০% ছাড়", "পরীক্ষার রুটিন, মার্কস ট্যাবুলেশন ও মেধা তালিকা", "অসীম শিক্ষার্থী ও শাখা"]
    ),
  },
  {
    id: "PRIMARY_HIGH",
    name: "Primary & High School",
    nameBn: "প্রাথমিক ও উচ্চ বিদ্যালয় (সমন্বিত)",
    sector: "PRIVATE",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    basis: "PER_STUDENT_MONTH",
    rate: 7,
    yearlyDiscountPct: 10,
    cycles: ["MONTHLY", "YEARLY"],
    group: "SCHOOLS",
    tone: "teal",
    ...f(
      ["One campus, primary through Class 10", "৳7 per student / month", "Pay yearly & save 10%", "Shared admin, separate academic sections"],
      ["এক ক্যাম্পাস, প্রাথমিক থেকে ১০ম শ্রেণি", "৳৭ প্রতি শিক্ষার্থী / মাস", "বছরে পরিশোধে ১০% ছাড়", "একই অ্যাডমিন, আলাদা একাডেমিক সেকশন"]
    ),
  },
  {
    id: "GOVT_COLLEGE",
    name: "Govt. College & University",
    nameBn: "সরকারি কলেজ ও বিশ্ববিদ্যালয়",
    sector: "GOVT",
    types: ["COLLEGE_AND_UNIVERSITY"],
    basis: "PER_STUDENT_MONTH",
    rate: 3,
    yearlyDiscountPct: null,
    cycles: ["MONTHLY"],
    group: "GOVERNMENT",
    tone: "govt",
    ...f(
      ["Only ৳3 per student / month", "Departments, sessions & hall management", "Unlimited students & departments", "Dedicated government onboarding support"],
      ["মাত্র ৳৩ প্রতি শিক্ষার্থী / মাস", "বিভাগ, সেশন ও হল ব্যবস্থাপনা", "অসীম শিক্ষার্থী ও বিভাগ", "সরকারি প্রতিষ্ঠানের জন্য নিবেদিত সাপোর্ট"]
    ),
  },
  {
    id: "COLLEGE_UNIV",
    name: "College & University",
    nameBn: "কলেজ ও বিশ্ববিদ্যালয়",
    sector: "PRIVATE",
    types: ["COLLEGE_AND_UNIVERSITY"],
    basis: "PER_STUDENT_YEAR",
    rate: 70,
    yearlyDiscountPct: null,
    cycles: ["YEARLY"],
    group: "HIGHER",
    tone: "violet",
    ...f(
      ["Flat ৳70 per student / year", "Departments, sessions & semester results", "Unlimited students & departments", "Priority email & phone support"],
      ["সমতল ৳৭০ প্রতি শিক্ষার্থী / বছর", "বিভাগ, সেশন ও সেমিস্টার ফলাফল", "অসীম শিক্ষার্থী ও বিভাগ", "প্রায়োরিটি ইমেইল ও ফোন সাপোর্ট"]
    ),
  },
  {
    id: "COACHING",
    name: "Coaching",
    nameBn: "কোচিং সেন্টার",
    sector: "ANY",
    types: ["COACHING"],
    basis: "PER_STUDENT_MONTH",
    rate: 7,
    yearlyDiscountPct: 10,
    cycles: ["MONTHLY", "YEARLY"],
    group: "SPECIAL",
    tone: "amber",
    ...f(
      ["৳7 per student / month", "Pay yearly & save 10%", "Batch schedules, attendance & payments", "Unlimited batches & students"],
      ["৳৭ প্রতি শিক্ষার্থী / মাস", "বছরে পরিশোধে ১০% ছাড়", "ব্যাচ রুটিন, উপস্থিতি ও পেমেন্ট", "অসীম ব্যাচ ও শিক্ষার্থী"]
    ),
  },
  {
    id: "MADRASHA",
    name: "Madrasa",
    nameBn: "মাদ্রাসা",
    sector: "ANY",
    types: ["MADRASHA"],
    basis: "PER_STUDENT_MONTH",
    rate: 5,
    yearlyDiscountPct: 10,
    cycles: ["MONTHLY", "YEARLY"],
    group: "SPECIAL",
    tone: "teal",
    ...f(
      ["৳5 per student / month", "Pay yearly & save 10%", "Arabic & general departments together", "Unlimited students & boarding support"],
      ["৳৫ প্রতি শিক্ষার্থী / মাস", "বছরে পরিশোধে ১০% ছাড়", "আরবি ও সাধারণ বিভাগ একসাথে", "অসীম শিক্ষার্থী ও আবাসিক সহায়তা"]
    ),
  },
];

export const PATTERN_BY_ID: Record<string, EducationPattern> = Object.fromEntries(
  EDUCATION_PATTERNS.map((p) => [p.id, p])
);

/** Patterns an institution may subscribe under, given its type + sector. */
export function patternsForInstitution(
  type: string,
  isGovernment: boolean
): EducationPattern[] {
  const out: EducationPattern[] = [];
  for (const p of EDUCATION_PATTERNS) {
    if (!p.types.includes(type as never)) continue;
    if (p.sector === "GOVT" && !isGovernment) continue;
    if (p.sector === "PRIVATE" && isGovernment) continue;
    // an institution matches at most one pattern per (sector, level) family —
    // PRIMARY_HIGH additionally appears for primary/high types as the
    // combined-campus option, so dedupe by id
    if (!out.some((x) => x.id === p.id)) out.push(p);
  }
  // combined "Primary & High School" pattern shows after the single-level ones
  return out.sort((a, b) => EDUCATION_PATTERNS.indexOf(a) - EDUCATION_PATTERNS.indexOf(b));
}

/** Months covered by a billing cycle for a pattern. */
export function cycleMonths(pattern: EducationPattern, cycle: BillingCycle): number {
  if (pattern.basis === "PER_STUDENT_YEAR") return 12;
  return cycle === "YEARLY" ? 12 : 1;
}

export interface CostBreakdown {
  students: number;
  cycle: BillingCycle;
  months: number;
  /** students × rate × months (or students × rate for per-year basis) */
  base: number;
  discountPct: number;
  discountAmount: number;
  setupFee: number;
  total: number;
}

/** Full subscription cost for a pattern at a given student count and cycle. */
export function estimateCost(opts: {
  pattern: EducationPattern;
  students: number;
  cycle: BillingCycle;
  withSetup?: boolean;
}): CostBreakdown {
  const { pattern, students, cycle, withSetup = false } = opts;
  const months = cycleMonths(pattern, cycle);
  const base =
    pattern.basis === "PER_STUDENT_YEAR"
      ? Math.round(students * pattern.rate * (cycle === "YEARLY" ? 1 : months) * 100) / 100
      : Math.round(students * pattern.rate * months * 100) / 100;
  const discountPct = cycle === "YEARLY" ? (pattern.yearlyDiscountPct ?? 0) : 0;
  const discountAmount = Math.round(base * (discountPct / 100) * 100) / 100;
  const setupFee = withSetup ? SETUP_FEE_BDT : 0;
  return {
    students,
    cycle,
    months,
    base,
    discountPct,
    discountAmount,
    setupFee,
    total: Math.round((base - discountAmount + setupFee) * 100) / 100,
  };
}

/** Formats a BDT amount compactly for card headlines (e.g. "৳8,400"). */
export function fmtBDTShort(v: number): string {
  return `৳${Math.round(v).toLocaleString("en-US")}`;
}

/* ------------------------------------------------------------------
 * Landing pricing cards — flat monthly packages per student-count
 * range. Categories are the cards (one per institution type / sector);
 * ranges (PricingTier rows in the DB) are managed by the central
 * admin, so new slabs can be added without a code change.
 * ------------------------------------------------------------------ */

export interface PricingCategory {
  code: string;
  name: string;
  nameBn: string;
  sector: "GOVT" | "PRIVATE" | "ANY";
  types: (typeof INSTITUTION_TYPES)[number][];
  /** PriceArt scene key for the card illustration */
  art: string;
  tone: "govt" | "teal" | "violet" | "amber";
  group: "GOVERNMENT" | "SCHOOLS" | "HIGHER" | "SPECIAL";
}

export const PRICING_CATEGORIES: PricingCategory[] = [
  {
    code: "GOVT_SCHOOL",
    name: "Govt. School",
    nameBn: "সরকারি বিদ্যালয়",
    sector: "GOVT",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    art: "GOVT_SCHOOL",
    tone: "govt",
    group: "GOVERNMENT",
  },
  {
    code: "NON_GOVT_SCHOOL",
    name: "Non-Govt. School",
    nameBn: "বেসরকারি বিদ্যালয়",
    sector: "PRIVATE",
    types: ["PRIMARY_AND_HIGH_SCHOOL"],
    art: "HIGH_SCHOOL",
    tone: "teal",
    group: "SCHOOLS",
  },
  {
    code: "GOVT_COLLEGE_UNIV",
    name: "Govt. College & University",
    nameBn: "সরকারি কলেজ ও বিশ্ববিদ্যালয়",
    sector: "GOVT",
    types: ["COLLEGE_AND_UNIVERSITY"],
    art: "GOVT_COLLEGE",
    tone: "govt",
    group: "HIGHER",
  },
  {
    code: "NON_GOVT_COLLEGE_UNIV",
    name: "Non-Govt. College & University",
    nameBn: "বেসরকারি কলেজ ও বিশ্ববিদ্যালয়",
    sector: "PRIVATE",
    types: ["COLLEGE_AND_UNIVERSITY"],
    art: "COLLEGE_UNIV",
    tone: "violet",
    group: "HIGHER",
  },
  {
    code: "COACHING",
    name: "Coaching Center",
    nameBn: "কোচিং সেন্টার",
    sector: "ANY",
    types: ["COACHING"],
    art: "COACHING",
    tone: "amber",
    group: "SPECIAL",
  },
  {
    code: "MADRASHA",
    name: "Madrasa",
    nameBn: "মাদ্রাসা",
    sector: "ANY",
    types: ["MADRASHA"],
    art: "MADRASHA",
    tone: "teal",
    group: "SPECIAL",
  },
];

export const PRICING_CATEGORY_BY_CODE: Record<string, PricingCategory> = Object.fromEntries(
  PRICING_CATEGORIES.map((c) => [c.code, c])
);

/** Pricing cards an institution may subscribe under, given type + sector. */
export function pricingCategoriesForInstitution(
  type: string,
  isGovernment: boolean
): PricingCategory[] {
  return PRICING_CATEGORIES.filter((c) => {
    if (!c.types.includes(type as never)) return false;
    if (c.sector === "GOVT" && !isGovernment) return false;
    if (c.sector === "PRIVATE" && isGovernment) return false;
    return true;
  });
}

/** "0–300" / "301+" — used on cards, requests and subscriptions. */
export function tierRangeLabel(minStudents: number, maxStudents: number | null): string {
  return maxStudents ? `${minStudents}–${maxStudents}` : `${minStudents}+`;
}

/** Yearly effective monthly price after the slab's yearly discount. */
export function yearlyEffectiveMonthly(monthlyPrice: number, yearlyDiscountPct: number): number {
  return Math.round(monthlyPrice * (1 - yearlyDiscountPct / 100) * 100) / 100;
}
