"use client";

import * as React from "react";
import { Shield, RefreshCw, Check, FileDown, Upload, FileUp, X, Plus, Trash2 } from "lucide-react";
import {
    Dialog,
    DialogContent,
    DialogTitle,
} from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { DataGrid, type Column, type RenderEditCellProps } from "react-data-grid";
import { useDropzone } from "react-dropzone";
import "react-data-grid/lib/styles.css";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { ReactSelect } from "@/components/ui/react-select";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { useGetRolesQuery } from "@/api/rtk/roles-api";
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api";
import {
    useGetRoleStagePermissionsByRoleQuery,
    useBulkCreateRoleStagePermissionsMutation,
    useBulkApplyRoleStagePermissionsMutation,
} from "@/api/rtk/role-stage-permissions-api";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import { useAuthToken } from "@/hooks/use-auth-token"
import {
    setServerPermissions,
    setPermissionFlag,
    setBulkPermissionFlag,
    discardChanges,
    commitChanges,
    selectPermissionsForRole,
    selectIsInSyncWithServer,
    selectDirtyStageIds,
    selectHasCachedPermissions,
} from "@/store/slices/role-permissions-slice";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import * as XLSX from "xlsx";
import { Loading } from "../ui/loading";

const EMPTY_ARRAY: any[] = [];
const EMPTY_OBJECT = {};

interface FlattenedStage {
    id: string; // The specific PipelineStage id or PipelineSubStage id
    name: string;
    pipelineName: string;
    type: "STAGE" | "SUBSTAGE";
}

// ─── Importer Component ──────────────────────────────────────────────────

