import "server-only";
import { prisma } from "@/app/lib/db";
import type { HomepageSectionKey } from "@/app/lib/definitions";

export type HeroContent = {
  heading: string;
  description: string;
  ctaText: string;
  ctaHref: string;
};

export type HomepageItemDto = {
  id: string;
  section: string;
  label: string;
  text: string;
  href: string;
  imageUrl: string;
  altText: string;
  sortOrder: number;
  published: boolean;
};

export type HomepageSectionDto = {
  id: string;
  key: HomepageSectionKey | string;
  label: string;
  sortOrder: number;
  visible: boolean;
};

export type HeaderContent = {
  title: string;
  subtitle: string;
  logoUrl: string;
};

export type GedContent = {
  heading: string;
  body: string;
  sealTop: string;
  sealMain: string;
  sealBottom: string;
};

export type AboutContent = {
  heading: string;
  body: string;
  ctaText: string;
  ctaHref: string;
  primaryImage: string;
  secondaryImage: string;
};

export type ProgramsSectionContent = {
  heading: string;
  body: string;
  imageUrl: string;
};

export type PartnersSectionContent = {
  label: string;
};

export type BlogsSectionContent = {
  heading: string;
  body: string;
};

export type FooterContent = {
  title: string;
  description: string;
  address: string;
  phone: string;
  email: string;
  programsHeading: string;
  contactHeading: string;
  programs: HomepageItemDto[];
};

async function settingsMap(keys: string[]) {
  const rows = await prisma.siteSetting.findMany({
    where: { key: { in: keys } },
  });
  return Object.fromEntries(rows.map((row) => [row.key, row.value]));
}

function mapItem(item: {
  id: string;
  section: string;
  label: string;
  text: string;
  href: string;
  imageUrl: string;
  altText: string;
  sortOrder: number;
  published: boolean;
}): HomepageItemDto {
  return {
    id: item.id,
    section: item.section,
    label: item.label,
    text: item.text,
    href: item.href,
    imageUrl: item.imageUrl,
    altText: item.altText,
    sortOrder: item.sortOrder,
    published: item.published,
  };
}

export async function getPublishedPrograms() {
  return prisma.program.findMany({
    where: { published: true },
    orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
  });
}

export async function getAllPrograms() {
  return prisma.program.findMany({
    orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
  });
}

export async function getProgramById(id: string) {
  return prisma.program.findUnique({ where: { id } });
}

export async function getPublishedBlogPosts() {
  return prisma.blogPost.findMany({
    where: { published: true },
    orderBy: [{ featured: "desc" }, { sortOrder: "asc" }, { createdAt: "desc" }],
  });
}

export async function getAllBlogPosts() {
  return prisma.blogPost.findMany({
    orderBy: [{ featured: "desc" }, { sortOrder: "asc" }, { createdAt: "desc" }],
  });
}

export async function getBlogPostById(id: string) {
  return prisma.blogPost.findUnique({ where: { id } });
}

export async function getHomepageSections() {
  const sections = await prisma.homepageSection.findMany({
    orderBy: { sortOrder: "asc" },
  });
  return sections as HomepageSectionDto[];
}

export async function getVisibleHomepageSections() {
  return (await getHomepageSections()).filter((section) => section.visible);
}

export async function getHomepageItems(section: string, publishedOnly = false) {
  const items = await prisma.homepageItem.findMany({
    where: {
      section,
      ...(publishedOnly ? { published: true } : {}),
    },
    orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
  });
  return items.map(mapItem);
}

export async function getHomepageItemById(id: string) {
  const item = await prisma.homepageItem.findUnique({ where: { id } });
  return item ? mapItem(item) : null;
}

export async function getSettingsByKeys(keys: string[]) {
  return settingsMap(keys);
}

export async function getHeaderContent(): Promise<HeaderContent> {
  const map = await settingsMap([
    "header_title",
    "header_subtitle",
    "header_logo",
  ]);
  return {
    title: map.header_title || "Vido International",
    subtitle: map.header_subtitle || "Home School",
    logoUrl: map.header_logo || "/vido_galary/logo-school.png",
  };
}

export async function getHeroContent(): Promise<HeroContent> {
  const map = await settingsMap([
    "hero_heading",
    "hero_description",
    "hero_cta_text",
    "hero_cta_href",
  ]);
  return {
    heading: map.hero_heading || "Discover Your Education Potential",
    description:
      map.hero_description ||
      "Our school provides dynamic environment that empowers students to new heights.",
    ctaText: map.hero_cta_text || "Explore More",
    ctaHref: map.hero_cta_href || "/programs",
  };
}

export async function getHeroSettingsMap() {
  const hero = await getHeroContent();
  return {
    hero_heading: hero.heading,
    hero_description: hero.description,
    hero_cta_text: hero.ctaText,
    hero_cta_href: hero.ctaHref,
  };
}

