"use client";

import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useRepositories } from "@/di/repository-provider";
import { useT } from "@/shared/i18n/client";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { Button } from "@/presentation/components/ui/button";
import { Switch } from "@/presentation/components/ui/switch";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/presentation/components/ui/dialog";
import type { RolesCatalog } from "@/domain/entities/internal-role";

interface RoleSettingsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  catalog: RolesCatalog | null;
  /** Refetch the catalog after a save so counts refresh everywhere. */
  onSaved: () => void;
}

export default function RoleSettingsDialog({
  open,
  onOpenChange,
  catalog,
  onSaved,
}: RoleSettingsDialogProps) {
  const t = useT();
  const container = useRepositories();

  const [activeRoleId, setActiveRoleId] = useState<number | null>(null);
  // roleId -> enabled permission codes (working copy).
  const [working, setWorking] = useState<Record<number, string[]>>({});

  useEffect(() => {
    if (!open || !catalog) return;
    const next: Record<number, string[]> = {};
    for (const r of catalog.roles) next[r.id] = [...r.permissions];
    setWorking(next);
    setActiveRoleId((prev) => prev ?? catalog.roles[0]?.id ?? null);
  }, [open, catalog]);

  const saveMutation = useApiMutation(
    (changed: { id: number; permissions: string[] }[]) =>
      Promise.all(
        changed.map((c) => container.internalRoleRepository.updatePermissions(c.id, c.permissions))
      ),
    {
      successMessage: t.internalUsers.toasts.roleUpdated,
      onSuccess: () => {
        onSaved();
        onOpenChange(false);
      },
    }
  );

  const toggle = (code: string, on: boolean) => {
    if (activeRoleId == null) return;
    setWorking((prev) => {
      const cur = new Set(prev[activeRoleId] ?? []);
      if (on) cur.add(code);
      else cur.delete(code);
      return { ...prev, [activeRoleId]: Array.from(cur) };
    });
  };

  const handleSave = () => {
    if (!catalog) return;
    const changed = catalog.roles
      .filter((r) => {
        const cur = working[r.id] ?? [];
        const origSet = new Set(r.permissions);
        return cur.length !== r.permissions.length || cur.some((c) => !origSet.has(c));
      })
      .map((r) => ({ id: r.id, permissions: working[r.id] ?? [] }));
    if (changed.length === 0) {
      onOpenChange(false);
      return;
    }
    saveMutation.mutate(changed);
  };

  const activeEnabled = new Set(activeRoleId != null ? working[activeRoleId] ?? [] : []);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>{t.internalUsers.roleSettings.title}</DialogTitle>
          <DialogDescription>{t.internalUsers.roleSettings.subtitle}</DialogDescription>
        </DialogHeader>

        {/* Role tabs */}
        <div className="flex flex-wrap gap-2">
          {catalog?.roles.map((r) => {
            const count = working[r.id]?.length ?? r.count;
            const active = r.id === activeRoleId;
            return (
              <button
                key={r.id}
                type="button"
                onClick={() => setActiveRoleId(r.id)}
                className={cn(
                  "rounded-full px-3 py-1.5 text-sm font-medium transition-colors",
                  active
                    ? "bg-primary text-primary-foreground shadow-sm"
                    : "bg-muted/60 text-muted-foreground hover:bg-muted"
                )}
              >
                {(t.internalUsers.roleLabels[r.code] ?? r.label) + ` (${count})`}
              </button>
            );
          })}
        </div>

        {/* Permission toggles for the active role */}
        <div className="-mr-1 max-h-[50vh] space-y-2 overflow-y-auto pr-1">
          {!catalog
            ? Array.from({ length: 6 }).map((_, i) => (
                <Skeleton key={i} className="h-[58px] w-full rounded-lg" />
              ))
            : catalog.permissions.map((perm) => {
                const label = t.internalUsers.permissionLabels[perm.code] ?? perm.label ?? perm.code;
                return (
                  <div
                    key={perm.code}
                    className="flex items-center justify-between gap-3 rounded-lg border border-border px-4 py-3"
                  >
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-foreground">{label}</p>
                      <p className="font-mono text-xs text-muted-foreground">{perm.code}</p>
                    </div>
                    <Switch
                      checked={activeEnabled.has(perm.code)}
                      onCheckedChange={(v) => toggle(perm.code, v)}
                    />
                  </div>
                );
              })}
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
            {t.common.cancel}
          </Button>
          <Button type="button" onClick={handleSave} disabled={saveMutation.loading || !catalog}>
            {saveMutation.loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            {t.common.save}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
