"use client"

import { useEffect, useRef, useState } from "react"
import { useRouter } from "next/navigation"
import {
  Building2,
  LayoutGrid,
  Award,
  Cpu,
  Route,
  MessageSquare,
  MapPin,
  HelpCircle,
  Megaphone,
  Users,
  Library,
  Save,
  Send,
  Loader2,
  X,
  ImagePlus,
} from "lucide-react"

import { type Language } from "@/components/dashboard/shared/LanguageTabs"
import { CategorySelect } from "@/components/dashboard/articles/CategorySelect"
import { HospitalBasicInfo, type HospitalBasicInfoStoredFields } from "./HospitalBasicInfo"
import { type HospitalHeroData } from "./HospitalHeroSection"
import { HospitalAboutSection, type HospitalAboutData } from "./HospitalAboutSection"
import { HospitalGallerySection, type HospitalGalleryData } from "./HospitalGallerySection"
import { HospitalDepartmentsSection, type HospitalDepartmentsData } from "./HospitalDepartmentsSection"
import { HospitalDoctorsSection, type HospitalDoctorsSectionData } from "./HospitalDoctorsSection"
import { HospitalAccreditationSection, type HospitalAccreditationData } from "./HospitalAccreditationSection"
import { HospitalTechnologySection, type HospitalTechnologyData } from "./HospitalTechnologySection"
import { HospitalVisitProcessSection, type HospitalVisitProcessData } from "./HospitalVisitProcessSection"
import { HospitalReviewsSection, type HospitalReviewsData } from "./HospitalReviewsSection"
import { HospitalLocationSection, type HospitalLocationData } from "./HospitalLocationSection"
import { HospitalPackagesSection, type HospitalPackagesData } from "./HospitalPackagesSection"
import { HospitalFAQSection, type HospitalFAQData } from "./HospitalFAQSection"
import { HospitalCTASection, type HospitalCTAData } from "./HospitalCTASection"
import { HospitalSimilarSection, type HospitalSimilarData } from "./HospitalSimilarSection"
import { validateUrlSlug } from "@/lib/slug-validation"
import { MEDIA_FILE_BASE } from "@/lib/media-manager/file-names"
import { stageImage, revokeStagedImage } from "@/lib/media-manager/stage"
import type { StagedImage } from "@/lib/media-manager/types"
import {
  commitPendingHospitalImages,
  createEmptyHospitalPendingImages,
  clearHospitalPendingImages,
  hospitalPendingHasAny,
  hospitalPendingKey,
} from "@/lib/media-manager/hospital-pending"
import { mergeHospitalFormMediaFromSavedForm } from "@/lib/media-manager/entity-form-media"

// ─── Locale content shape ─────────────────────────────────────────────────────

interface LocaleContent {
  hospitalName: string
  hospitalLocation: string
  /** Localized hospital type label — independent per locale */
  hospitalType: string
  hero: HospitalHeroData
  about: HospitalAboutData
  gallery: HospitalGalleryData
  departments: HospitalDepartmentsData
  doctors: HospitalDoctorsSectionData
  accreditation: HospitalAccreditationData
  technology: HospitalTechnologyData
  visitProcess: HospitalVisitProcessData
  reviews: HospitalReviewsData
  location: HospitalLocationData
  packages: HospitalPackagesData
  faq: HospitalFAQData
  cta: HospitalCTAData
  similar: HospitalSimilarData
}

// ─── Empty defaults ────────────────────────────────────────────────────────────

function emptyLocale(): LocaleContent {
  return {
    hospitalName: "",
    hospitalLocation: "",
    hospitalType: "",
    hero: {
      virtualTourUrl: "",
      heroStats: [],
      galleryImages: [],
    },
    about: { eyebrow: "", title: "", description: "", aboutStats: [] },
    gallery: { eyebrow: "", title: "", categories: [], images: [], videos: [] },
    departments: { eyebrow: "", title: "", subtitle: "", departments: [] },
    doctors: { eyebrow: "", title: "", primaryButtonText: "", primaryButtonLink: "", doctorIds: [] },
    accreditation: { eyebrow: "", title: "", subtitle: "", accreditations: [] },
    technology: { eyebrow: "", title: "", subtitle: "", technologies: [] },
    visitProcess: { eyebrow: "", title: "", subtitle: "", steps: [] },
    reviews: { eyebrow: "", title: "", reviews: [] },
    location: {
      eyebrow: "", title: "", googleMapsUrl: "", contactInfoCardTitle: "", contactInfo: [],
      contactButtonIcon: "", contactButtonText: "", contactButtonLink: "",
      extraCardTitle: "", extraCard: [],
    },
    packages: { eyebrow: "", title: "", subtitle: "" },
    faq: { eyebrow: "", title: "", faqs: [] },
    cta: {
      eyebrow: "", title: "", subtitle: "", features: [],
      buttonIcon: "", buttonText: "", buttonLink: "",
      formTitle: "", fullNameLabel: "", phoneLabel: "", emailLabel: "",
      procedureLabel: "", procedures: [], messageLabel: "",
      formButtonIcon: "", formButtonText: "", formButtonLink: "", endOfFormLabel: "",
    },
    similar: { eyebrow: "", title: "", primaryButtonText: "", primaryButtonLink: "" },
  }
}

