"use client"

import React, { useEffect, useState } from "react"
import {
  Sparkles,
  SlidersHorizontal,
  ShieldCheck,
  Building2,
  HelpCircle,
  Megaphone,
  Save,
  Pencil,
  Loader2,
  AlertCircle,
  CheckCircle,
} from "lucide-react"

import { HospitalsPageHeroSection } from "./HospitalsPageHeroSection"
import { HospitalsPageFiltersSection } from "./HospitalsPageFiltersSection"
import { HospitalsPageAccreditationSection } from "./HospitalsPageAccreditationSection"
import { HospitalsPageWhySection } from "./HospitalsPageWhySection"
import { HospitalsPageFAQSection } from "./HospitalsPageFAQSection"
import { HospitalsPageCTASection } from "./HospitalsPageCTASection"
import { LanguageTabs, type Language } from "../shared/LanguageTabs"
import { HOSPITALS_PAGE_LOCALE_CODES } from "@/lib/pages/hospitals-page/locales"
import {
  createEmptyHospitalsPageFormState,
  type HospitalsPageFormStateShape,
} from "@/lib/pages/hospitals-page/form-types"
import {
  CmsPagePendingProvider,
  useCmsPagePendingRef,
} from "@/components/dashboard/cms-pages/CmsPagePendingContext"
import {
  clearAllCmsPending,
  commitPendingHospitalsPageLocales,
  cmsPendingHasAny,
} from "@/lib/media-manager/cms-page-pending"

// ─── Section wrapper ──────────────────────────────────────────────────────────

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 ? <div className="px-6 pb-6">{footer}</div> : null}
    </section>
  )
}

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

const LOCALE_CODES: Language[] = [...HOSPITALS_PAGE_LOCALE_CODES]

export function HospitalsPageForm() {
  const [activeLanguage, setActiveLanguage] = useState<Language>("en")
  return (
    <CmsPagePendingProvider activeLanguage={activeLanguage}>
      <HospitalsPageFormBody
        activeLanguage={activeLanguage}
        setActiveLanguage={setActiveLanguage}
      />
    </CmsPagePendingProvider>
  )
}

