import { useCallback } from "react";
import { Folder, Network } from "lucide-react";
import { Link } from "react-router-dom";
import {
  DashboardWidgetList,
  DismissibleAlert,
  LoadingFrame,
  StatusBadge,
  useDashboardWidgetData,
  type ApiSettings,
  type DashboardWidgetConfiguration
} from "@govoplan/core-webui";
import {
  listFileSpaces,
  type FileSpace
} from "../../api/files";

export default function FileSpacesWidget({
  settings,
  refreshKey,
  configuration
}: {
  settings: ApiSettings;
  refreshKey: number;
  configuration: DashboardWidgetConfiguration;
}) {
  const maxItems = numberSetting(configuration.maxItems, 6, 1, 16);
  const includeConnectors = configuration.includeConnectors !== false;
  const load = useCallback(async () => {
    const response = await listFileSpaces(settings);
    return response.spaces
      .filter(
        (space) =>
          includeConnectors || (space.space_type ?? "managed") === "managed"
      )
      .sort((left, right) => left.label.localeCompare(right.label))
      .slice(0, maxItems);
  }, [includeConnectors, maxItems, settings]);
  const { data: spaces, loading, error } = useDashboardWidgetData(
    load,
    refreshKey
  );

  return (
    <LoadingFrame loading={loading} label="Loading file spaces">
      {error && (
        <DismissibleAlert tone="warning" resetKey={error}>
          {error}
        </DismissibleAlert>
      )}
      <DashboardWidgetList
        emptyText="No file spaces are available."
        items={(spaces ?? []).map((space) => ({
          id: space.id,
          title: space.label,
          detail: spaceDescription(space),
          meta: space.owner_type === "group" ? "Group" : "Personal",
          leading:
            space.space_type === "connector" ? (
              <Network size={17} aria-hidden="true" />
            ) : (
              <Folder size={17} aria-hidden="true" />
            ),
          trailing: space.read_only ? (
            <StatusBadge status="locked" label="Read only" />
          ) : undefined,
          to: "/files"
        }))}
      />
      <div className="dashboard-contribution-footer">
        <Link className="btn btn-secondary" to="/files">
          Open files
        </Link>
      </div>
    </LoadingFrame>
  );
}

function spaceDescription(space: FileSpace): string {
  if (space.space_type !== "connector") {
    return space.description || "Managed storage";
  }
  return [space.provider, space.library_id, space.remote_path]
    .filter(Boolean)
    .join(" · ") || "Connected storage";
}

function numberSetting(
  value: unknown,
  fallback: number,
  minimum: number,
  maximum: number
): number {
  const numeric = typeof value === "number" ? value : Number(value);
  return Number.isFinite(numeric)
    ? Math.max(minimum, Math.min(maximum, Math.floor(numeric)))
    : fallback;
}