interface HospitalFormState {
  categoryId: string
  basicInfo: HospitalBasicInfoStoredFields
  translations: {
    en: LocaleContent
    ar: LocaleContent
    tr: LocaleContent
  }
}

function normalizeHeroFromDb(
  hero: unknown,
  normalizeGallery: (value: unknown) => { image: string; imagePublicId: string }[]
): HospitalHeroData {
  const h = hero && typeof hero === "object" ? (hero as Record<string, unknown>) : {}
  return {
    virtualTourUrl: typeof h.virtualTourUrl === "string" ? h.virtualTourUrl : "",
    heroStats: [],
    galleryImages: normalizeGallery(h.galleryImages),
  }
}

const emptyState: HospitalFormState = {
  categoryId: "",
  basicInfo: {
    slug: "", image: "", imagePublicId: "",
    rating: "", reviewCount: "", badge: "",
    foundedYear: "",
    bedsCount: "",
    departmentsCount: "",
    doctorsCount: "",
    patientsPerYear: "",
    isFeatured: false,
  },
  translations: {
    en: emptyLocale(),
    ar: emptyLocale(),
    tr: emptyLocale(),
  },
}

// ─── Section component ────────────────────────────────────────────────────────

interface SectionProps {
  id: string
  icon: React.ReactNode
  title: string
  description: string
  accent: "navy" | "green"
  children: React.ReactNode
  footer?: React.ReactNode
}

function Section({ id, icon, title, description, accent, children, footer }: SectionProps) {
  const bg = accent === "navy" ? "rgba(29,45,104,0.02)" : "rgba(43,182,115,0.02)"
  const iconBg = accent === "navy" ? "rgba(29,45,104,0.08)" : "rgba(43,182,115,0.10)"
  const iconColor = accent === "navy" ? "var(--brand-navy)" : "var(--brand-green)"

  return (
    <section className="bg-card rounded-2xl border border-border overflow-hidden" aria-labelledby={id}>
      <div className="flex items-center gap-3 px-6 py-4 border-b border-border" style={{ background: bg }}>
        <div className="w-8 h-8 rounded-xl flex items-center justify-center shrink-0" style={{ background: iconBg }}>
          <span style={{ color: iconColor }} aria-hidden="true">{icon}</span>
        </div>
        <div>
          <h2 id={id} className="text-sm font-bold text-foreground font-sans">{title}</h2>
          <p className="text-xs text-muted-foreground font-sans">{description}</p>
        </div>
      </div>
      <div className="p-6">{children}</div>
      {footer}
    </section>
  )
}

type HospitalSectionKey =
  | "basic"
  | "about"
  | "gallery"
  | "departments"
  | "doctors"
  | "accreditation"
  | "technology"
  | "visitProcess"
  | "reviews"
  | "location"
  | "packages"
  | "faq"
  | "cta"
  | "similar"

const inputClass =
  "w-full bg-card border border-border rounded-xl px-4 py-2.5 text-sm text-foreground font-sans placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673] transition-colors"

// ─── Gallery uploader (copied locally for Basic Information) ────────────────

function GalleryUploader({
  value,
  onChange,
  getHospitalSlug,
  onStageHeroGallery,
  onClearStagedHeroGallery,
}: {
  value: { image: string; imagePublicId: string }[]
  onChange: (items: { image: string; imagePublicId: string }[]) => void
  getHospitalSlug?: () => string
  onStageHeroGallery?: (index: number, staged: StagedImage) => void
  onClearStagedHeroGallery?: (index: number) => void
}) {
  const inputRef = useRef<HTMLInputElement>(null)
  const [error, setError] = useState<string | null>(null)

  function handleFiles(files: FileList | File[]) {
    setError(null)
    const hospitalSlug = getHospitalSlug?.().trim() ?? ""
    if (!hospitalSlug) {
      setError("Please enter the hospital slug before selecting images.")
      return
    }
    const incoming = Array.from(files)
    const next = [...value]
    let baseIndex = value.length
    try {
      for (const file of incoming) {
        if (!file.type.startsWith("image/")) {
          setError("Please upload a valid image.")
          continue
        }
        if (file.size > 5 * 1024 * 1024) {
          setError("Image size must be 5 MB or less.")
          continue
        }
        const index = baseIndex
        baseIndex += 1
        const staged = stageImage(file, {
          maxBytes: 5 * 1024 * 1024,
          fileBaseName: MEDIA_FILE_BASE.heroGallery,
          fileIndex: index,
        })
        onStageHeroGallery?.(index, staged)
        next.push({ image: staged.previewUrl, imagePublicId: "" })
      }
      if (next.length > value.length) onChange(next)
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to prepare images.")
    }
  }

  return (
    <div className="flex flex-col gap-3">
      <label className="text-xs font-bold text-foreground font-sans uppercase tracking-wider">
        Gallery Images
      </label>
      <div className="flex flex-wrap gap-3">
        {value.map((item, idx) => (
          <div key={idx} className="relative w-24 h-20 rounded-xl overflow-hidden border border-border bg-muted shrink-0">
            <img src={item.image} alt="Gallery" className="w-full h-full object-cover" />
            <button
              type="button"
              onClick={() => {
                onClearStagedHeroGallery?.(idx)
                onChange(value.filter((_, i) => i !== idx))
              }}
              className="absolute top-1 right-1 w-6 h-6 rounded-md bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors cursor-pointer"
              aria-label="Remove image"
            >
              <X className="w-3 h-3" aria-hidden="true" />
            </button>
          </div>
        ))}
        <button
          type="button"
          onClick={() => inputRef.current?.click()}
          className="flex flex-col items-center justify-center gap-1.5 w-24 h-20 rounded-xl border-2 border-dashed cursor-pointer transition-all shrink-0"
          style={{ borderColor: "var(--border)", background: "var(--card)" }}
          aria-label="Add gallery image"
        >
          <ImagePlus className="w-5 h-5 text-muted-foreground" aria-hidden="true" />
          <span className="text-[10px] text-muted-foreground font-sans">Add Image</span>
        </button>
      </div>
      {error && <p className="text-xs text-red-500 font-sans">{error}</p>}
      <input
        ref={inputRef}
        type="file"
        multiple
        accept="image/*"
        className="sr-only"
        aria-hidden="true"
        onChange={(e) => {
          const files = e.target.files
          if (files && files.length > 0) void handleFiles(files)
          e.target.value = ""
        }}
      />
    </div>
  )
}

