import { Edit, FileText, Folder, Minus, Plus } from "lucide-react";
import { useEffect, useState } from "react";
import { resourceApi } from "~/api/resource-api.service";
import { ConfirmAlert } from "~/components/btn/confirm-alert";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import { Label } from "~/components/ui/label";
import { Switch } from "~/components/ui/switch";
import { ResourceItemModal } from "./modals/resource-item-modal";
import { cn } from "~/lib/utils";

export interface IResourceItemProps {
  data: IResource;
  openOnMount?: boolean;
  level?: number;
  onToggle: (resource: IResource, parent?: IResource) => void;
}

export default function ResourceItem({
  data,
  openOnMount,
  level = 0,
  onToggle,
}: IResourceItemProps) {
  const [expanded, setExpanded] = useState(false);
  const hasChildren = data.children && data.children.length > 0;

  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (openOnMount === undefined) return;

    setOpen(openOnMount);
  }, [openOnMount]);

  const handleSubmit = async () => {
    const newChildren = data.children.map((item) => ({
      ...item,
      disabled: !data.disabled,
    }));

    const result = await resourceApi.bulkUpdate([
      {
        ...data,
        disabled: !data.disabled,
        children: newChildren,
      },
      ...newChildren,
    ]);

    if (!result) return;
  };

  useEffect(() => {
    const disabled = data.children.every((item) => item.disabled);

    if (!disabled) return;
  }, [data]);

  return (
    // <Card key={sData.id} className="overflow-hidden py-0">
    //   <Collapsible open={open} onOpenChange={setOpen}>
    //     <CollapsibleTrigger asChild>
    //       <CardHeader className="pb-3 cursor-pointer hover:bg-gray-50 transition-colors py-6">
    //         <div className="flex items-center justify-between">
    //           <div className="flex items-center gap-3">
    //             <div>
    //               <CardTitle className="text-lg">{sData.name}</CardTitle>
    //               <CardDescription>
    //                 {_.filter(sData.children, { disabled: false }).length}{" "}
    //                 resource(s) - {sData.children.length} đang hoạt động
    //               </CardDescription>
    //             </div>
    //           </div>
    //           <div className="flex items-center gap-2">
    //             <ConfirmAlert
    //               onConfirm={handleSubmit}
    //               description="Hành động này có thể gây ra ảnh hưởng với các chức năng khác."
    //             >
    //               <div
    //                 onClick={(e) => e.stopPropagation()}
    //                 className="flex items-center space-x-2"
    //               >
    //                 <Switch checked={!sData.disabled} />
    //                 <Label className="text-sm">Hoạt động</Label>
    //               </div>
    //             </ConfirmAlert>

    //             <Badge variant="outline">
    //               {sData.children.length} resources
    //             </Badge>
    //             <Button variant="ghost" size="sm">
    //               {open ? <Minus /> : <Plus />}
    //             </Button>
    //           </div>
    //         </div>
    //       </CardHeader>
    //     </CollapsibleTrigger>
    //     <CollapsibleContent>
    //       <CardContent className="pb-6">
    //         <div className="space-y-3">
    //           {sData.children.map((resource) => (
    //             <div
    //               key={resource.id}
    //               className="flex items-center justify-between p-4 border rounded-lg bg-gray-50"
    //             >
    //               <div className="flex-1">
    //                 <div className="flex items-center gap-3">
    //                   <div>
    //                     <h4 className="font-medium capitalize">
    //                       {resource.name || resource.function_permisstion}
    //                     </h4>
    //                     <p className="text-sm text-muted-foreground">
    //                       {resource.description}
    //                     </p>
    //                   </div>
    //                   <Badge variant="outline" className="ml-auto mr-1">
    //                     ID: {resource.id}
    //                   </Badge>
    //                 </div>
    //               </div>
    //               <div className="flex items-center space-x-3">
    //                 <ConfirmAlert
    //                   onConfirm={() => handleChildrenSubmit(resource)}
    //                   description="Hành động này có thể gây ra ảnh hưởng với các chức năng khác."
    //                 >
    //                   <div className="flex items-center space-x-2">
    //                     <Switch checked={!resource.disabled} />
    //                     <Label className="text-sm">Hoạt động</Label>
    //                   </div>
    //                 </ConfirmAlert>
    //                 <ResourceItemModal data={resource}>
    //                   <Button variant="outline" size="sm">
    //                     <Edit className="mr-2 h-4 w-4" />
    //                     Sửa
    //                   </Button>
    //                 </ResourceItemModal>
    //               </div>
    //             </div>
    //           ))}
    //         </div>
    //       </CardContent>
    //     </CollapsibleContent>
    //   </Collapsible>
    // </Card>

    <div className={cn("space-y-1", level === 0 && "border rounded-md")}>
      <div
        className="flex items-center space-x-2 p-2 rounded-md hover:bg-gray-50 dark:hover:bg-gray-800  "
        style={{ paddingLeft: `${level * 20 + 8}px` }}
      >
        {hasChildren && (
          <Button
            variant="ghost"
            size="sm"
            className="h-4 w-4 p-0"
            onClick={() => setExpanded(!expanded)}
          >
            {expanded ? (
              <Minus className="h-3 w-3" />
            ) : (
              <Plus className="h-3 w-3" />
            )}
          </Button>
        )}
        {!hasChildren && <div className="w-4" />}

        <div className="flex items-center space-x-2 flex-1">
          {data.type === "controller" ? (
            <Folder className="h-4 w-4 text-blue-500" />
          ) : (
            <FileText className="h-4 w-4 text-green-500" />
          )}

          <div className="flex-1">
            <div className="flex items-center space-x-2">
              <span className="font-medium">{data.name}</span>
              {data.is_public && (
                <Badge variant="secondary" className="text-xs">
                  Public (Auto-granted)
                </Badge>
              )}
              {data.disabled && (
                <Badge variant="outline" className="text-xs">
                  Disabled
                </Badge>
              )}
            </div>
            {data.description && (
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {data.description}
              </p>
            )}
            <p className="text-xs text-gray-400 dark:text-gray-500">
              {data.path} {data.method && `(${data.method})`}
            </p>
          </div>
        </div>

        <div className="">
          <div className="flex items-center gap-2">
            {level <= 0 && (
              <Badge variant="outline">
                {data.children.filter((item) => !item.disabled).length} /{" "}
                {data.children.length} resources
              </Badge>
            )}
            <ConfirmAlert
              onConfirm={handleSubmit}
              description="Hành động này có thể gây ra ảnh hưởng với các chức năng khác."
            >
              <div
                onClick={(e) => e.stopPropagation()}
                className="flex items-center space-x-2"
              >
                <Switch checked={!data.disabled} />
                <Label className="text-sm">Hoạt động</Label>
              </div>
            </ConfirmAlert>

            <ResourceItemModal data={data}>
              <Button variant="outline" size="sm">
                <Edit className="mr-2 h-4 w-4" />
                Sửa
              </Button>
            </ResourceItemModal>
          </div>
        </div>
      </div>

      {hasChildren && expanded && (
        <div className="space-y-1">
          {data.children.map((child) => (
            <ResourceItem
              key={child.id}
              data={child}
              onToggle={onToggle}
              level={level + 1}
            />
          ))}
        </div>
      )}
    </div>
  );
}
