"use client"

import { useEffect, useState } from "react"
import { OrgSettingsSection } from "@/components/admin/settings/org-settings-form"
import {
  SettingsCard,
  SettingsField,
  SettingsToggleRow,
} from "@/components/settings/settings-kit"
import { AutomationTabMasonry } from "@/components/gmail/settings/automation/automation-tab-masonry"
import { AgendaVideoProviderSelectLabel } from "@/components/agenda/agenda-video-provider-select-label"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"
import {
  AGENDA_VIDEO_PROVIDER_LABELS,
  AGENDA_VIDEO_PROVIDERS,
  type AgendaVideoProvider,
} from "@/lib/agenda/agenda-settings-types"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import type { MailThemeMode } from "@/lib/mail-settings/types"

const THEME_OPTIONS: { id: MailThemeMode; label: string }[] = [
  { id: "light", label: "Clair" },
  { id: "dark", label: "Sombre" },
  { id: "system", label: "Système" },
]

export function AgendaSection() {
  const agenda = useOrgSettingsStore((s) => s.agenda)
  const setAgenda = useOrgSettingsStore((s) => s.setAgenda)
  const [draft, setDraft] = useState(agenda)

  useEffect(() => {
    setDraft(agenda)
  }, [agenda])

  const updateApiKey = (provider: AgendaVideoProvider, value: string) => {
    setDraft((prev) => ({
      ...prev,
      video_provider_api_keys: {
        ...prev.video_provider_api_keys,
        [provider]: value,
      },
    }))
  }

  return (
    <OrgSettingsSection
      title="Agenda"
      description="Thème et visioconférence par défaut pour toute l'organisation."
      policySection="agenda"
      beforeSave={() => setAgenda(draft)}
    >
      <AutomationTabMasonry columns={2}>
        <SettingsCard title="Thème" description="Mode clair/sombre par défaut de l'agenda.">
          <SettingsToggleRow
            title="Imposer le thème organisationnel"
            description="Les utilisateurs ne peuvent plus changer le mode clair/sombre."
            checked={draft.enforce_org_theme}
            onCheckedChange={(v) => setDraft((p) => ({ ...p, enforce_org_theme: v }))}
          />
          <SettingsField label="Thème par défaut">
            <Select
              value={draft.default_theme_mode}
              onValueChange={(v) =>
                setDraft((p) => ({ ...p, default_theme_mode: v as MailThemeMode }))
              }
            >
              <SelectTrigger className="h-9 w-full max-w-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {THEME_OPTIONS.map((opt) => (
                  <SelectItem key={opt.id} value={opt.id}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </SettingsField>
        </SettingsCard>

        <SettingsCard
          title="Visioconférence"
          description="Fournisseur visio par défaut pour les événements."
        >
          <SettingsToggleRow
            title="Imposer le fournisseur visio"
            description="Les utilisateurs ne peuvent plus choisir Zoom, Meet, etc."
            checked={draft.enforce_org_video_provider}
            onCheckedChange={(v) => setDraft((p) => ({ ...p, enforce_org_video_provider: v }))}
          />
          <SettingsField label="Fournisseur visio par défaut">
            <Select
              value={draft.default_video_provider}
              onValueChange={(v) =>
                setDraft((p) => ({
                  ...p,
                  default_video_provider: v as AgendaVideoProvider,
                }))
              }
            >
              <SelectTrigger className="h-9 w-full max-w-xs">
                <SelectValue>
                  <AgendaVideoProviderSelectLabel provider={draft.default_video_provider} />
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {AGENDA_VIDEO_PROVIDERS.map((provider) => (
                  <SelectItem key={provider} value={provider}>
                    <AgendaVideoProviderSelectLabel provider={provider} />
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </SettingsField>
        </SettingsCard>

        <SettingsCard
          title="Clés API visioconférence (organisation)"
          description="Stockées côté serveur. UltiMeet n'exige pas de clé API."
        >
          {(["zoom", "google_meet", "teams", "jitsi"] as AgendaVideoProvider[]).map(
            (provider) => (
              <SettingsField key={provider} label={AGENDA_VIDEO_PROVIDER_LABELS[provider]}>
                <Input
                  type="password"
                  autoComplete="off"
                  className="h-9"
                  placeholder="Clé API (laisser vide pour conserver l'existante)"
                  value={draft.video_provider_api_keys[provider] ?? ""}
                  onChange={(e) => updateApiKey(provider, e.target.value)}
                />
              </SettingsField>
            ),
          )}
        </SettingsCard>
      </AutomationTabMasonry>
    </OrgSettingsSection>
  )
}