function RoleStagePermissionsImporter({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
    const fileInputRef = React.useRef<HTMLInputElement>(null);
    const [gridRows, setGridRows] = React.useState<Record<string, string>[]>([]);
    const [gridColumns, setGridColumns] = React.useState<Column<Record<string, string>>[]>([]);
    const [isReady, setIsReady] = React.useState(false);
    const [bulkCreate, { isLoading: isImporting }] = useBulkCreateRoleStagePermissionsMutation();

    const buildColumns = React.useCallback((headers: string[]): Column<Record<string, string>>[] => [
        {
            key: "__rowNum__",
            name: "#",
            width: 48,
            resizable: false,
            frozen: true,
            renderCell: ({ rowIdx }: { rowIdx: number }) => (
                <span className="text-[11px] text-gray-400 text-center block w-full">{rowIdx + 1}</span>
            ),
        },
        ...headers.map((h) => ({
            key: h,
            name: h,
            resizable: true,
            minWidth: 120,
            renderEditCell: (p: RenderEditCellProps<Record<string, string>>) => (
                <input
                    autoFocus
                    className="w-full h-full border-none outline-hidden px-2 bg-accent/5 text-[13px]"
                    defaultValue={p.row[h] ?? ""}
                    onBlur={(e) => p.onRowChange({ ...p.row, [h]: e.target.value }, true)}
                    onKeyDown={(e) => {
                        if (e.key === "Enter") p.onRowChange({ ...p.row, [h]: (e.target as HTMLInputElement).value }, true);
                        if (e.key === "Escape") p.onClose(false);
                    }}
                />
            ),
        })),
    ], []);

    const parseFile = async (file: File) => {
        const buf = await file.arrayBuffer();
        const wb = XLSX.read(buf, { type: "array" });
        const sheet = wb.Sheets[wb.SheetNames[0]];
        const rows = XLSX.utils.sheet_to_json<Record<string, any>>(sheet, { defval: "" });
        if (!rows.length) {
            toast.error("No data found");
            return;
        }
        const headers = Object.keys(rows[0]);
        setGridColumns(buildColumns(headers));
        setGridRows(rows.map(r => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, String(v)]))));
        setIsReady(true);
    };

    const { getRootProps, getInputProps, isDragActive } = useDropzone({
        accept: { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [".xlsx"] },
        maxFiles: 1,
        onDrop: (files) => files[0] && parseFile(files[0]),
    });

    const handleImport = async () => {
        try {
            const result = await bulkCreate({ permissions: gridRows }).unwrap();
            toast.success(`Import complete: ${result.inserted} created, ${result.updated} updated, ${result.skipped} skipped`);
            setIsReady(false);
            setGridRows([]);
            onClose();
        } catch {
            toast.error("Bulk import failed");
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[1000px] w-[95vw] h-[85vh] p-0 flex flex-col overflow-hidden">
                <div className="p-6 border-b bg-accent/5 flex items-start justify-between">
                    <div>
                        <DialogTitle className="text-[18px] font-bold">Import Role Permissions</DialogTitle>
                        <p className="text-[12px] text-gray-500 mt-1">Upload an Excel file with Role, Pipeline, Stage, View, Edit, and Delete columns.</p>
                    </div>
                    {isReady && (
                        <div className="flex items-center gap-2">
                            <Button variant="ghostMuted" size="sm" onClick={() => setIsReady(false)}>
                                <X size={14} className="mr-1.5" /> Clear
                            </Button>
                            <Button size="sm" onClick={handleImport} disabled={isImporting}>
                                <Upload size={14} className="mr-1.5" /> {isImporting ? "Importing..." : `Import ${gridRows.length} Rows`}
                            </Button>
                        </div>
                    )}
                </div>

                <div className="flex-1 overflow-hidden">
                    {!isReady ? (
                        <div {...getRootProps()} className="h-full flex flex-col items-center justify-center p-10 cursor-pointer hover:bg-accent/5 transition-colors border-2 border-dashed border-gray-100 m-6 rounded-2xl">
                            <input {...getInputProps()} />
                            <div className="h-16 w-16 rounded-2xl bg-accent/10 flex items-center justify-center text-accent mb-4">
                                <FileUp size={32} />
                            </div>
                            <p className="text-[14px] font-bold text-gray-800">{isDragActive ? "Drop it!" : "Drag & Drop Excel file here"}</p>
                            <p className="text-[12px] text-gray-400 mt-1">or click to browse your files</p>
                        </div>
                    ) : (
                        <div className="h-full border-t flex flex-col bg-white">
                            <div className="flex-1 overflow-auto">
                                <DataGrid
                                    columns={[
                                        ...gridColumns,
                                        {
                                            key: "delete",
                                            name: "",
                                            width: 40,
                                            renderCell: ({ rowIdx }) => (
                                                <Button 
                                                    variant="ghostIconTightDanger"
                                                    onClick={() => setGridRows(prev => prev.filter((_, i) => i !== rowIdx))}
                                                    className="mx-auto"
                                                >
                                                    <Trash2 size={14} />
                                                </Button>
                                            )
                                        }
                                    ]}
                                    rows={gridRows}
                                    onRowsChange={setGridRows}
                                    className="rdg-light text-[13px]"
                                    rowHeight={38}
                                    headerRowHeight={42}
                                    style={{ height: "100%" }}
                                />
                            </div>
                            <div className="px-6 py-2 bg-gray-50 border-t flex items-center gap-3 text-[11px] text-gray-500">
                                <Check size={12} className="text-green-500" />
                                <span>Double-click a cell to edit. Valid Role and Stage names are required for successful mapping.</span>
                            </div>
                        </div>
                    )}
                </div>
            </DialogContent>
        </Dialog>
    );
}

