"use client"

import { OrgSettingsSection } from "@/components/admin/settings/org-settings-form"
import { DeployLockedHint } from "@/components/admin/settings/deploy-locked-hint"
import { useOrgSettingsStore } from "@/lib/admin-settings/org-settings-store"
import { isPluginDeployLocked } from "@/lib/admin/deploy-runtime"
import { Switch } from "@/components/ui/switch"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"

export function PluginsSection() {
  const plugins = useOrgSettingsStore((s) => s.plugins)
  const togglePlugin = useOrgSettingsStore((s) => s.togglePlugin)
  const deployLocked = useOrgSettingsStore((s) => s.meta?.deployLocked)

  return (
    <OrgSettingsSection
      title="Plugins"
      description="Modules fonctionnels activables pour toute l'organisation."
      policySection="plugins"
    >
      <div className="space-y-3">
        {plugins.map((plugin) => {
          const locked = isPluginDeployLocked(deployLocked, plugin.id)
          return (
            <Card key={plugin.id}>
              <CardContent className="flex items-center gap-4 py-4">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <p className="font-medium">{plugin.name}</p>
                    <Badge variant="outline">v{plugin.version}</Badge>
                  </div>
                  <p className="mt-1 text-sm text-muted-foreground">{plugin.description}</p>
                  {plugin.id === "ai-assistant" && !plugin.enabled ? (
                    <p className="mt-1 text-xs text-muted-foreground">
                      N&apos;oubliez pas d&apos;enregistrer après activation. OpenWebUI doit être
                      déployé (<code className="rounded bg-muted px-1">AI_ASSISTANT_ENABLED=true</code>
                      ).
                    </p>
                  ) : null}
                  {locked ? <DeployLockedHint section="plugins" field={plugin.id} /> : null}
                </div>
                <Switch
                  checked={plugin.enabled}
                  disabled={locked}
                  onCheckedChange={(enabled) => togglePlugin(plugin.id, enabled)}
                />
              </CardContent>
            </Card>
          )
        })}
      </div>
    </OrgSettingsSection>
  )
}
