import { useEffect, useState } from "react";
import { isAxiosError } from "axios";
import { Shield } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@edr/ui-common";

import { api } from "@/auth/http";

interface LocaleText {
  en?: string;
  am?: string;
}

interface RoleRecord {
  id: string;
  key: string;
  name?: LocaleText;
}

interface PermissionRecord {
  id: string;
  key: string;
  name?: LocaleText;
}

interface ListResponse<T> {
  items?: T[];
  data?: T[];
}

const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
  value?.en ?? value?.am ?? fallback;

const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
  if (!payload) {
    return [] as T[];
  }

  if (Array.isArray(payload)) {
    return payload;
  }

  return payload.items ?? payload.data ?? [];
};

const RolesPage = () => {
  const [roles, setRoles] = useState<RoleRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedRole, setSelectedRole] = useState<RoleRecord | null>(null);
  const [rolePermissions, setRolePermissions] = useState<PermissionRecord[]>([]);
  const [rolePermissionsLoading, setRolePermissionsLoading] = useState(false);
  const [rolePermissionsError, setRolePermissionsError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const loadRoles = async () => {
      setLoading(true);
      setErrorMessage(null);

      try {
        const response = await api.get<ListResponse<RoleRecord>>("/roles");

        if (!isMounted) {
          return;
        }

        setRoles(
          getItems(response.data).sort((left, right) =>
            getLocaleLabel(left.name, left.key).localeCompare(
              getLocaleLabel(right.name, right.key),
            ),
          ),
        );
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setErrorMessage(
          isAxiosError(error)
            ? error.response?.data?.message ?? "Unable to load roles."
            : "Unable to load roles.",
        );
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    void loadRoles();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    if (!selectedRole) {
      setRolePermissions([]);
      setRolePermissionsError(null);
      setRolePermissionsLoading(false);
      return;
    }

    let isMounted = true;

    const loadRolePermissions = async () => {
      setRolePermissionsLoading(true);
      setRolePermissionsError(null);

      try {
        const response = await api.get<ListResponse<PermissionRecord>>(
          `/role-permissions/given-first/${selectedRole.id}`,
        );

        if (!isMounted) {
          return;
        }

        setRolePermissions(
          getItems(response.data).sort((left, right) =>
            getLocaleLabel(left.name, left.key).localeCompare(
              getLocaleLabel(right.name, right.key),
            ),
          ),
        );
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setRolePermissionsError(
          isAxiosError(error)
            ? error.response?.data?.message ?? "Unable to load role details."
            : "Unable to load role details.",
        );
      } finally {
        if (isMounted) {
          setRolePermissionsLoading(false);
        }
      }
    };

    void loadRolePermissions();

    return () => {
      isMounted = false;
    };
  }, [selectedRole]);

  return (
    <section className="p-6">
      <div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
        <div className="space-y-3">
          <p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
            User Management
          </p>
          <div className="flex items-start justify-between gap-4">
            <div>
              <h1 className="text-3xl font-semibold text-foreground">Roles</h1>
              <p className="mt-3 max-w-2xl text-sm text-muted-foreground">
                Browse freight backoffice roles and their internal keys in a simple grid view.
              </p>
            </div>
            <div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
              {roles.length} roles
            </div>
          </div>
        </div>

        {loading ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            Loading roles...
          </div>
        ) : errorMessage ? (
          <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
            {errorMessage}
          </div>
        ) : roles.length ? (
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {roles.map((role) => (
              <button
                key={role.id}
                type="button"
                onClick={() => setSelectedRole(role)}
                className="rounded-2xl border border-border bg-background p-5 text-left transition hover:border-border/80 hover:bg-accent/20"
              >
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-sky-50 text-sky-600 dark:bg-sky-950/40 dark:text-sky-300">
                    <Shield className="h-5 w-5" />
                  </div>
                  <div className="min-w-0">
                    <p className="truncate text-sm font-semibold text-foreground">
                      {getLocaleLabel(role.name, role.key)}
                    </p>
                    <p className="truncate text-xs text-muted-foreground">{role.key}</p>
                  </div>
                </div>
              </button>
            ))}
          </div>
        ) : (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            No roles available.
          </div>
        )}
      </div>

      <Dialog open={Boolean(selectedRole)} onOpenChange={(open) => !open && setSelectedRole(null)}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>{selectedRole ? getLocaleLabel(selectedRole.name, selectedRole.key) : "Role details"}</DialogTitle>
            <DialogDescription>
              {selectedRole
                ? `Review the permission set assigned to ${getLocaleLabel(selectedRole.name, selectedRole.key)}.`
                : undefined}
            </DialogDescription>
          </DialogHeader>

          {selectedRole ? (
            <div className="space-y-6">
              <div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Role name
                  </p>
                  <p className="mt-2 text-sm font-semibold text-foreground">
                    {getLocaleLabel(selectedRole.name, selectedRole.key)}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Role key
                  </p>
                  <p className="mt-2 font-mono text-sm text-foreground">{selectedRole.key}</p>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <h2 className="text-sm font-semibold text-foreground">Permissions</h2>
                  <div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
                    {rolePermissions.length} permissions
                  </div>
                </div>

                {rolePermissionsLoading ? (
                  <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                    Loading role details...
                  </div>
                ) : rolePermissionsError ? (
                  <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
                    {rolePermissionsError}
                  </div>
                ) : rolePermissions.length ? (
                  <div className="grid gap-3 md:grid-cols-2">
                    {rolePermissions.map((permission) => (
                      <article
                        key={permission.id}
                        className="rounded-2xl border border-border/70 bg-background/80 p-4 shadow-sm"
                      >
                        <p className="truncate text-sm font-semibold leading-5 text-foreground">
                          {getLocaleLabel(permission.name, permission.key)}
                        </p>
                        <p className="mt-1 truncate font-mono text-xs text-muted-foreground/90">
                          {permission.key}
                        </p>
                      </article>
                    ))}
                  </div>
                ) : (
                  <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                    No permissions are assigned to this role.
                  </div>
                )}
              </div>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </section>
  );
};

export default RolesPage;
