import { z } from "zod"
import {
  DOCTORS_PAGE_LOCALE_CODES,
  type DoctorsPageLocaleCode,
} from "@/lib/pages/doctors/locales"
import {
  createEmptyDoctorsPageFormState,
  type DoctorsPageFormStateShape,
} from "@/lib/pages/doctors/form-types"

const DOCTORS_PAGE_SECTION_KEYS = ["hero", "features", "faq", "cta"] as const
type DoctorsPageSectionKey = (typeof DOCTORS_PAGE_SECTION_KEYS)[number]
export type { DoctorsPageSectionKey }

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 quickStatSchema = z.object({
  label: z.string(),
  value: z.string(),
})

const imageEyebrowItemSchema = z.object({
  label: z.string(),
  value: z.string(),
  icon: z.string(),
})

const featureSchema = z.object({
  title: z.string(),
  description: z.string(),
  icon: z.string(),
})

const faqSchema = z.object({
  question: z.string(),
  answer: z.string(),
})

const doctorsPageFormSchema = z.object({
  hero: z.object({
    eyebrow: z.string(),
    title: z.string(),
    description: z.string(),
    imageEyebrow: z.array(imageEyebrowItemSchema),
    quickStats: z.array(quickStatSchema),
  }),
  features: z.object({
    title: z.string(),
    subtitle: z.string(),
    features: z.array(featureSchema),
  }),
  faq: z.object({
    title: z.string(),
    faqs: z.array(faqSchema),
  }),
  cta: 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(),
  }),
})

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

export function parseDoctorsPagePutBody(input: unknown):
  | { ok: true; data: { locales: Record<string, DoctorsPageFormStateShape>; sectionKey?: DoctorsPageSectionKey } }
  | { 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: DoctorsPageSectionKey | undefined
  if (typeof raw.sectionKey === "string") {
    if (!DOCTORS_PAGE_SECTION_KEYS.includes(raw.sectionKey as DoctorsPageSectionKey)) {
      return { ok: false, error: `Unknown section key: ${raw.sectionKey}` }
    }
    sectionKey = raw.sectionKey as DoctorsPageSectionKey
  } 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 (!DOCTORS_PAGE_LOCALE_CODES.includes(key as DoctorsPageLocaleCode)) {
      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, DoctorsPageFormStateShape>
  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 parseDoctorsPageJsonForStorage(value: unknown): { data: DoctorsPageFormStateShape } {
  const base = createEmptyDoctorsPageFormState()
  const parsed = doctorsPageFormSchema.safeParse(value)
  return { data: parsed.success ? parsed.data : base }
}
