"use client"

import { useState, useEffect } from "react"
import { Shield } from "lucide-react"
import { router } from "@inertiajs/react"
import AppLayout from "@/Layouts/AppLayout"
import { Input } from "@/Components/UI/Input"
import { Label } from "@/Components/UI/Label"
import { Switch } from "@/Components/UI/Switch"
import { Button } from "@/Components/UI/Button"
import { Separator } from "@/Components/UI/Separator"
import { Card, CardContent } from "@/Components/UI/Card"
import useTranslate from "@/hooks/useTranslate";
import { route } from "ziggy-js"

export default function RoleEdit({ role, rolePermissions }) {
    const t = useTranslate()

    const breadcrumbs = [
        { label: t("Dashboard"), href: route("user.home") },
        { label: t("Access Control"), href: route("user.access-control.index") },
        { label: t("Edit Role") },
    ]

    const [roleName, setRoleName] = useState(role?.name || "")
    const [selectedPermissions, setSelectedPermissions] = useState({})
    const [isSubmitting, setIsSubmitting] = useState(false)

    useEffect(() => {
        if (role?.permissions) {
            setSelectedPermissions(role.permissions)
        }
    }, [role])

    const handlePermissionToggle = (category, permission) => {
        setSelectedPermissions((prev) => {
            const categoryPermissions = prev[category] || []
            const isSelected = categoryPermissions.includes(permission)

            if (isSelected) {
                const updatedPermissions = categoryPermissions.filter((p) => p !== permission)
                if (updatedPermissions.length === 0) {
                    const { [category]: removed, ...rest } = prev
                    return rest
                }
                return { ...prev, [category]: updatedPermissions }
            } else {
                return { ...prev, [category]: [...categoryPermissions, permission] }
            }
        })
    }

    const handleAllPermissions = () => {
        const allSelected = Object.keys(rolePermissions).every((category) =>
            rolePermissions[category].every((permission) => selectedPermissions[category]?.includes(permission)),
        )

        if (allSelected) {
            setSelectedPermissions({})
        } else {
            const allPermissions = {}
            Object.keys(rolePermissions).forEach((category) => {
                allPermissions[category] = [...rolePermissions[category]]
            })
            setSelectedPermissions(allPermissions)
        }
    }

    const handleCategoryToggle = (category) => {
        const categoryPermissions = rolePermissions[category]
        const selectedCategoryPermissions = selectedPermissions[category] || []
        const allSelected = categoryPermissions.every((permission) => selectedCategoryPermissions.includes(permission))

        if (allSelected) {
            const { [category]: removed, ...rest } = selectedPermissions
            setSelectedPermissions(rest)
        } else {
            setSelectedPermissions((prev) => ({
                ...prev,
                [category]: [...categoryPermissions],
            }))
        }
    }

    const isPermissionSelected = (category, permission) => {
        return selectedPermissions[category]?.includes(permission) || false
    }

    const isCategoryFullySelected = (category) => {
        const categoryPermissions = rolePermissions[category]
        const selectedCategoryPermissions = selectedPermissions[category] || []
        return categoryPermissions.every((permission) => selectedCategoryPermissions.includes(permission))
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        setIsSubmitting(true)

        const formData = {
            id: role.id,
            name: roleName,
            permissions: selectedPermissions,
        }

        router.post(route("user.role.update"), formData, {
            onFinish: () => setIsSubmitting(false),
            onError: () => setIsSubmitting(false),
        })
    }

    const getCategoryDisplayName = (category) => {
        return category
            .split("_")
            .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
            .join(" ")
    }

    const getPermissionDisplayName = (permission) => {
        return permission
            .split("_")
            .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
            .join(" ")
    }

    const categories = Object.keys(rolePermissions)
    const midPoint = Math.ceil(categories.length / 2)
    const leftColumnCategories = categories.slice(0, midPoint)
    const rightColumnCategories = categories.slice(midPoint)

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <div className="p-6 bg-gray-50 dark:bg-black">
                <div>
                    {/* Header */}
                    <div className="mb-6">
                        <div className="flex items-center gap-3 mb-2">
                            <div>
                                <Shield className="h-6 w-6 text-primary" />
                            </div>
                            <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                                Edit Role: {role?.name || 'Role'}
                            </h1>
                        </div>
                        <p className="text-gray-500 dark:text-gray-200">
                            Configure permissions and access controls for this user role
                        </p>
                    </div>
                    {/* Role Name Section */}
                    <Card className="mb-6">
                        <CardContent className="p-6">
                            <div className="space-y-4">
                                <div className="space-y-2">
                                    <Label htmlFor="roleName" className="text-sm font-medium text-gray-900 dark:text-white">Role Name</Label>
                                    <Input
                                        id="roleName"
                                        value={roleName}
                                        onChange={(e) => setRoleName(e.target.value)}
                                        placeholder="Enter role name"
                                        className="bg-white dark:bg-zinc-900 border-gray-300 dark:border-gray-600"
                                        required
                                    />
                                </div>
                                <Separator />
                                <div className="flex items-center justify-between">
                                    <div>
                                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Permissions Configuration</h3>
                                        <p className="text-sm text-gray-500 dark:text-gray-400">Select the permissions you want to assign to this role</p>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <Label htmlFor="allPermissions" className="text-sm font-medium text-gray-900 dark:text-white">
                                            Select All Permissions
                                        </Label>
                                        <Switch
                                            id="allPermissions"
                                            checked={Object.keys(rolePermissions).every((category) =>
                                                rolePermissions[category].every((permission) => selectedPermissions[category]?.includes(permission)),
                                            )}
                                            onCheckedChange={handleAllPermissions}
                                            className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary"
                                        />
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <div>
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                {/* Left Column */}
                                <div className="space-y-6">
                                    {leftColumnCategories.map((category) => (
                                        <Card key={category} className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                                            <CardContent className="p-6">
                                                <div className="flex items-center justify-between mb-4">
                                                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                                                        {getCategoryDisplayName(category)}
                                                    </h3>
                                                    <div className="flex items-center space-x-2">
                                                        <Label htmlFor={`${category}-all`} className="text-sm font-medium text-gray-600 dark:text-gray-300">
                                                            Select All
                                                        </Label>
                                                        <Switch 
                                                            id={`${category}-all`}
                                                            checked={isCategoryFullySelected(category)}
                                                            onCheckedChange={() => handleCategoryToggle(category)}
                                                            className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary"
                                                        />
                                                    </div>
                                                </div>
                                                <Separator className="mb-4 bg-gray-200 dark:bg-gray-700" />
                                                <div className="space-y-3">
                                                    {rolePermissions[category].map((permission) => (
                                                        <div key={permission} className="flex items-center justify-between p-3 rounded-lg bg-gray-50 dark:bg-zinc-800 border border-gray-100 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-zinc-700 transition-colors">
                                                            <Label
                                                                htmlFor={`${category}-${permission}`}
                                                                className="cursor-pointer text-gray-700 dark:text-gray-300 font-medium"
                                                            >
                                                                {getPermissionDisplayName(permission)}
                                                            </Label>
                                                            <Switch
                                                                id={`${category}-${permission}`}
                                                                checked={isPermissionSelected(category, permission)}
                                                                onCheckedChange={() => handlePermissionToggle(category, permission)}
                                                                className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary"
                                                            />
                                                        </div>
                                                    ))}
                                                </div>
                                            </CardContent>
                                        </Card>
                                    ))}
                                </div>

                                {/* Right Column */}
                                <div className="space-y-6">
                                    {rightColumnCategories.map((category) => (
                                        <Card key={category} className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                                            <CardContent className="p-6">
                                                <div className="flex items-center justify-between mb-4">
                                                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                                                        {getCategoryDisplayName(category)}
                                                    </h3>
                                                    <div className="flex items-center space-x-2">
                                                        <Label htmlFor={`${category}-all-right`} className="text-sm font-medium text-gray-600 dark:text-gray-300">
                                                            Select All
                                                        </Label>
                                                        <Switch
                                                            id={`${category}-all-right`}
                                                            checked={isCategoryFullySelected(category)}
                                                            onCheckedChange={() => handleCategoryToggle(category)}
                                                            className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary"
                                                        />
                                                    </div>
                                                </div>
                                                <Separator className="mb-4 bg-gray-200 dark:bg-gray-700" />
                                                <div className="space-y-3">
                                                    {rolePermissions[category].map((permission) => (
                                                        <div key={permission} className="flex items-center justify-between p-3 rounded-lg bg-gray-50 dark:bg-zinc-800 border border-gray-100 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-zinc-700 transition-colors">
                                                            <Label
                                                                htmlFor={`${category}-right-${permission}`}
                                                                className="cursor-pointer text-gray-700 dark:text-gray-300 font-medium"
                                                            >
                                                                {getPermissionDisplayName(permission)}
                                                            </Label>
                                                            <Switch
                                                                id={`${category}-right-${permission}`}
                                                                checked={isPermissionSelected(category, permission)}
                                                                onCheckedChange={() => handlePermissionToggle(category, permission)}
                                                                className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary"
                                                            />
                                                        </div>
                                                    ))}
                                                </div>
                                            </CardContent>
                                        </Card>
                                    ))}
                                </div>
                            </div>

                            {/* Submit Section */}
                            <Card className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                                <CardContent className="p-6">
                                    <div className="flex items-center justify-between">
                                        <Button
                                            type="button"
                                            variant="outline"
                                            onClick={() => window.history.back()}
                                            className="px-6 py-2 border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-zinc-700"
                                        >
                                            Cancel
                                        </Button>
                                        <Button
                                            type="submit"
                                            disabled={isSubmitting}
                                            className="px-6 py-2 bg-gradient-to-r from-primary to-secondary hover:from-primary/90 hover:to-secondary/90 text-white font-medium"
                                        >
                                            {isSubmitting ? "Updating Role..." : "Update Role"}
                                        </Button>
                                    </div>
                                </CardContent>
                            </Card>
                        </form>
                    </div>
                </div>
            </div>
        </AppLayout>
    )
}
