import { z } from "zod"
import { HOME_PAGE_LOCALE_CODES, type HomePageLocaleCode } from "@/lib/pages/home/locales"
import { createEmptyHomePageFormState, type HomePageFormStateShape } from "@/lib/pages/home/form-types"

const HOME_PAGE_SECTION_KEYS = [
  "hero",
  "stats",
  "services",
  "whyChooseUs",
  "testimonials",
  "process",
  "doctors",
  "reviews",
  "hospitals",
  "certifications",
  "faq",
  "blog",
  "finalCTA",
] as const

type HomePageSectionKey = (typeof HOME_PAGE_SECTION_KEYS)[number]
export type { HomePageSectionKey }

function hasAnyMissingStringOrArray(node: unknown): boolean {
  if (typeof node === "string") return node.trim() === ""
  if (Array.isArray(node)) {
    if (node.length === 0) return true
    return node.some((item) => hasAnyMissingStringOrArray(item))
  }
  if (node && typeof node === "object") {
    return Object.values(node as Record<string, unknown>).some((value) => hasAnyMissingStringOrArray(value))
  }
  return false
}

function findFirstMissingPath(node: unknown, path: string[] = []): string | null {
  if (typeof node === "string") {
    return node.trim() === "" ? path.join(".") || "en" : null
  }

  if (Array.isArray(node)) {
    if (node.length === 0) return path.join(".") || "en"
    for (let index = 0; index < node.length; index += 1) {
      const missingPath = findFirstMissingPath(node[index], [...path, `[${index}]`])
      if (missingPath) return missingPath
    }
    return null
  }

  if (node && typeof node === "object") {
    for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
      const missingPath = findFirstMissingPath(value, [...path, key])
      if (missingPath) return missingPath
    }
  }

  return null
}

const homePageFormSchema = z.object({
  hero: z.object({
    title: z.string(),
    description: z.string(),
    primaryButtonText: z.string(),
    primaryButtonLink: z.string(),
  }),
  stats: z.object({
    title: z.string(),
    stats: z.array(z.object({ label: z.string(), value: z.string() })),
  }),
  services: z.object({
    title: z.string(),
    categories: z.array(z.object({ title: z.string(), icon: z.string() })),
    serviceDetails: z.array(
      z.object({
        category: z.string().optional().default(""),
        image: z.string(),
        title: z.string(),
        description: z.string(),
      })
    ),
    buttonText: z.string(),
    buttonLink: z.string(),
  }),
  whyChooseUs: z.object({
    title: z.string(),
    features: z.array(z.object({ title: z.string(), description: z.string(), icon: z.string() })),
  }),
  testimonials: z.object({
    title: z.string(),
    subtitle: z.string(),
    testimonials: z.array(z.object({ name: z.string(), treatment: z.string(), videoLink: z.string() })),
    buttonText: z.string(),
    buttonLink: z.string(),
  }),
  process: z.object({
    title: z.string(),
    steps: z.array(
      z.object({
        title: z.string(),
        description: z.string(),
        image: z.string(),
        imageTitle: z.string(),
        imageSubtitle: z.string(),
        imageIcon: z.string(),
      })
    ),
  }),
  doctors: z.object({
    title: z.string(),
    subtitle: z.string(),
    buttonText: z.string(),
    buttonLink: z.string(),
  }),
  reviews: z.object({
    title: z.string(),
    subtitle: z.string(),
    reviews: z.array(
      z.object({ review: z.string(), fullname: z.string(), location: z.string(), avatar: z.string() })
    ),
  }),
  hospitals: z.object({
    title: z.string(),
    subtitle: z.string(),
    hospitals: z.array(
      z.object({
        location: z.string(),
        name: z.string(),
        description: z.string(),
        image: z.string(),
        features: z.array(z.string()),
        buttonText: z.string(),
        buttonLink: z.string(),
      })
    ),
  }),
  certifications: z.object({
    title: z.string(),
    subtitle: z.string(),
    certifications: z.array(
      z.object({
        name: z.string(),
        description: z.string(),
        status: z.string(),
        issuer: z.string(),
        year: z.string(),
        image: z.string(),
      })
    ),
  }),
  faq: z.object({
    title: z.string(),
    categories: z.array(z.object({ name: z.string() })),
    faqs: z.array(
      z.object({
        category: z.string(),
        question: z.string(),
        answer: z.string(),
      })
    ),
  }),
  blog: z.object({
    eyebrow: z.string(),
    title: z.string(),
    subtitle: z.string(),
  }),
  finalCTA: z.object({
    eyebrow: z.string(),
    title: z.string(),
    description: z.string(),
    primaryButtonText: z.string(),
    primaryButtonLink: z.string(),
    secondaryButtonIcon: z.string(),
    secondaryButtonText: z.string(),
    secondaryButtonLink: z.string(),
    badges: z.array(z.object({ label: z.string(), icon: z.string() })),
  }),
})

