"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 (
    <>
      <SettingsSectionHeader title={title} description={description} />
      <SettingsSyncBanner isFetching={isFetching} isError={isError} onRetry={() => refetch()} />
      {!showPendingBanner ? null : <AdminPendingApiBanner />}
      {showEffectiveBanner ? <AdminRuntimePanel /> : null}
      <div className="space-y-6">{children}</div>
      {hasSave ? (
        <div className="mt-6 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>
      ) : null}
    </>
  )
}