export async function getGedContent(): Promise<GedContent> {
  const map = await settingsMap([
    "ged_heading",
    "ged_body",
    "ged_seal_top",
    "ged_seal_main",
    "ged_seal_bottom",
  ]);
  return {
    heading: map.ged_heading || "American GED® partner in Kenya.",
    body:
      map.ged_body ||
      "Earn a globally recognised US high school equivalency right here at Vido - your direct pathway to American universities, careers abroad, and opportunities worldwide.",
    sealTop: map.ged_seal_top || "Official",
    sealMain: map.ged_seal_main || "GED®",
    sealBottom: map.ged_seal_bottom || "Partner · Kenya",
  };
}

export async function getAboutContent(): Promise<AboutContent> {
  const map = await settingsMap([
    "about_heading",
    "about_body",
    "about_cta_text",
    "about_cta_href",
    "about_image_primary",
    "about_image_secondary",
  ]);
  return {
    heading: map.about_heading || "About Vido School",
    body:
      map.about_body ||
      "Vido International Home School provides flexible, quality education that empowers learners to grow academically, creatively, and confidently in a supportive home-based environment.",
    ctaText: map.about_cta_text || "Read More",
    ctaHref: map.about_cta_href || "/about",
    primaryImage: map.about_image_primary || "/vido_galary/kidslab.jpg",
    secondaryImage: map.about_image_secondary || "/vido_galary/kidsbag.jpg",
  };
}

export async function getProgramsSectionContent(): Promise<ProgramsSectionContent> {
  const map = await settingsMap([
    "programs_heading",
    "programs_body",
    "programs_image",
  ]);
  return {
    heading: map.programs_heading || "Learning That Fits Your Child",
    body:
      map.programs_body ||
      "From in-center classes to online lessons and home tutoring, we support each student with the guidance they need to thrive.",
    imageUrl: map.programs_image || "/vido_galary/kidslearning.png",
  };
}

export async function getPartnersSectionContent(): Promise<PartnersSectionContent> {
  const map = await settingsMap(["partners_label"]);
  return {
    label: map.partners_label || "Our Partners",
  };
}

export async function getBlogsSectionContent(): Promise<BlogsSectionContent> {
  const map = await settingsMap(["blogs_heading", "blogs_body"]);
  return {
    heading: map.blogs_heading || "Latest Updates from Vido School",
    body:
      map.blogs_body ||
      "News, highlights, and insights from our learning community.",
  };
}

export async function getFooterContent(): Promise<FooterContent> {
  const [map, programs] = await Promise.all([
    settingsMap([
      "footer_title",
      "footer_description",
      "footer_address",
      "footer_phone",
      "footer_email",
      "footer_programs_heading",
      "footer_contact_heading",
    ]),
    getHomepageItems("footer_program", true),
  ]);

  return {
    title: map.footer_title || "Vido International Home School",
    description:
      map.footer_description ||
      "Building confident learners through modern academics, mentorship, and a values-driven community.",
    address:
      map.footer_address ||
      "Omwami Close, Kitengela\nMon - Fri: 8:00 AM - 5:00 PM",
    phone: map.footer_phone || "+254 718 372 880",
    email: map.footer_email || "info@vidoschool.com",
    programsHeading: map.footer_programs_heading || "Programs",
    contactHeading: map.footer_contact_heading || "Contact Us",
    programs,
  };
}

export async function getFullHomepageContent() {
  const [
    sections,
    header,
    hero,
    heroSlides,
    ged,
    about,
    programsSection,
    programs,
    partnersSection,
    partners,
    blogsSection,
    posts,
    footer,
  ] = await Promise.all([
    getVisibleHomepageSections(),
    getHeaderContent(),
    getHeroContent(),
    getHomepageItems("hero_slide", true),
    getGedContent(),
    getAboutContent(),
    getProgramsSectionContent(),
    getPublishedPrograms(),
    getPartnersSectionContent(),
    getHomepageItems("partner", true),
    getBlogsSectionContent(),
    getPublishedBlogPosts(),
    getFooterContent(),
  ]);

  return {
    sections,
    header,
    hero,
    heroSlides,
    ged,
    about,
    programsSection,
    programs,
    partnersSection,
    partners,
    blogsSection,
    posts,
    footer,
  };
}

export async function getDashboardStats() {
  const [
    contactTotal,
    contactNew,
    admissionTotal,
    admissionNew,
    programCount,
    blogCount,
    recentContacts,
    recentAdmissions,
  ] = await Promise.all([
    prisma.contactSubmission.count(),
    prisma.contactSubmission.count({ where: { status: "new" } }),
    prisma.admissionSubmission.count(),
    prisma.admissionSubmission.count({ where: { status: "new" } }),
    prisma.program.count(),
    prisma.blogPost.count(),
    prisma.contactSubmission.findMany({
      orderBy: { createdAt: "desc" },
      take: 5,
    }),
    prisma.admissionSubmission.findMany({
      orderBy: { createdAt: "desc" },
      take: 5,
    }),
  ]);

  return {
    contactTotal,
    contactNew,
    admissionTotal,
    admissionNew,
    programCount,
    blogCount,
    recentContacts,
    recentAdmissions,
  };
}