function HospitalsPageFormBody({
  activeLanguage,
  setActiveLanguage,
}: {
  activeLanguage: Language
  setActiveLanguage: (lang: Language) => void
}) {
  const [formByLanguage, setFormByLanguage] = useState<Record<Language, HospitalsPageFormStateShape>>({
    en: createEmptyHospitalsPageFormState(),
    tr: createEmptyHospitalsPageFormState(),
    ar: createEmptyHospitalsPageFormState(),
  })
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)

  const [savingSectionKey, setSavingSectionKey] = useState<keyof HospitalsPageFormStateShape | null>(null)
  const [saving, setSaving] = useState(false)
  const [isLockedForEditing, setIsLockedForEditing] = useState(false)
  const [sectionFeedback, setSectionFeedback] = useState<
    Partial<Record<keyof HospitalsPageFormStateShape, { type: "success" | "error"; message: string }>>
  >({})
  const sectionFeedbackTimersRef = React.useRef<
    Partial<Record<keyof HospitalsPageFormStateShape, ReturnType<typeof setTimeout>>>
  >({})

  const [saveSuccess, setSaveSuccess] = useState<string | null>(null)
  const [saveError, setSaveError] = useState<string | null>(null)
  const [englishValidationTouched, setEnglishValidationTouched] = useState(false)

  const isFormLocked = loading || saving || savingSectionKey !== null || isLockedForEditing
  const pendingImages = useCmsPagePendingRef()

  useEffect(() => {
    return () => clearAllCmsPending(pendingImages)
  }, [])

  async function commitPendingImagesIfAny(): Promise<Record<Language, HospitalsPageFormStateShape>> {
    if (!cmsPendingHasAny(pendingImages)) return buildPayload()
    const merged = await commitPendingHospitalsPageLocales(formByLanguage, pendingImages)
    setFormByLanguage(merged)
    return merged
  }

  function getEnglishValidationErrors() {
    const en = formByLanguage.en
    const heroStatErrors = en.hero.statistics.map((item) => ({
      icon: !item.icon.trim(),
      title: !item.title.trim(),
      subtitle: !item.subtitle.trim(),
      value: !item.value.trim(),
    }))
    const certErrors = en.hero.certifications.map((item) => ({
      title: !item.title.trim(),
      subtitle: !item.subtitle.trim(),
      image: !item.image.trim(),
    }))
    const accreditationItemErrors = en.accreditation.accreditationItems.map((item) => ({
      cardColor: !item.cardColor.trim(),
      icon: !item.icon.trim(),
      title: !item.title.trim(),
      subtitle: !item.subtitle.trim(),
      description: !item.description.trim(),
    }))
    const whyItemErrors = en.why.features.map((item) => ({
      icon: !item.icon.trim(),
      title: !item.title.trim(),
      description: !item.description.trim(),
    }))
    const faqItemErrors = en.faq.faqs.map((item) => ({
      question: !item.question.trim(),
      answer: !item.answer.trim(),
    }))
    const filterItemErrors = en.filters.filters.map((filter) => ({
      label: !filter.label.trim(),
      options: filter.options.length === 0 || filter.options.some((option) => !option.label.trim()),
      optionItems: filter.options.map((option) => ({ label: !option.label.trim() })),
    }))
    const sortOptionErrors = en.filters.sortOptions.map((option) => ({
      label: !option.label.trim(),
    }))
    return {
      hero: {
        icon: !en.hero.icon.trim(),
        eyebrow: !en.hero.eyebrow.trim(),
        title: !en.hero.title.trim(),
        description: !en.hero.description.trim(),
        image: !en.hero.image.trim(),
        statistics: en.hero.statistics.length === 0 || heroStatErrors.some((item) => item.icon || item.title || item.subtitle || item.value),
        statisticsItems: heroStatErrors,
        certifications: en.hero.certifications.length === 0 || certErrors.some((item) => item.title || item.subtitle || item.image),
        certificationsItems: certErrors,
      },
      filters: {
        filters: en.filters.filters.length === 0 || filterItemErrors.some((item) => item.label || item.options),
        filterItems: filterItemErrors,
        sortOptions: en.filters.sortOptions.length === 0 || sortOptionErrors.some((item) => item.label),
        sortOptionItems: sortOptionErrors,
      },
      accreditation: {
        title: !en.accreditation.title.trim(),
        subTitle: !en.accreditation.subTitle.trim(),
        accreditationItems: en.accreditation.accreditationItems.length === 0 || accreditationItemErrors.some((item) => item.cardColor || item.icon || item.title || item.subtitle || item.description),
        accreditationItemErrors,
      },
      why: {
        title: !en.why.title.trim(),
        subTitle: !en.why.subTitle.trim(),
        features: en.why.features.length === 0 || whyItemErrors.some((item) => item.icon || item.title || item.description),
        featureItems: whyItemErrors,
      },
      faq: {
        title: !en.faq.title.trim(),
        faqs: en.faq.faqs.length === 0 || faqItemErrors.some((item) => item.question || item.answer),
        faqItems: faqItemErrors,
      },
      cta: {
        eyebrow: !en.cta.eyebrow.trim(),
        title: !en.cta.title.trim(),
        subtitle: !en.cta.subtitle.trim(),
        primaryButtonIcon: !en.cta.primaryButtonIcon.trim(),
        primaryButtonText: !en.cta.primaryButtonText.trim(),
        primaryButtonLink: !en.cta.primaryButtonLink.trim(),
        secondaryButtonIcon: !en.cta.secondaryButtonIcon.trim(),
        secondaryButtonText: !en.cta.secondaryButtonText.trim(),
        secondaryButtonLink: !en.cta.secondaryButtonLink.trim(),
      },
    }
  }

  function hasEnglishValidationErrors() {
    const errors = getEnglishValidationErrors()
    return (
      errors.hero.icon ||
      errors.hero.eyebrow ||
      errors.hero.title ||
      errors.hero.description ||
      errors.hero.image ||
      errors.hero.statistics ||
      errors.hero.certifications ||
      errors.filters.filters ||
      errors.filters.sortOptions ||
      errors.accreditation.title ||
      errors.accreditation.subTitle ||
      errors.accreditation.accreditationItems ||
      errors.why.title ||
      errors.why.subTitle ||
      errors.why.features ||
      errors.faq.title ||
      errors.faq.faqs ||
      errors.cta.eyebrow ||
      errors.cta.title ||
      errors.cta.subtitle ||
      errors.cta.primaryButtonIcon ||
      errors.cta.primaryButtonText ||
      errors.cta.primaryButtonLink ||
      errors.cta.secondaryButtonIcon ||
      errors.cta.secondaryButtonText ||
      errors.cta.secondaryButtonLink
    )
  }

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch("/api/admin/hospitals-page", { credentials: "include" })
        const data: {
          success?: boolean
          error?: string
          locales?: Partial<Record<Language, HospitalsPageFormStateShape>>
        } = await res.json()
        if (cancelled) return
        if (!res.ok || !data.success) {
          setLoadError(data.error ?? "Failed to load hospitals page.")
          return
        }
        setFormByLanguage((prev) => {
          const next = { ...prev }
          for (const code of HOSPITALS_PAGE_LOCALE_CODES) {
            const chunk = data.locales?.[code]
            if (chunk?.hero) next[code] = chunk
          }
          return next
        })
      } catch {
        if (!cancelled) setLoadError("Failed to load hospitals page. Please try again.")
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    void load()
    return () => {
      cancelled = true
    }
  }, [])

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

  function showSectionFeedback(
    sectionKey: keyof HospitalsPageFormStateShape,
    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 updateSection<K extends keyof HospitalsPageFormStateShape>(
    key: K,
    value: HospitalsPageFormStateShape[K]
  ) {
    if (isFormLocked) return
    setFormByLanguage((prev) => ({
      ...prev,
      [activeLanguage]: { ...prev[activeLanguage], [key]: value },
    }))
    setSaveSuccess(null)
    setSaveError(null)
  }

  function buildPayload(): Record<Language, HospitalsPageFormStateShape> {
    return {
      en: { ...formByLanguage.en },
      tr: { ...formByLanguage.tr },
      ar: { ...formByLanguage.ar },
    }
  }

  async function refreshFromServer() {
    const refreshRes = await fetch("/api/admin/hospitals-page", { credentials: "include" })
    const refreshData: {
      success?: boolean
      error?: string
      locales?: Partial<Record<Language, HospitalsPageFormStateShape>>
    } = await refreshRes.json()
    if (!refreshRes.ok || !refreshData.success) {
      throw new Error(refreshData.error ?? "Failed to refresh latest data.")
    }
    if (refreshData.locales) {
      setFormByLanguage((prev) => {
        const next = { ...prev }
        for (const code of LOCALE_CODES) {
          const chunk = refreshData.locales?.[code]
          if (chunk) next[code] = chunk
        }
        return next
      })
    }
  }

  async function handleSave() {
    setEnglishValidationTouched(true)
    if (hasEnglishValidationErrors()) {
      setActiveLanguage("en")
      setSaveSuccess(null)
      setSaveError("Please fill all required English fields.")
      return
    }
    setSaving(true)
    setSaveSuccess(null)
    setSaveError(null)
    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/hospitals-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to save")
      await refreshFromServer()
      setSaveSuccess("Hospitals page saved successfully.")
      setIsLockedForEditing(true)
    } catch (error) {
      setActiveLanguage("en")
      setSaveError(error instanceof Error ? error.message : "Something went wrong. Please try again.")
    } finally {
      setSaving(false)
    }
  }

  async function handleSaveSection(sectionKey: keyof HospitalsPageFormStateShape) {
    setEnglishValidationTouched(true)
    setSavingSectionKey(sectionKey)
    setSaveSuccess(null)
    setSaveError(null)

    try {
      const payloadLocales = await commitPendingImagesIfAny()
      const res = await fetch("/api/admin/hospitals-page", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ locales: payloadLocales, sectionKey }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (!res.ok || !data.success) throw new Error(data.error ?? "Failed to save section")
      await refreshFromServer()
      setSaveSuccess(`${String(sectionKey)} section saved successfully.`)
      showSectionFeedback(sectionKey, "success", "Section saved successfully.")
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Something went wrong. Please try again."
      setActiveLanguage("en")
      showSectionFeedback(sectionKey, "error", errorMessage)
      setSaveError(errorMessage)
    } finally {
      setSavingSectionKey(null)
    }
  }

  function renderSectionSaveButton(sectionKey: keyof HospitalsPageFormStateShape) {
    const isSavingThisSection = savingSectionKey === sectionKey
    const feedback = sectionFeedback[sectionKey]
    return (
      <div className="flex flex-col items-end gap-2">
        <button
          type="button"
          onClick={() => void handleSaveSection(sectionKey)}
          disabled={isFormLocked}
          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] flex items-center gap-1.5"
            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.type === "success" ? (
              <CheckCircle className="w-3.5 h-3.5 shrink-0" aria-hidden="true" />
            ) : (
              <AlertCircle className="w-3.5 h-3.5 shrink-0" aria-hidden="true" />
            )}
            {feedback.message}
          </div>
        ) : null}
      </div>
    )
  }

  const form = formByLanguage[activeLanguage]

  return (
    <div className="flex flex-col gap-6">

      {saveError && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{ background: "rgba(239,68,68,0.06)", borderColor: "rgba(239,68,68,0.30)", color: "#dc2626" }}
          role="alert"
        >
          <AlertCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveError}
        </div>
      )}

      {saveSuccess && (
        <div
          className="flex items-center gap-3 px-4 py-3 rounded-xl border text-sm font-sans"
          style={{ background: "rgba(43,182,115,0.06)", borderColor: "rgba(43,182,115,0.30)", color: "var(--brand-green)" }}
          role="status"
        >
          <CheckCircle className="w-4 h-4 shrink-0" aria-hidden="true" />
          {saveSuccess}
        </div>
      )}

      {/* Language Tabs */}
      <div className="bg-card rounded-2xl border border-border overflow-hidden">
        <div
          className="flex items-center gap-2 px-6 py-3 border-b border-border"
          style={{ background: "rgba(29,45,104,0.02)" }}
        >
          <div
            className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0 text-sm"
            style={{ background: "rgba(29,45,104,0.08)" }}
            aria-hidden="true"
          >
            🌐
          </div>
          <div>
            <p className="text-sm font-bold font-sans" style={{ color: "var(--brand-navy)" }}>
              Page Language
            </p>
            <p className="text-xs text-muted-foreground font-sans leading-none mt-0.5">
              English is required to save. Turkish and Arabic are optional.
            </p>
          </div>
        </div>
        <div className="px-6 py-4">
          <LanguageTabs
            activeLanguage={activeLanguage}
            onChange={(lang) => {
              if (isFormLocked) return
              setActiveLanguage(lang)
            }}
            disabled={isFormLocked}
          />
        </div>
      </div>

      {/* Section 1 — Hero */}
      <Section
        id="section-hospitals-hero"
        icon={<Sparkles className="w-4 h-4" />}
        title="Hero Section"
        description="Icon, eyebrow, title, description, statistics, and certifications"
        accent="navy"
        footer={renderSectionSaveButton("hero")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageHeroSection
              value={form.hero}
              onChange={(v) => updateSection("hero", v)}
              isDefaultLanguage={activeLanguage === "en"}
              defaultSharedData={formByLanguage.en.hero}
              validation={
                activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().hero : undefined
              }
              disabled={isFormLocked}
            />
          </fieldset>
        )}
      </Section>

      {/* Section 2 — Filters */}
      <Section
        id="section-hospitals-filters"
        icon={<SlidersHorizontal className="w-4 h-4" />}
        title="Filters Section"
        description="Filterable options and sort options for the hospitals listing"
        accent="green"
        footer={renderSectionSaveButton("filters")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageFiltersSection
              value={form.filters}
              onChange={(v) => updateSection("filters", v)}
              validation={
                activeLanguage === "en" && englishValidationTouched
                  ? getEnglishValidationErrors().filters
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Section 3 — Accreditation Info */}
      <Section
        id="section-hospitals-accreditation"
        icon={<ShieldCheck className="w-4 h-4" />}
        title="Accreditation Info Section"
        description="Title, subtitle, and accreditation items with card color, icon, and description"
        accent="navy"
        footer={renderSectionSaveButton("accreditation")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageAccreditationSection
              value={form.accreditation}
              onChange={(v) => updateSection("accreditation", v)}
              validation={
                activeLanguage === "en" && englishValidationTouched
                  ? getEnglishValidationErrors().accreditation
                  : undefined
              }
            />
          </fieldset>
        )}
      </Section>

      {/* Section 4 — Why Our Hospitals */}
      <Section
        id="section-hospitals-why"
        icon={<Building2 className="w-4 h-4" />}
        title="Why Our Hospitals Section"
        description="Title, subtitle, and feature items with icon and description"
        accent="green"
        footer={renderSectionSaveButton("why")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageWhySection
              value={form.why}
              onChange={(v) => updateSection("why", v)}
              validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().why : undefined}
            />
          </fieldset>
        )}
      </Section>

      {/* Section 5 — FAQ */}
      <Section
        id="section-hospitals-faq"
        icon={<HelpCircle className="w-4 h-4" />}
        title="FAQ Section"
        description="Section title and repeatable question/answer pairs"
        accent="navy"
        footer={renderSectionSaveButton("faq")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageFAQSection
              value={form.faq}
              onChange={(v) => updateSection("faq", v)}
              validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().faq : undefined}
            />
          </fieldset>
        )}
      </Section>

      {/* Section 6 — Final CTA */}
      <Section
        id="section-hospitals-cta"
        icon={<Megaphone className="w-4 h-4" />}
        title="Final CTA Section"
        description="Eyebrow, title, subtitle, primary and secondary call-to-action buttons"
        accent="green"
        footer={renderSectionSaveButton("cta")}
      >
        {loading ? (
          <p className="text-sm text-muted-foreground font-sans">Loading...</p>
        ) : (
          <fieldset disabled={isFormLocked} className="min-w-0">
            <HospitalsPageCTASection
              value={form.cta}
              onChange={(v) => updateSection("cta", v)}
              validation={activeLanguage === "en" && englishValidationTouched ? getEnglishValidationErrors().cta : undefined}
            />
          </fieldset>
        )}
      </Section>

      {/* Global save button */}
      <div className="flex items-center justify-end gap-3 pb-2">
        {isLockedForEditing && (
          <button
            type="button"
            onClick={() => {
              setIsLockedForEditing(false)
              setSaveSuccess(null)
              setSaveError(null)
            }}
            disabled={saving || savingSectionKey !== null}
            className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-bold font-sans border border-border text-foreground bg-card transition-all hover:brightness-105 active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
          >
            <Pencil className="w-4 h-4" aria-hidden="true" />
            Edit Page
          </button>
        )}
        <button
          type="button"
          onClick={() => void handleSave()}
          disabled={isFormLocked}
          className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm 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)" }}
        >
          {saving ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
              Saving...
            </>
          ) : (
            <>
              <Save className="w-4 h-4" aria-hidden="true" />
              Save Changes
            </>
          )}
        </button>
      </div>

    </div>
  )
}