const localesSchema = z.record(z.string(), homePageFormSchema)

export function parseHomePagePutBody(input: unknown):
  | { ok: true; data: { locales: Record<string, HomePageFormStateShape>; sectionKey?: HomePageSectionKey } }
  | { ok: false; error: string } {
  if (!input || typeof input !== "object" || !("locales" in input)) {
    return { ok: false, error: "Invalid body: expected { locales }" }
  }
  const raw = input as { locales: unknown; sectionKey?: unknown }
  if (!raw.locales || typeof raw.locales !== "object" || Array.isArray(raw.locales)) {
    return { ok: false, error: "Invalid locales" }
  }
  let sectionKey: HomePageSectionKey | undefined
  if (typeof raw.sectionKey === "string") {
    if (!HOME_PAGE_SECTION_KEYS.includes(raw.sectionKey as HomePageSectionKey)) {
      return { ok: false, error: `Unknown section key: ${raw.sectionKey}` }
    }
    sectionKey = raw.sectionKey as HomePageSectionKey
  } else if (raw.sectionKey !== undefined) {
    return { ok: false, error: "Invalid section key" }
  }

  for (const key of Object.keys(raw.locales as Record<string, unknown>)) {
    if (!HOME_PAGE_LOCALE_CODES.includes(key as HomePageLocaleCode)) {
      return { ok: false, error: `Unknown locale: ${key}` }
    }
  }
  const parsed = z.object({ locales: localesSchema }).safeParse({ locales: raw.locales })
  if (!parsed.success) {
    return { ok: false, error: parsed.error.issues[0]?.message ?? "Validation failed" }
  }
  const parsedLocales = parsed.data.locales as Record<string, HomePageFormStateShape>
  const englishLocale = parsedLocales.en
  if (!englishLocale) {
    return { ok: false, error: "English (en) content is required" }
  }

  if (sectionKey) {
    const englishSection = englishLocale[sectionKey]
    if (hasAnyMissingStringOrArray(englishSection)) {
      const missingPath = findFirstMissingPath(englishSection, ["en", sectionKey])
      return {
        ok: false,
        error: missingPath
          ? `Please fill all required English fields. Missing: ${missingPath}`
          : "Please fill all required English fields.",
      }
    }
  } else if (hasAnyMissingStringOrArray(englishLocale)) {
    const missingPath = findFirstMissingPath(englishLocale)
    return {
      ok: false,
      error: missingPath
        ? `Please fill all required English fields. Missing: ${missingPath}`
        : "Please fill all required English fields.",
    }
  }

  return {
    ok: true,
    data: {
      locales: parsedLocales,
      sectionKey,
    },
  }
}

export function parseHomePageJsonForStorage(value: unknown): { data: HomePageFormStateShape } {
  const base = createEmptyHomePageFormState()
  const parsed = homePageFormSchema.safeParse(value)
  return { data: parsed.success ? parsed.data : base }
}
