"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { SettingsSectionHeader } from "@/components/gmail/settings/settings-section-header"
import { SettingsSyncBanner } from "@/components/gmail/settings/settings-sync-banner"
import { AdminPendingApiBanner } from "@/components/admin/settings/admin-pending-api-banner"
import { AdminRuntimePanel } from "@/components/admin/settings/admin-runtime-panel"
import type { OrgPolicySectionKey } from "@/lib/api/admin-org-types"
import { useOrgSettings } from "@/lib/api/hooks/use-org-settings"
import { useSaveOrgPolicy } from "@/lib/api/hooks/use-save-org-policy"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"

export function OrgSettingsSection({
  title,
  description,
  children,
  policySection,
  showEffectiveBanner = true,
  beforeSave,
}: {
  title: string
  description?: string
  children: React.ReactNode
  policySection?: OrgPolicySectionKey | OrgPolicySectionKey[]
  showEffectiveBanner?: boolean
  beforeSave?: () => void | Promise<void>
}) {
  const [saved, setSaved] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { isFetching, isError, refetch, isFetched } = useOrgSettings()
  const savePolicy = useSaveOrgPolicy()
  const apiSynced = useOrgSettingsStore((s) => s.apiSynced)
  const showPendingBanner = !apiSynced && !isError && (isFetching || !isFetched)
  const hasSave = Boolean(policySection)

  async function handleSave() {
    if (!policySection) return
    setError(null)
    try {
      await beforeSave?.()
      const sections = Array.isArray(policySection) ? policySection : [policySection]
      await savePolicy(sections)
      setSaved(true)
      setTimeout(() => setSaved(false), 2000)
    } catch (err) {
      setError(err instanceof Error ? err.message : "Échec de l'enregistrement")
    }
  }

  return (
    <div className="flex min-h-full flex-col">
      <div className="flex-1 space-y-6 pb-6">
        <SettingsSectionHeader title={title} description={description} />
        <SettingsSyncBanner isFetching={isFetching} isError={isError} onRetry={() => refetch()} />
        {!showPendingBanner ? null : <AdminPendingApiBanner />}
        {showEffectiveBanner ? <AdminRuntimePanel /> : null}
        {children}
      </div>
      {hasSave ? (
        <div className="sticky bottom-0 z-10 -mx-4 shrink-0 border-t border-border bg-mail-surface/95 px-4 py-4 backdrop-blur supports-[backdrop-filter]:bg-mail-surface/80 sm:-mx-8 sm:px-8 dark:bg-mail-surface-elevated/95">
          <div className="flex flex-wrap items-center gap-3">
            <Button
              type="button"
              onClick={() => void handleSave()}
              disabled={!apiSynced || isFetching}
            >
              Enregistrer
            </Button>
            {saved ? (
              <span className="text-sm text-green-600 dark:text-green-500">
                Réglages enregistrés sur le serveur
              </span>
            ) : null}
            {error ? <span className="text-sm text-destructive">{error}</span> : null}
          </div>
        </div>
      ) : null}
    </div>
  )
}