// ─── Main form ────────────────────────────────────────────────────────────────

interface HospitalFormProps {
  hospitalId?: string
  onSuccess?: () => void
  cancelHref?: string
}

export function HospitalForm({ hospitalId, onSuccess, cancelHref = "/dashboard/hospitals" }: HospitalFormProps) {
  const router = useRouter()
  const [form, setForm] = useState<HospitalFormState>(emptyState)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loadingHospital, setLoadingHospital] = useState(!!hospitalId)
  const [createdHospitalId, setCreatedHospitalId] = useState<string | null>(null)
  const [activeLocale, setActiveLocale] = useState<Language>("en")
  const sharedFieldsLocked = activeLocale !== "en"
  const [pendingAction, setPendingAction] = useState<"draft" | "published" | null>(null)
  const [savingSectionKey, setSavingSectionKey] = useState<HospitalSectionKey | null>(null)
  const [sectionFeedback, setSectionFeedback] = useState<
    Partial<Record<HospitalSectionKey, { type: "success" | "error"; message: string }>>
  >({})
  const sectionFeedbackTimersRef = useRef<Partial<Record<HospitalSectionKey, ReturnType<typeof setTimeout>>>>({})
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [submitSuccess, setSubmitSuccess] = useState<string | null>(null)
  const [slugAvailable, setSlugAvailable] = useState<boolean | null>(null)
  const [checkingSlug, setCheckingSlug] = useState(false)
  const [slugError, setSlugError] = useState<string | null>(null)
  const pendingImagesRef = useRef(createEmptyHospitalPendingImages())
  /** Slug from server — updated after each successful save. */
  const loadedHospitalSlugRef = useRef("")

  const locale = form.translations[activeLocale]

  function getHospitalSlug() {
    return form.basicInfo.slug.trim()
  }

  function handleStageMainPhoto(staged: StagedImage) {
    if (pendingImagesRef.current.mainPhoto) {
      revokeStagedImage(pendingImagesRef.current.mainPhoto)
    }
    pendingImagesRef.current.mainPhoto = staged
  }

  function handleClearStagedMainPhoto() {
    if (pendingImagesRef.current.mainPhoto) {
      revokeStagedImage(pendingImagesRef.current.mainPhoto)
      pendingImagesRef.current.mainPhoto = null
    }
  }

  function handleStageHeroGallery(index: number, staged: StagedImage) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.heroGallery.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.heroGallery.set(key, staged)
  }

  function handleClearStagedHeroGallery(index: number) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.heroGallery.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.heroGallery.delete(key)
  }

  function handleStageGalleryImage(index: number, staged: StagedImage) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.galleryImages.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.galleryImages.set(key, staged)
  }

  function handleClearStagedGalleryImage(index: number) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.galleryImages.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.galleryImages.delete(key)
  }

  function handleStageAccreditationLogo(index: number, staged: StagedImage) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.accreditationLogo.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.accreditationLogo.set(key, staged)
  }

  function handleClearStagedAccreditationLogo(index: number) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.accreditationLogo.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.accreditationLogo.delete(key)
  }

  function handleStageAccreditationCertificate(index: number, staged: StagedImage) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.accreditationCertificate.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.accreditationCertificate.set(key, staged)
  }

  function handleClearStagedAccreditationCertificate(index: number) {
    const key = hospitalPendingKey(activeLocale, index)
    const existing = pendingImagesRef.current.accreditationCertificate.get(key)
    if (existing) revokeStagedImage(existing)
    pendingImagesRef.current.accreditationCertificate.delete(key)
  }

  useEffect(() => {
    return () => clearHospitalPendingImages(pendingImagesRef.current)
  }, [])

  async function checkSlugAvailability(slug: string) {
    const normalized = slug.trim()
    const localValidation = validateUrlSlug(normalized)
    if (!localValidation.valid) {
      setSlugAvailable(false)
      setSlugError(localValidation.error)
      return false
    }

    try {
      setCheckingSlug(true)
      setSlugError(null)
      const effectiveHospitalId = hospitalId ?? createdHospitalId
      const url =
        `/api/hospitals/check-slug?slug=${encodeURIComponent(normalized)}` +
        (effectiveHospitalId ? `&excludeId=${encodeURIComponent(effectiveHospitalId)}` : "")
      const res = await fetch(url)
      const json = await res.json().catch(() => ({}))
      const available = !!json?.available
      setSlugAvailable(available)
      if (!available) {
        setSlugError(typeof json?.error === "string" ? json.error : "Slug already in use")
      }
      return available
    } catch {
      setSlugAvailable(false)
      setSlugError("Failed to check slug availability")
      return false
    } finally {
      setCheckingSlug(false)
    }
  }

  useEffect(() => {
    if (!hospitalId) {
      setLoadingHospital(false)
      return
    }
    let cancelled = false
    async function loadHospital() {
      setLoadingHospital(true)
      setLoadError(null)
      try {
        const res = await fetch(`/api/admin/hospitals/${hospitalId}`, { cache: "no-store" })
        const json = await res.json().catch(() => ({}))
        if (!res.ok || json?.success === false) {
          throw new Error(typeof json?.error === "string" ? json.error : "Failed to load hospital")
        }
        const loadedForm = json?.hospital?.form
        if (!cancelled && loadedForm && typeof loadedForm === "object") {
          const raw = { ...(loadedForm as Record<string, unknown>) }
          delete raw.tags
          const rawForm = (raw as unknown as HospitalFormState) ?? emptyState
          const next: HospitalFormState = {
            ...rawForm,
            basicInfo: { ...emptyState.basicInfo, ...rawForm.basicInfo },
          }
          const normalizeGallery = (value: unknown): { image: string; imagePublicId: string }[] => {
            if (!Array.isArray(value)) return []
            return value
              .map((item) => {
                if (typeof item === "string") return { image: item, imagePublicId: "" }
                if (item && typeof item === "object") {
                  const rec = item as Record<string, unknown>
                  return {
                    image: typeof rec.image === "string" ? rec.image : "",
                    imagePublicId: typeof rec.imagePublicId === "string" ? rec.imagePublicId : "",
                  }
                }
                return { image: "", imagePublicId: "" }
              })
              .filter((item) => item.image !== "")
          }
          setForm({
            ...next,
            translations: {
              ...next.translations,
              en: {
                ...next.translations.en,
                hospitalType:
                  typeof next.translations.en.hospitalType === "string" ? next.translations.en.hospitalType : "",
                hero: normalizeHeroFromDb(next.translations.en.hero, normalizeGallery),
              },
              ar: {
                ...next.translations.ar,
                hospitalType:
                  typeof next.translations.ar.hospitalType === "string" ? next.translations.ar.hospitalType : "",
                hero: normalizeHeroFromDb(next.translations.ar.hero, normalizeGallery),
              },
              tr: {
                ...next.translations.tr,
                hospitalType:
                  typeof next.translations.tr.hospitalType === "string" ? next.translations.tr.hospitalType : "",
                hero: normalizeHeroFromDb(next.translations.tr.hero, normalizeGallery),
              },
            },
          })
          loadedHospitalSlugRef.current =
            typeof next.basicInfo.slug === "string" ? next.basicInfo.slug.trim() : ""
        }
      } catch (error) {
        if (!cancelled) {
          setLoadError(error instanceof Error ? error.message : "Failed to load hospital")
          setForm(emptyState)
        }
      } finally {
        if (!cancelled) setLoadingHospital(false)
      }
    }
    void loadHospital()
    return () => {
      cancelled = true
    }
  }, [hospitalId])

  useEffect(() => {
    return () => {
      for (const timer of Object.values(sectionFeedbackTimersRef.current)) {
        if (timer) clearTimeout(timer)
      }
    }
  }, [])

  function getSectionTitle(sectionKey: HospitalSectionKey) {
    switch (sectionKey) {
      case "basic":
        return "Basic Information"
      case "about":
        return "About Hospital"
      case "gallery":
        return "Gallery"
      case "departments":
        return "Departments"
      case "doctors":
        return "Doctors Section"
      case "accreditation":
        return "Accreditation & Certifications"
      case "technology":
        return "Equipment & Technology"
      case "visitProcess":
        return "Visit Process"
      case "reviews":
        return "Patient Reviews"
      case "location":
        return "Location & Logistics"
      case "packages":
        return "Packages Section"
      case "faq":
        return "FAQ"
      case "cta":
        return "CTA Section"
      case "similar":
        return "Similar Hospitals"
      default:
        return sectionKey
    }
  }

  function showSectionFeedback(sectionKey: HospitalSectionKey, type: "success" | "error", message: string) {
    const existingTimer = sectionFeedbackTimersRef.current[sectionKey]
    if (existingTimer) clearTimeout(existingTimer)
    setSectionFeedback((prev) => ({
      ...prev,
      [sectionKey]: { type, message },
    }))
    sectionFeedbackTimersRef.current[sectionKey] = setTimeout(() => {
      setSectionFeedback((prev) => {
        const next = { ...prev }
        delete next[sectionKey]
        return next
      })
      delete sectionFeedbackTimersRef.current[sectionKey]
    }, 3500)
  }

  function setLocale(patch: Partial<LocaleContent>) {
    setForm((prev) => ({
      ...prev,
      translations: {
        ...prev.translations,
        [activeLocale]: { ...prev.translations[activeLocale], ...patch },
      },
    }))
  }

  async function runSubmit(
    status: "draft" | "published",
    options?: { callOnSuccess?: boolean; suppressGlobalFeedback?: boolean }
  ) {
    const callOnSuccess = options?.callOnSuccess !== false
    const suppressGlobalFeedback = options?.suppressGlobalFeedback ?? false
    const effectiveHospitalId = hospitalId ?? createdHospitalId
    const isCreating = !hospitalId && !createdHospitalId

    if (!suppressGlobalFeedback) {
      setSubmitError(null)
      setSubmitSuccess(null)
    }
    setPendingAction(status)
    try {
      const requestedSlug = form.basicInfo.slug?.trim() ?? ""
      const localValidation = validateUrlSlug(requestedSlug)
      if (!localValidation.valid) {
        const msg = localValidation.error ?? "Invalid slug."
        if (!suppressGlobalFeedback) setSubmitError(msg)
        if (suppressGlobalFeedback) throw new Error(msg)
        setPendingAction(null)
        return
      }

      let available = slugAvailable
      if (available === null) {
        available = await checkSlugAvailability(requestedSlug)
      }
      if (!available) {
        const msg = slugError ?? "Slug already in use."
        if (!suppressGlobalFeedback) setSubmitError(msg)
        if (suppressGlobalFeedback) throw new Error(msg)
        setPendingAction(null)
        return
      }

      let basicInfoForSave = form.basicInfo
      let translationsForSave = form.translations

      if (hospitalPendingHasAny(pendingImagesRef.current)) {
        const hospitalSlug = getHospitalSlug()
        if (!hospitalSlug) {
          const msg = "Hospital slug is required before saving images."
          if (!suppressGlobalFeedback) setSubmitError(msg)
          if (suppressGlobalFeedback) throw new Error(msg)
          setPendingAction(null)
          return
        }

        const committed = await commitPendingHospitalImages(
          {
            basicInfo: form.basicInfo,
            translations: {
              en: {
                hero: form.translations.en.hero,
                gallery: form.translations.en.gallery,
                accreditation: form.translations.en.accreditation,
              },
              ar: {
                hero: form.translations.ar.hero,
                gallery: form.translations.ar.gallery,
                accreditation: form.translations.ar.accreditation,
              },
              tr: {
                hero: form.translations.tr.hero,
                gallery: form.translations.tr.gallery,
                accreditation: form.translations.tr.accreditation,
              },
            },
          },
          {
            hospitalSlug,
            hospitalId: effectiveHospitalId ?? undefined,
            pending: pendingImagesRef.current,
          }
        )
        basicInfoForSave = committed.basicInfo
        translationsForSave = {
          en: {
            ...form.translations.en,
            hero: committed.translations.en.hero,
            gallery: committed.translations.en.gallery,
            accreditation: committed.translations.en.accreditation,
          },
          ar: {
            ...form.translations.ar,
            hero: committed.translations.ar.hero,
            gallery: committed.translations.ar.gallery,
            accreditation: committed.translations.ar.accreditation,
          },
          tr: {
            ...form.translations.tr,
            hero: committed.translations.tr.hero,
            gallery: committed.translations.tr.gallery,
            accreditation: committed.translations.tr.accreditation,
          },
        }
        setForm((prev) => ({
          ...prev,
          basicInfo: basicInfoForSave,
          translations: translationsForSave,
        }))
      }

      const payload = { ...form, basicInfo: basicInfoForSave, translations: translationsForSave, status }
      const url = effectiveHospitalId ? `/api/admin/hospitals/${effectiveHospitalId}` : "/api/admin/hospitals"
      const method = effectiveHospitalId ? "PUT" : "POST"
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.success === false) {
        throw new Error(typeof json?.error === "string" ? json.error : "Save failed")
      }

      const newId =
        typeof json?.hospital?.id === "string"
          ? json.hospital.id
          : typeof json?.id === "string"
            ? json.id
            : null
      if (isCreating && typeof newId === "string") {
        setCreatedHospitalId(newId)
      }

      const savedForm = json?.hospital?.form
      if (savedForm && typeof savedForm === "object") {
        setForm((prev) => mergeHospitalFormMediaFromSavedForm(prev, savedForm))
      }

      loadedHospitalSlugRef.current = requestedSlug

      if (!suppressGlobalFeedback) {
        setSubmitSuccess(status === "draft" ? "Saved as draft." : "Hospital published successfully.")
      }
      if (callOnSuccess) {
        if (onSuccess) {
          onSuccess()
        } else {
          router.push(cancelHref)
        }
      }
    } catch (error) {
      if (!suppressGlobalFeedback) {
        setSubmitError(error instanceof Error ? error.message : "An error occurred while saving.")
      }
      if (suppressGlobalFeedback) throw error instanceof Error ? error : new Error("Save failed")
    } finally {
      setPendingAction(null)
    }
  }

  if (hospitalId && loadingHospital) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 rounded-2xl border border-border bg-card py-24" role="status" aria-live="polite">
        <Loader2 className="w-10 h-10 animate-spin text-[var(--brand-navy)]" aria-hidden="true" />
        <p className="text-sm text-muted-foreground font-sans">Loading hospital…</p>
      </div>
    )
  }

  if (hospitalId && loadError) {
    return (
      <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-4 text-sm text-red-800 font-sans" role="alert">
        {loadError}
      </div>
    )
  }

  async function handleSaveSection(sectionKey: HospitalSectionKey) {
    setSavingSectionKey(sectionKey)
    try {
      await runSubmit("draft", {
        suppressGlobalFeedback: true,
        callOnSuccess: false,
      })
      showSectionFeedback(sectionKey, "success", `${getSectionTitle(sectionKey)} saved successfully.`)
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to save section."
      showSectionFeedback(sectionKey, "error", `Failed to save ${getSectionTitle(sectionKey)}: ${msg}`)
    } finally {
      setSavingSectionKey(null)
    }
  }

  function renderSectionSaveButton(sectionKey: HospitalSectionKey) {
    const isSavingThisSection = savingSectionKey === sectionKey
    const feedback = sectionFeedback[sectionKey]

    return (
      <div className="flex flex-col items-end gap-2 px-6 pb-6 pt-0">
        <button
          type="button"
          onClick={() => void handleSaveSection(sectionKey)}
          disabled={pendingAction !== null}
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold font-sans text-white transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          style={{ background: "var(--brand-navy)" }}
        >
          {isSavingThisSection ? (
            <>
              <Loader2 className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />
              Saving section...
            </>
          ) : (
            <>
              <Save className="w-3.5 h-3.5" aria-hidden="true" />
              Save Section
            </>
          )}
        </button>
        {feedback ? (
          <div
            className="text-xs font-sans px-3 py-1.5 rounded-lg border max-w-[420px]"
            style={
              feedback.type === "success"
                ? { background: "rgba(43,182,115,0.08)", borderColor: "rgba(43,182,115,0.30)", color: "var(--brand-green)" }
                : { background: "rgba(239,68,68,0.08)", borderColor: "rgba(239,68,68,0.30)", color: "#dc2626" }
            }
            role="alert"
          >
            {feedback.message}
          </div>
        ) : null}
      </div>
    )
  }

  return (
    <form
      onSubmit={(e) => { e.preventDefault(); void runSubmit("published") }}
      className="flex flex-col gap-6"
      noValidate
    >

      {/* Section 1 — Basic Information */}
      <Section
        id="section-basic"
        icon={<Building2 className="w-4 h-4" />}
        title="Basic Information"
        description="Hospital name, image, slug, type, facility metrics, virtual tour, and hero gallery"
        accent="navy"
        footer={renderSectionSaveButton("basic")}
      >
        <div className="flex flex-col gap-5">
          <div className="flex items-center gap-2 rounded-xl border border-border bg-muted/30 p-1">
            {([
              { locale: "en", label: "English" },
              { locale: "ar", label: "Arabic" },
              { locale: "tr", label: "Turkish" },
            ] as const).map((tab) => (
              <button
                key={tab.locale}
                type="button"
                onClick={() => setActiveLocale(tab.locale)}
                className="px-3 py-1.5 rounded-lg text-xs font-semibold font-sans transition-colors cursor-pointer"
                style={
                  activeLocale === tab.locale
                    ? { background: "var(--brand-green)", color: "#fff" }
                    : { color: "var(--muted-foreground)" }
                }
              >
                {tab.label}
              </button>
            ))}
          </div>
          <div className="grid  gap-4">
            <CategorySelect
              value={form.categoryId}
              onChange={(v) => setForm((prev) => ({ ...prev, categoryId: v }))}
              disabled={sharedFieldsLocked}
              placeholder="Select hospital category..."
              nativeRequired={false}
            />
          </div>

          <HospitalBasicInfo
            value={{
              ...form.basicInfo,
              name: form.translations[activeLocale].hospitalName,
              location: form.translations[activeLocale].hospitalLocation,
              type: form.translations[activeLocale].hospitalType,
            }}
            onChange={(v) => {
              setForm((prev) => ({
                ...prev,
                basicInfo:
                  activeLocale === "en"
                    ? {
                        slug: v.slug,
                        image: v.image,
                        imagePublicId: v.imagePublicId,
                        rating: v.rating,
                        reviewCount: v.reviewCount,
                        badge: v.badge,
                        foundedYear: v.foundedYear,
                        bedsCount: v.bedsCount,
                        departmentsCount: v.departmentsCount,
                        doctorsCount: v.doctorsCount,
                        patientsPerYear: v.patientsPerYear,
                        isFeatured: v.isFeatured,
                      }
                    : prev.basicInfo,
                translations: {
                  ...prev.translations,
                  [activeLocale]: {
                    ...prev.translations[activeLocale],
                    hospitalName: v.name,
                    hospitalLocation: v.location,
                    hospitalType: v.type,
                  },
                },
              }))
              setSlugAvailable(null)
              const localValidation = validateUrlSlug(v.slug)
              setSlugError(localValidation.valid ? null : localValidation.error)
            }}
            onSlugBlur={(value) => {
              void checkSlugAvailability(value)
            }}
            checkingSlug={checkingSlug}
            slugError={slugError}
            slugAvailable={slugAvailable}
            sharedFieldsLocked={sharedFieldsLocked}
            getHospitalSlug={getHospitalSlug}
            onStageMainPhoto={handleStageMainPhoto}
            onClearStagedMainPhoto={handleClearStagedMainPhoto}
          />

          {/* Virtual tour + hero gallery (hero stats removed — use Basic Information metrics instead) */}
          <div className="flex flex-col gap-3">
            <div className="flex flex-col gap-1.5">
              <label htmlFor="hero-virtual-tour" className="text-xs font-bold text-foreground font-sans uppercase tracking-wider flex items-center gap-1">
                Virtual Tour URL
              </label>
              <input
                id="hero-virtual-tour"
                type="url"
                value={locale.hero.virtualTourUrl}
                onChange={(e) => setLocale({ hero: { ...locale.hero, virtualTourUrl: e.target.value } })}
                placeholder="https://..."
                className={inputClass}
              />
            </div>

            <GalleryUploader
              value={locale.hero.galleryImages}
              onChange={(urls) => setLocale({ hero: { ...locale.hero, galleryImages: urls } })}
              getHospitalSlug={getHospitalSlug}
              onStageHeroGallery={handleStageHeroGallery}
              onClearStagedHeroGallery={handleClearStagedHeroGallery}
            />
          </div>

        </div>
      </Section>

      {/* Hero Section moved into Basic Information */}

      {/* Section 3 — About Hospital */}
      <Section
        id="section-about"
        icon={<Building2 className="w-4 h-4" />}
        title="About Hospital"
        description="Description, key stats, and hospital overview"
        accent="navy"
        footer={renderSectionSaveButton("about")}
      >
        <HospitalAboutSection value={locale.about} onChange={(v) => setLocale({ about: v })} />
      </Section>

      {/* Section 4 — Gallery */}
      <Section
        id="section-gallery"
        icon={<LayoutGrid className="w-4 h-4" />}
        title="Gallery"
        description="Photo gallery with categories, images, and videos"
        accent="green"
        footer={renderSectionSaveButton("gallery")}
      >
        <HospitalGallerySection
          value={locale.gallery}
          onChange={(v) => setLocale({ gallery: v })}
          getHospitalSlug={getHospitalSlug}
          onStageGalleryImage={handleStageGalleryImage}
          onClearStagedGalleryImage={handleClearStagedGalleryImage}
        />
      </Section>

      {/* Section 5 — Departments */}
      <Section
        id="section-departments"
        icon={<LayoutGrid className="w-4 h-4" />}
        title="Departments"
        description="Medical departments and specialties offered at this hospital"
        accent="navy"
        footer={renderSectionSaveButton("departments")}
      >
        <HospitalDepartmentsSection value={locale.departments} onChange={(v) => setLocale({ departments: v })} />
      </Section>

      {/* Section 6 — Doctors */}
      <Section
        id="section-doctors"
        icon={<Users className="w-4 h-4" />}
        title="Doctors Section"
        description="Section heading and button for the doctors listing on this hospital page"
        accent="green"
        footer={renderSectionSaveButton("doctors")}
      >
        <HospitalDoctorsSection
          value={locale.doctors}
          onChange={(v) => setLocale({ doctors: v })}
          doctorNameLocale={activeLocale}
        />
      </Section>

      {/* Section 7 — Accreditation */}
      <Section
        id="section-accreditation"
        icon={<Award className="w-4 h-4" />}
        title="Accreditation & Certifications"
        description="International accreditations and quality certifications"
        accent="navy"
        footer={renderSectionSaveButton("accreditation")}
      >
        <HospitalAccreditationSection
          value={locale.accreditation}
          onChange={(v) => setLocale({ accreditation: v })}
          getHospitalSlug={getHospitalSlug}
          onStageAccreditationLogo={handleStageAccreditationLogo}
          onClearStagedAccreditationLogo={handleClearStagedAccreditationLogo}
          onStageAccreditationCertificate={handleStageAccreditationCertificate}
          onClearStagedAccreditationCertificate={handleClearStagedAccreditationCertificate}
        />
      </Section>

      {/* Section 8 — Equipment & Technology */}
      <Section
        id="section-technology"
        icon={<Cpu className="w-4 h-4" />}
        title="Equipment & Technology"
        description="Medical equipment and advanced technologies available at this hospital"
        accent="green"
        footer={renderSectionSaveButton("technology")}
      >
        <HospitalTechnologySection value={locale.technology} onChange={(v) => setLocale({ technology: v })} />
      </Section>

      {/* Section 9 — Visit Process */}
      <Section
        id="section-visit-process"
        icon={<Route className="w-4 h-4" />}
        title="Visit Process"
        description="Step-by-step process for patients visiting this hospital"
        accent="navy"
        footer={renderSectionSaveButton("visitProcess")}
      >
        <HospitalVisitProcessSection value={locale.visitProcess} onChange={(v) => setLocale({ visitProcess: v })} />
      </Section>

      {/* Section 10 — Reviews */}
      <Section
        id="section-reviews"
        icon={<MessageSquare className="w-4 h-4" />}
        title="Patient Reviews"
        description="Reviews and testimonials from patients treated at this hospital"
        accent="green"
        footer={renderSectionSaveButton("reviews")}
      >
        <HospitalReviewsSection value={locale.reviews} onChange={(v) => setLocale({ reviews: v })} />
      </Section>

      {/* Section 11 — Location & Logistics */}
      <Section
        id="section-location"
        icon={<MapPin className="w-4 h-4" />}
        title="Location & Logistics"
        description="Contact details, address, and additional logistics information"
        accent="navy"
        footer={renderSectionSaveButton("location")}
      >
        <HospitalLocationSection value={locale.location} onChange={(v) => setLocale({ location: v })} />
      </Section>

      {/* Section 12 — Packages */}
      <Section
        id="section-packages"
        icon={<Library className="w-4 h-4" />}
        title="Packages Section"
        description="Section heading for the hospital packages listing"
        accent="green"
        footer={renderSectionSaveButton("packages")}
      >
        <HospitalPackagesSection value={locale.packages} onChange={(v) => setLocale({ packages: v })} />
      </Section>

      {/* Section 13 — FAQ */}
      <Section
        id="section-faq"
        icon={<HelpCircle className="w-4 h-4" />}
        title="Frequently Asked Questions"
        description="Common questions and detailed answers about this hospital"
        accent="navy"
        footer={renderSectionSaveButton("faq")}
      >
        <HospitalFAQSection value={locale.faq} onChange={(v) => setLocale({ faq: v })} />
      </Section>

      {/* Section 14 — CTA */}
      <Section
        id="section-cta"
        icon={<Megaphone className="w-4 h-4" />}
        title="CTA Section"
        description="Call-to-action section with contact form and features list"
        accent="green"
        footer={renderSectionSaveButton("cta")}
      >
        <HospitalCTASection value={locale.cta} onChange={(v) => setLocale({ cta: v })} />
      </Section>

      {/* Section 15 — Similar Hospitals */}
      <Section
        id="section-similar"
        icon={<Building2 className="w-4 h-4" />}
        title="Similar Hospitals"
        description="Section heading for related hospitals shown at the bottom of the page"
        accent="navy"
        footer={renderSectionSaveButton("similar")}
      >
        <HospitalSimilarSection value={locale.similar} onChange={(v) => setLocale({ similar: v })} />
      </Section>

      {/* Actions */}
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 flex-wrap">
        <div className="flex-1 min-w-0">
          {submitError && (
            <div
              className="inline-flex items-start gap-2 px-4 py-2.5 rounded-xl text-sm font-sans"
              style={{ background: "rgba(239,68,68,0.08)", color: "#ef4444", border: "1px solid rgba(239,68,68,0.20)" }}
              role="alert"
            >
              {submitError}
            </div>
          )}
          {submitSuccess && (
            <div
              className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-sans"
              style={{ background: "rgba(43,182,115,0.08)", color: "var(--brand-green)", border: "1px solid rgba(43,182,115,0.20)" }}
              role="status"
            >
              {submitSuccess}
            </div>
          )}
        </div>

        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 shrink-0">
          <button
            type="button"
            onClick={() => router.push(cancelHref)}
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-sm font-semibold font-sans border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Cancel
          </button>

          <button
            type="button"
            onClick={() => void runSubmit("draft")}
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed disabled:active:scale-100 border border-transparent"
            style={{ background: "var(--brand-navy)", boxShadow: "0 2px 8px rgba(29,45,104,0.25)" }}
          >
            {pendingAction === "draft" ? (
              <div className="w-4 h-4 rounded-full border-2 border-t-transparent animate-spin" style={{ borderColor: "rgba(255,255,255,0.8) transparent rgba(255,255,255,0.8) rgba(255,255,255,0.8)" }} aria-hidden="true" />
            ) : (
              <Save className="w-4 h-4" aria-hidden="true" />
            )}
            {pendingAction === "draft" ? "Saving…" : "Save as Draft"}
          </button>

          <button
            type="submit"
            disabled={pendingAction !== null}
            className="flex cursor-pointer items-center justify-center gap-2 px-6 py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed disabled:active:scale-100"
            style={{ background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.3)" }}
          >
            {pendingAction === "published" ? (
              <div className="w-4 h-4 rounded-full border-2 border-t-transparent animate-spin" style={{ borderColor: "rgba(255,255,255,0.8) transparent rgba(255,255,255,0.8) rgba(255,255,255,0.8)" }} aria-hidden="true" />
            ) : (
              <Send className="w-4 h-4" aria-hidden="true" />
            )}
            {pendingAction === "published" ? "Publishing…" : "Publish Hospital"}
          </button>
        </div>
      </div>
    </form>
  )
}
