import { X } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { rolesApi } from "~/api/roles-api.service";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";

// Role Selection Component
export interface RoleSelectionProps {
  value: IRole[];
  onChange: (roles: IRole[]) => void;
}

export function RoleSelection({ value, onChange }: RoleSelectionProps) {
  const [data, setData] = useState<IRole[]>([]);

  const currentRoles = useMemo(() => {
    // return Array.isArray(value) ? value : [];
    return value;
  }, [value]);

  const handleRoleToggle = useCallback(
    (role: IRole) => {
      console.log({ role, currentRoles });

      const isSelected = value.some((r) => r.id === role.id);
      if (isSelected) {
        onChange(currentRoles.filter((r) => r.id !== role.id));
      } else {
        onChange([...value, role]);
      }
    },
    [currentRoles, onChange]
  );

  const fetch = async () => {
    const response = await rolesApi.index();

    if (!response?.data) return;

    setData(response.data);
  };

  useEffect(() => {
    fetch();
  }, []);

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
        {data.map((role) => {
          const isSelected = currentRoles.some((r) => r.id === role.id);
          return (
            <div
              key={role.id}
              className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                isSelected
                  ? "border-primary bg-primary/5"
                  : "border-input hover:border-primary/50"
              }`}
              onClick={() => handleRoleToggle(role)}
            >
              <div className="flex items-center space-x-2">
                <Checkbox checked={isSelected} />
                <div>
                  <div className="font-medium">{role.role_name}</div>
                  {role?.description && (
                    <div className="text-sm text-muted-foreground">
                      {role?.description}
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
      {currentRoles.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {currentRoles.map((role) => (
            <Badge key={role.id} variant="secondary">
              {role.role_name}
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-auto p-0 ml-2"
                onClick={() => handleRoleToggle(role)}
              >
                <X className="h-3 w-3" />
              </Button>
            </Badge>
          ))}
        </div>
      )}
    </div>
  );
}
