"use client";

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
	DialogFooter,
} from "@/components/ui/dialog";
import { ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
import { toTitleCase } from "@/lib/utils";
import { useApi } from "@/hooks/use-api";

type Action = "create" | "read" | "update" | "delete";

interface Permission {
	resource: string;
	actions: Action[];
}

interface Role {
	name: string;
	permissions: Permission[];
}

// Sample data
const initialRoles: Role[] = [
	{
		name: "Admin",
		permissions: [
			{
				resource: "users",
				actions: ["create", "read", "update", "delete"],
			},
			{
				resource: "events",
				actions: ["create", "read", "update", "delete"],
			},
			{
				resource: "blogs",
				actions: ["create", "read", "update", "delete"],
			},
		],
	},
	{
		name: "Editor",
		permissions: [
			{ resource: "users", actions: ["read"] },
			{ resource: "events", actions: ["create", "read", "update"] },
			{ resource: "blogs", actions: ["create", "read", "update"] },
		],
	},
];

interface PermissionsGrouped {
	resource: string;
	actions: string[];
}

export default function RolesAndPermissions() {
	const [roles, setRoles] = useState<Role[]>(initialRoles);
	const [newRoleName, setNewRoleName] = useState<string>("");
	const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);

	const { data: permissions } = useApi<PermissionsGrouped[]>(
		"/permissions/grouped",
		{},
		true,
	);

	const addNewRole = () => {
		if (newRoleName.trim() === "") return;

		const newRole: Role = {
			name: newRoleName.trim(),
			permissions: [
				{ resource: "users", actions: [] },
				{ resource: "events", actions: [] },
				{ resource: "blogs", actions: [] },
			],
		};
		setRoles([...roles, newRole]);
		setNewRoleName("");
		setIsDialogOpen(false);
	};

	const deleteRole = (index: number) => {
		const updatedRoles = roles.filter((_, i) => i !== index);
		setRoles(updatedRoles);
	};

	return (
		<div className="container mx-auto p-4 space-y-6">
			<div className="flex justify-between items-center">
				<h1 className="text-2xl font-bold">Rôles et Permissions</h1>
				<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
					<DialogTrigger asChild>
						<Button>
							<Plus className="mr-2 h-4 w-4" /> Nouveau rôle
						</Button>
					</DialogTrigger>
					<DialogContent>
						<DialogHeader>
							<DialogTitle>Nouveau rôle</DialogTitle>
						</DialogHeader>
						<div className="py-4">
							<Input
								placeholder="Nom du rôle"
								value={newRoleName}
								onChange={(e) => setNewRoleName(e.target.value)}
							/>
						</div>
						<DialogFooter>
							<Button
								onClick={addNewRole}
								disabled={newRoleName.trim() === ""}
							>
								Ajouter
							</Button>
						</DialogFooter>
					</DialogContent>
				</Dialog>
			</div>
			{roles.map((role, index) => (
				<RoleCard
					key={index}
					role={role}
					onDelete={() => deleteRole(index)}
				/>
			))}
		</div>
	);
}

interface RoleCardProps {
	role: Role;
	onDelete: () => void;
}

function RoleCard({ role, onDelete }: RoleCardProps) {
	return (
		<Card>
			<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
				<CardTitle>{role.name}</CardTitle>
				<Button variant="destructive" size="icon" onClick={onDelete}>
					<Trash2 className="h-4 w-4" />
				</Button>
			</CardHeader>
			<CardContent>
				{role.permissions.map((permission) => (
					<ResourceSection
						key={permission.resource}
						resource={permission.resource}
						actions={permission.actions}
					/>
				))}
			</CardContent>
		</Card>
	);
}

interface ResourceSectionProps {
	resource: string;
	actions: Action[];
}

function ResourceSection({ resource, actions }: ResourceSectionProps) {
	const [isExpanded, setIsExpanded] = useState<boolean>(false);

	return (
		<div className="mb-4">
			<button
				className="flex items-center text-lg font-semibold mb-2"
				onClick={() => setIsExpanded(!isExpanded)}
			>
				{isExpanded ? (
					<ChevronDown className="mr-2" />
				) : (
					<ChevronRight className="mr-2" />
				)}
				{toTitleCase(resource)}
			</button>
			{isExpanded && (
				<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 ml-6">
					{actions.map((action) => (
						<div
							key={action}
							className="flex items-center space-x-2"
						>
							<Checkbox id={`${resource}-${action}`} />
							<label
								htmlFor={`${resource}-${action}`}
								className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
							>
								{action}
							</label>
						</div>
					))}
				</div>
			)}
		</div>
	);
}
