"use client"


import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { toggleOrganizationModule } from "../actions"
import { useState } from "react"
import { Loader2 } from "lucide-react"

import { AVAILABLE_MODULES } from "@/lib/constants"

export function OrgModulesForm({ orgId, enabledModules }: { orgId: string, enabledModules: string[] }) {
    const [loading, setLoading] = useState<string | null>(null)

    const handleToggle = async (moduleId: string, checked: boolean) => {
        setLoading(moduleId)
        await toggleOrganizationModule(orgId, moduleId, checked)
        setLoading(null)
    }

    return (
        <div className="space-y-4">
            {AVAILABLE_MODULES.map((module) => {
                const isEnabled = enabledModules.includes(module.id)
                const isLoading = loading === module.id

                return (
                    <div key={module.id} className="flex items-center justify-between space-x-2 border p-3 rounded-md">
                        <div className="flex flex-col space-y-1">
                            <Label htmlFor={module.id} className="font-medium flex items-center gap-2 cursor-pointer">
                                <module.icon className="h-4 w-4 text-muted-foreground" />
                                {module.label}
                            </Label>
                            <span className="text-sm text-muted-foreground pl-6">
                                {module.description}
                            </span>
                        </div>
                        <div className="flex items-center gap-2">
                            {isLoading && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
                            <Switch
                                id={module.id}
                                checked={isEnabled}
                                onCheckedChange={(checked: boolean) => handleToggle(module.id, checked)}
                                disabled={!!loading}
                            />
                        </div>
                    </div>
                )
            })}
        </div>
    )
}