export function RolePermissionsTab() {
    const { token } = useAuthToken();
    const dispatch = useAppDispatch();
    const [selectedRoleId, setSelectedRoleId] = React.useState("");
    const [isImporterOpen, setIsImporterOpen] = React.useState(false);
    const [selectedStageIds, setSelectedStageIds] = React.useState<string[]>([]);

    const { data: roles = EMPTY_ARRAY, isLoading: rolesLoading } = useGetRolesQuery(undefined, { skip: !token });
    const { data: pipelines = EMPTY_ARRAY, isLoading: pipelinesLoading } = useGetPipelinesQuery(undefined, { skip: !token });

    // Flatten all stages and sub-stages from all pipelines
    const allStagesFlattened = React.useMemo(() => {
        const flattened: FlattenedStage[] = [];
        pipelines.forEach((p) => {
            (p.stages as any[]).forEach((s) => {
                // Main stage
                flattened.push({
                    id: s.id,
                    name: s.name,
                    pipelineName: p.name,
                    type: "STAGE",
                });

                // Sub-stages (from stageName relation if populated)
                const subStages = s.stageName?.pipelineSubStages || s.subStages || [];
                subStages.forEach((ss: any) => {
                    flattened.push({
                        id: ss.id,
                        name: `↳ ${ss.name}`,
                        pipelineName: p.name,
                        type: "SUBSTAGE",
                    });
                });
            });
        });
        return flattened;
    }, [pipelines]);

    const {
        data: apiPermissions = EMPTY_ARRAY,
        isLoading: permissionsLoading,
        isFetching: permissionsFetching,
    } = useGetRoleStagePermissionsByRoleQuery(selectedRoleId, {
        skip: !token || !selectedRoleId,
        refetchOnMountOrArgChange: true,
    });

    // Redux slice state
    const localEntries = useAppSelector(selectPermissionsForRole(selectedRoleId));
    const isInSync = useAppSelector(selectIsInSyncWithServer(selectedRoleId));
    const dirtyStageIds = useAppSelector(selectDirtyStageIds(selectedRoleId));
    const hasCached = useAppSelector(selectHasCachedPermissions(selectedRoleId));

    const [bulkApplyPermissions] = useBulkApplyRoleStagePermissionsMutation();
    const [saving, setSaving] = React.useState(false);

    // Sync slice state when data changes
    const stageIdsKey = allStagesFlattened.map((s) => s.id).join(",");
    const permissionsKey = apiPermissions
        .map((p) => `${p.id}:${p.canView}:${p.canEdit}:${p.canDelete}`)
        .join(",");

    React.useEffect(() => {
        // Only set default role if not already set and roles are available and we are not still loading
        if (!selectedRoleId && !rolesLoading && roles.length > 0) {
            const firstId = roles[0].id;
            if (firstId && selectedRoleId !== firstId) {
                setSelectedRoleId(firstId);
            }
        }
    }, [selectedRoleId, roles, rolesLoading, setSelectedRoleId]);

    React.useEffect(() => {
        if (!selectedRoleId || allStagesFlattened.length === 0) return;
        dispatch(
            setServerPermissions({
                roleId: selectedRoleId,
                stageIds: allStagesFlattened.map((s) => s.id),
                permissions: apiPermissions,
            }),
        );
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedRoleId, permissionsKey, stageIdsKey]);

    // Auto-select stages that already have some permission applied
    React.useEffect(() => {
        if (!selectedRoleId || !apiPermissions) {
            setSelectedStageIds([]);
            return;
        }

        const accessibleIds = apiPermissions
            .filter(p => p.canView || p.canEdit || p.canDelete)
            .map(p => p.pipelineStageId || p.pipelineSubStageId || p.stageNameId)
            .filter((id): id is string => Boolean(id));

        // Use a stable key for comparison to avoid redundant state updates
        const nextKey = accessibleIds.sort().join(",");
        const currentKey = selectedStageIds.sort().join(",");

        if (nextKey !== currentKey) {
            setSelectedStageIds(accessibleIds);
        }
    }, [selectedRoleId, apiPermissions]); // selectedStageIds intentionally omitted to break potential loop if it was causing one

    const rows = React.useMemo(() => {
        return allStagesFlattened.map((stage) => {
            const entry = localEntries[stage.id];
            const apiPerm = apiPermissions.find(
                (p) =>
                    p.pipelineStageId === stage.id ||
                    p.pipelineSubStageId === stage.id ||
                    p.stageNameId === stage.id,
            ) ?? null;

            return {
                stageId: stage.id,
                stageName: stage.name,
                pipelineName: stage.pipelineName,
                type: stage.type,
                apiPermission: apiPerm,
                canView: entry?.canView ?? false,
                canEdit: entry?.canEdit ?? false,
                canDelete: entry?.canDelete ?? false,
                isDirty: entry?.isDirty ?? false,
            };
        });
    }, [allStagesFlattened, localEntries, apiPermissions]);

    const handleFlag = (stageId: string, flag: "canView" | "canEdit" | "canDelete", value: boolean) => {
        dispatch(setPermissionFlag({ roleId: selectedRoleId, stageId, flag, value }));
    };

    const handleBulkFlag = (flag: "canView" | "canEdit" | "canDelete" | "all", value: boolean) => {
        if (!selectedRoleId || selectedStageIds.length === 0) return;
        dispatch(setBulkPermissionFlag({
            roleId: selectedRoleId,
            stageIds: selectedStageIds,
            flag,
            value
        }));
        if (flag === "all" && !value) {
            // If revoking all, maybe clear selection or keep it?
        }
    };

    const handleSelectAllRows = (checked: boolean) => {
        if (checked) {
            setSelectedStageIds(rows.map(r => r.stageId));
        } else {
            setSelectedStageIds([]);
        }
    };

    const handleSelectRow = (stageId: string, checked: boolean) => {
        if (checked) {
            setSelectedStageIds(prev => [...prev, stageId]);
        } else {
            setSelectedStageIds(prev => prev.filter(id => id !== stageId));
        }
    };

    const handleSaveAll = async () => {
        if (!selectedRoleId) return;
        setSaving(true);
        const dirtyRows = rows.filter((r) => r.isDirty);

        const create: {
            pipelineStageId?: string;
            pipelineSubStageId?: string;
            canView: boolean;
            canEdit: boolean;
            canDelete: boolean;
        }[] = [];
        const update: {
            id: string;
            canView: boolean;
            canEdit: boolean;
            canDelete: boolean;
        }[] = [];
        const deleteIds: string[] = [];

        for (const row of dirtyRows) {
            const hasAny = row.canView || row.canEdit || row.canDelete;
            if (row.apiPermission) {
                if (!hasAny) {
                    deleteIds.push(row.apiPermission.id);
                } else {
                    update.push({
                        id: row.apiPermission.id,
                        canView: row.canView,
                        canEdit: row.canEdit,
                        canDelete: row.canDelete,
                    });
                }
            } else if (hasAny) {
                const item = {
                    canView: row.canView,
                    canEdit: row.canEdit,
                    canDelete: row.canDelete,
                    ...(row.type === "STAGE"
                        ? { pipelineStageId: row.stageId }
                        : { pipelineSubStageId: row.stageId }),
                };
                create.push(item);
            }
        }

        try {
            const result = await bulkApplyPermissions({
                roleId: selectedRoleId,
                create,
                update,
                deleteIds,
            }).unwrap();
            if (!result.success && result.errors.length > 0) {
                toast.error(
                    `${result.errors.length} operation(s) failed. First: ${result.errors[0]}`,
                );
            } else {
                dispatch(commitChanges(selectedRoleId));
                toast.success("Permissions saved");
            }
        } catch {
            toast.error("Failed to save permissions");
        } finally {
            setSaving(false);
        }
    };

    const handleDiscard = () => {
        dispatch(discardChanges(selectedRoleId));
    };

    const isLoading = rolesLoading || pipelinesLoading;
    const isPermissionsLoading = !hasCached && (permissionsLoading || permissionsFetching);
    const isPermissionsRefreshing = hasCached && permissionsFetching;
    const accessibleCount = apiPermissions.filter((p) => p.canView).length;
    const dirtyCount = dirtyStageIds.length;

    const handleDownloadExcel = () => {
        if (!selectedRoleId || rows.length === 0) return;

        const roleName = roles.find((r) => r.id === selectedRoleId)?.name || "Role";

        const data = rows.map((r) => ({
            "Stage / Sub-Stage": r.stageName,
            Pipeline: r.pipelineName,
            Type: r.type,
            View: r.canView ? "Yes" : "No",
            Edit: r.canEdit ? "Yes" : "No",
            Delete: r.canDelete ? "Yes" : "No",
            Status: r.apiPermission ? "Saved" : r.isDirty ? "Unsaved" : "-",
        }));

        const ws = XLSX.utils.json_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Permissions");

        // Set column widths
        const colWidths = [
            { wch: 30 }, // Stage
            { wch: 15 }, // Pipeline
            { wch: 10 }, // Type
            { wch: 8 }, // View
            { wch: 8 }, // Edit
            { wch: 8 }, // Delete
            { wch: 12 }, // Status
        ];
        ws["!cols"] = colWidths;

        XLSX.writeFile(wb, `${roleName}_Permissions_${new Date().toISOString().split("T")[0]}.xlsx`);
        toast.success("Excel file downloaded");
    };

    const handleDownloadSample = () => {
        const sampleData = [
            {
                Role: "TSC",
                "Stage / Sub-Stage": "New Lead",
                Pipeline: "Sales",
                Type: "STAGE",
                View: "Yes",
                Edit: "No",
                Delete: "No",
            },
            {
                Role: "AM",
                "Stage / Sub-Stage": "↳ Follow-up",
                Pipeline: "Sales",
                Type: "SUBSTAGE",
                View: "Yes",
                Edit: "Yes",
                Delete: "No",
            },
        ];

        const ws = XLSX.utils.json_to_sheet(sampleData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sample");
        ws["!cols"] = [{ wch: 30 }, { wch: 15 }, { wch: 10 }, { wch: 8 }, { wch: 8 }, { wch: 8 }];
        XLSX.writeFile(wb, `Role_Permissions_Sample.xlsx`);
        toast.info("Sample template downloaded");
    };

    return (
        <div className="space-y-5">
            <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 border-b border-border/60 pb-4">
                <div className="flex items-center gap-3">
                    <div className="h-9 w-9 rounded-xl bg-accent/10 flex items-center justify-center text-accent">
                        <Shield size={18} />
                    </div>
                    <div>
                        <h2 className="text-[18px] font-extrabold text-text font-['Lexend'] tracking-tight">
                            Role Permissions
                        </h2>
                        <p className="text-[12px] text-gray-700 mt-0.5">
                            Assign direct permissions to pipelines, stages, and sub-stages.
                        </p>
                    </div>
                </div>
            </div>

            {permissionsLoading ? (
                <Loading
                  layout="section"
                  message="Loading permissions…"
                  className="py-16"
                />
            ) : (
                <>
                    <RoleStagePermissionsImporter
                        isOpen={isImporterOpen}
                        onClose={() => setIsImporterOpen(false)}
                    />

                    <div className="flex items-center gap-3">
                        <Label className="text-[12px] font-semibold text-gray-600 shrink-0">Select Role</Label>
                        <ReactSelect
                            value={selectedRoleId}
                            onValueChange={setSelectedRoleId}
                            disabled={isLoading}
                            allowEmpty
                            emptyOptionLabel="Choose a role..."
                            placeholder="Choose a role..."
                            options={roles
                                .filter((role) => role.id)
                                .map((role) => ({
                                    value: role.id!,
                                    label: role.name,
                                }))}
                            aria-label="Select role"
                            triggerClassName="w-64 h-9 text-[13px] rounded-xl"
                        />
                        {selectedRoleId && (
                            <Badge variant="secondary" className="text-[11px]">
                                {accessibleCount} stage{accessibleCount !== 1 ? "s" : ""} accessible
                            </Badge>
                        )}
                    </div>
                    {selectedStageIds.length > 0 && (
                        <div className=" z-[60] animate-in fade-in slide-in-from-bottom-6 duration-400 w-full max-w-fit px-4">
                            <div className="bg-white/95 dark:bg-gray-950/95 backdrop-blur-md border border-white/40 shadow-[0_8px_30px_rgb(0,0,0,0.12)] rounded-[20px] p-2.5 flex flex-col md:flex-row items-center gap-3 md:gap-8">
                                <div className="flex items-center gap-3.5 pl-2.5 md:border-r border-border/50 md:pr-8">
                                    <div className="size-9 rounded-xl bg-accent text-white flex items-center justify-center shadow-lg shadow-accent/20 shrink-0">
                                        <Shield size={19} />
                                    </div>
                                    <div className="flex flex-col">
                                        <span className="text-[13px] font-bold text-gray-900 dark:text-gray-100 whitespace-nowrap leading-tight">
                                            {selectedStageIds.length} Stages Selected
                                        </span>
                                        <span className="text-[11px] text-gray-500 font-semibold font-['Lexend'] tracking-wide">
                                            BULK ACTIONS
                                        </span>
                                    </div>
                                </div>

                                <div className="flex flex-wrap items-center justify-center gap-2">
                                    <div className="flex items-center gap-1.5 p-1 bg-muted/30 rounded-xl">
                                        <Button
                                            variant="ghostSuccessRow"
                                            onClick={() => handleBulkFlag("canView", true)}
                                        >
                                            Grant View
                                        </Button>
                                        <Button
                                            variant="ghostInfoRow"
                                            onClick={() => handleBulkFlag("canEdit", true)}
                                        >
                                            Grant Edit
                                        </Button>
                                        <Button
                                            variant="ghostIndigoRow"
                                            onClick={() => handleBulkFlag("canDelete", true)}
                                        >
                                            Grant Delete
                                        </Button>
                                    </div>

                                    <div className="w-px h-5 bg-border/60 mx-1 hidden sm:block" />

                                    <Button
                                        variant="destructiveRowEmphasis"
                                        onClick={() => handleBulkFlag("all", false)}
                                    >
                                        <Trash2 size={13} className="mr-1.5" />
                                        Revoke All
                                    </Button>

                                    <Button
                                        variant="ghostMutedRowDismiss"
                                        onClick={() => setSelectedStageIds([])}
                                    >
                                        Cancel
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )}

                    {selectedRoleId && (
                        <div className="rounded-2xl border border-border bg-white/60 backdrop-blur-sm overflow-hidden">
                            <div className="px-4 py-3 border-b border-border/60 flex items-center justify-between">
                                <p className="text-[12px] text-gray-500">
                                    Select stages to manage their access in bulk. Use the floating bar to grant/revoke permissions.
                                </p>
                                {(isPermissionsLoading || isPermissionsRefreshing) && (
                                    <div className="flex items-center gap-1.5 text-[11px] text-gray-400">
                                        <RefreshCw size={12} className="animate-spin" />
                                        {isPermissionsRefreshing && <span>Refreshing…</span>}
                                    </div>
                                )}
                            </div>

                            <div className="overflow-x-auto">
                                <Table variant="transparent">
                                    <TableHeader>
                                        <TableRow className="bg-muted/40 border-b border-border hover:bg-muted/40">
                                            <TableHead className="w-[40px] pl-4">
                                                <Checkbox
                                                    checked={rows.length > 0 && selectedStageIds.length === rows.length}
                                                    onCheckedChange={(v) => handleSelectAllRows(!!v)}
                                                />
                                            </TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 pl-4">Stage / Sub-Stage</TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500">Pipeline</TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 text-center">View</TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 text-center">Edit</TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 text-center">Delete</TableHead>
                                            <TableHead className="text-[11px] font-bold uppercase tracking-wider text-gray-500 text-center">Status</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {rows.length === 0 ? (
                                            <TableRow>
                                                <TableCell colSpan={7} className="text-center py-10 text-[13px] text-gray-400">
                                                    No stages or sub-stages found in pipelines
                                                </TableCell>
                                            </TableRow>
                                        ) : (
                                            rows.map((row) => (
                                                <TableRow
                                                    key={row.stageId}
                                                    onClick={() => {
                                                        if (!isPermissionsLoading && !saving) {
                                                            handleSelectRow(row.stageId, !selectedStageIds.includes(row.stageId));
                                                        }
                                                    }}
                                                    className={cn(
                                                        "border-b border-border/60 transition-colors cursor-pointer group/row",
                                                        row.isDirty ? "bg-amber-50/40" : "hover:bg-muted/20",
                                                        selectedStageIds.includes(row.stageId) && "bg-accent/5",
                                                        row.type === "SUBSTAGE" && "bg-muted/5",
                                                    )}
                                                >
                                                    <TableCell className="py-3 pl-4">
                                                        <Checkbox
                                                            checked={selectedStageIds.includes(row.stageId)}
                                                            onCheckedChange={(v) => handleSelectRow(row.stageId, !!v)}
                                                            onClick={(e) => e.stopPropagation()}
                                                        />
                                                    </TableCell>
                                                    <TableCell className="py-3 pl-4">
                                                        <span className={cn(
                                                            "text-[13px] font-semibold text-text",
                                                            row.type === "SUBSTAGE" && "text-gray-600 font-medium ml-2"
                                                        )}>
                                                            {row.stageName}
                                                        </span>
                                                    </TableCell>
                                                    <TableCell className="py-3">
                                                        <span className="text-[12px] text-gray-500">{row.pipelineName}</span>
                                                    </TableCell>
                                                    <TableCell className="py-3 text-center">
                                                        <Checkbox
                                                            checked={row.canView}
                                                            className="pointer-events-none opacity-80"
                                                        />
                                                    </TableCell>
                                                    <TableCell className="py-3 text-center">
                                                        <Checkbox
                                                            checked={row.canEdit}
                                                            className="pointer-events-none opacity-80"
                                                        />
                                                    </TableCell>
                                                    <TableCell className="py-3 text-center">
                                                        <Checkbox
                                                            checked={row.canDelete}
                                                            className="pointer-events-none opacity-80"
                                                        />
                                                    </TableCell>
                                                    <TableCell className="py-3 text-center">
                                                        {row.isDirty ? (
                                                            <Badge variant="outline" className="text-[10px] border-amber-300 text-amber-600 bg-amber-50">
                                                                Unsaved
                                                            </Badge>
                                                        ) : row.apiPermission ? (
                                                            <Badge variant="secondary" className="text-[10px] bg-green-50 text-green-700 border-green-200">
                                                                <Check size={10} className="mr-1" /> Saved
                                                            </Badge>
                                                        ) : (
                                                            <span className="text-[11px] text-gray-300">—</span>
                                                        )}
                                                    </TableCell>
                                                </TableRow>
                                            ))
                                        )}
                                    </TableBody>
                                </Table>
                            </div>

                            {!isInSync && (
                                <div className="px-4 py-3 border-t border-border/60 bg-amber-50/40 flex items-center justify-between gap-3">
                                    <p className="text-[12px] text-amber-700">
                                        {dirtyStageIds.length} unsaved change{dirtyStageIds.length > 1 ? "s" : ""}
                                    </p>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            variant="ghostOutlineRow"
                                            onClick={handleDiscard}
                                            disabled={saving}
                                        >
                                            Discard
                                        </Button>
                                        <Button
                                            variant="accentRowSm"
                                            onClick={handleSaveAll}
                                            disabled={saving}
                                        >
                                            {saving ? (
                                                <RefreshCw size={12} className="mr-1.5 animate-spin" />
                                            ) : (
                                                <Check size={12} className="mr-1.5" />
                                            )}
                                            Save {dirtyStageIds.length} change{dirtyStageIds.length > 1 ? "s" : ""}
                                        </Button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}


                    {!selectedRoleId && !isLoading && (
                        <div className="flex flex-col items-center justify-center py-16 text-center rounded-2xl border-2 border-dashed border-gray-100">
                            <Shield size={36} className="text-gray-200 mb-3" />
                            <p className="text-[14px] font-semibold text-gray-700">Select a role to manage stage access</p>
                            <p className="text-[12px] text-gray-400 mt-1">
                                Choose a role above to view and edit its stage permissions.
                            </p>
                        </div>
                    )}
                </>
            )}


        </div>
    );
}
