import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, RefreshCw, RotateCcw, Users } from "lucide-react";
import { RoleGuard } from "../../components/auth/RoleGuard";
import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import {
  fetchUserProjectionStatus,
  reconcileUserProjection,
  resetUserProjection,
} from "../../lib/adminApi";
import { t } from "../../lib/i18n";
import { getAdminDateLocale } from "../../lib/locale";

function formatDateTime(value?: string) {
  if (!value) {
    return "-";
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return new Intl.DateTimeFormat(getAdminDateLocale(), {
    dateStyle: "medium",
    timeStyle: "medium",
  }).format(date);
}

function ProjectionStatusBadge({
  ready,
  status,
}: {
  ready: boolean;
  status: string;
}) {
  if (ready) {
    return (
      <Badge variant="success">
        {t("ui.admin.user_projection.status.ready", "ready")}
      </Badge>
    );
  }
  if (status === "failed") {
    return (
      <Badge variant="warning">
        {t("ui.admin.user_projection.status.failed", "failed")}
      </Badge>
    );
  }
  return (
    <Badge variant="secondary">
      {status
        ? status
        : t("ui.admin.user_projection.status.not_ready", "not ready")}
    </Badge>
  );
}

function UserProjectionContent() {
  const queryClient = useQueryClient();
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ["user-projection-status"],
    queryFn: fetchUserProjectionStatus,
  });

  const invalidate = async () => {
    await queryClient.invalidateQueries({
      queryKey: ["user-projection-status"],
    });
  };

  const reconcileMutation = useMutation({
    mutationFn: reconcileUserProjection,
    onSuccess: invalidate,
  });

  const resetMutation = useMutation({
    mutationFn: resetUserProjection,
    onSuccess: invalidate,
  });

  const handleReset = () => {
    const confirmed = window.confirm(
      t(
        "msg.admin.user_projection.reset_confirm",
        "Rebuild user projection from the Kratos source of truth?",
      ),
    );
    if (confirmed) {
      resetMutation.mutate();
    }
  };

  const isWorking = reconcileMutation.isPending || resetMutation.isPending;
  const actionResult = reconcileMutation.data ?? resetMutation.data;
  const actionError = reconcileMutation.error ?? resetMutation.error;

  return (
    <main className="space-y-6 flex flex-col h-[calc(100vh-theme(spacing.32))]">
      <header className="flex flex-shrink-0 flex-wrap items-start justify-between gap-4 sticky top-[-2.5rem] z-20 -mt-4 bg-background/95 pb-2 pt-4 backdrop-blur">
        <div className="flex min-w-0 items-start gap-3">
          <div className="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-primary/15 bg-primary/10 text-primary">
            <Users size={20} />
          </div>
          <div className="space-y-2">
            <h2 className="text-3xl font-semibold">
              {t(
                "ui.admin.user_projection.title",
                "User Projection Management",
              )}
            </h2>
            <p className="text-sm text-muted-foreground">
              {t(
                "msg.admin.user_projection.subtitle",
                "Review and sync the Kratos user read model.",
              )}
            </p>
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={() => reconcileMutation.mutate()}
            disabled={isWorking}
          >
            <RefreshCw size={16} />
            {t("ui.admin.user_projection.actions.reconcile", "Re-sync")}
          </Button>
          <Button
            type="button"
            variant="destructive"
            onClick={handleReset}
            disabled={isWorking}
          >
            <RotateCcw size={16} />
            {t(
              "ui.admin.user_projection.actions.reset",
              "Reset and rebuild",
            )}
          </Button>
        </div>
      </header>

      {isError ? (
        <section className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
          {(error as Error)?.message ||
            t(
              "msg.admin.user_projection.load_error",
              "Failed to load projection status.",
            )}
        </section>
      ) : null}

      {actionResult ? (
        <section className="rounded-lg border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200">
          {t(
            "msg.admin.user_projection.action_success",
            "Refreshed the projection for {{count}} users.",
            { count: actionResult.syncedUsers },
          )}
        </section>
      ) : null}

      {actionError ? (
        <section className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-sm text-destructive">
          {(actionError as Error)?.message ||
            t(
              "msg.admin.user_projection.action_error",
              "Projection operation failed.",
            )}
        </section>
      ) : null}

      <section className="rounded-lg border border-border bg-card p-5">
        <div className="flex items-center gap-3 border-b border-border pb-4">
          <div>
            <h3 className="text-lg font-bold flex items-center gap-2">
              {t(
                "ui.admin.user_projection.card.title",
                "Kratos users projection",
              )}
            </h3>
            <p className="text-sm text-muted-foreground">
              {t(
                "ui.admin.user_projection.card.description",
                "Current user read model state referenced by backend DB statistics.",
              )}
            </p>
          </div>
        </div>

        {isLoading ? (
          <div className="py-8 text-sm text-muted-foreground">
            {t("ui.admin.user_projection.loading", "Loading")}
          </div>
        ) : (
          <dl className="grid gap-4 py-5 sm:grid-cols-2 lg:grid-cols-4">
            <div>
              <dt className="text-sm text-muted-foreground">
                {t("ui.admin.user_projection.summary.status", "Status")}
              </dt>
              <dd className="mt-1">
                <ProjectionStatusBadge
                  ready={data?.ready ?? false}
                  status={data?.status ?? "unknown"}
                />
              </dd>
            </div>
            <div>
              <dt className="text-sm text-muted-foreground">
                {t(
                  "ui.admin.user_projection.summary.projected_users",
                  "Projected users",
                )}
              </dt>
              <dd className="mt-1 text-xl font-semibold tabular-nums">
                {data?.projectedUsers ?? 0}
              </dd>
            </div>
            <div>
              <dt className="text-sm text-muted-foreground">
                {t(
                  "ui.admin.user_projection.summary.last_synced",
                  "Last synced",
                )}
              </dt>
              <dd className="mt-1 text-sm">
                {formatDateTime(data?.lastSyncedAt)}
              </dd>
            </div>
            <div>
              <dt className="text-sm text-muted-foreground">
                {t(
                  "ui.admin.user_projection.summary.updated_at",
                  "Updated at",
                )}
              </dt>
              <dd className="mt-1 text-sm">
                {formatDateTime(data?.updatedAt)}
              </dd>
            </div>
          </dl>
        )}

        {data?.lastError ? (
          <div className="flex gap-2 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-200">
            <AlertTriangle className="mt-0.5 shrink-0" size={16} />
            <span>{data.lastError}</span>
          </div>
        ) : null}
      </section>
    </main>
  );
}

export default function UserProjectionPage() {
  return (
    <RoleGuard
      roles={["super_admin"]}
      fallback={
      <main className="p-6 md:p-8">
        <section className="rounded-lg border border-border bg-card p-5">
          <h2 className="text-lg font-semibold">
            {t(
              "ui.admin.user_projection.forbidden.title",
              "Access denied",
            )}
          </h2>
          <p className="mt-2 text-sm text-muted-foreground">
            {t(
              "msg.admin.user_projection.forbidden.description",
              "This screen is only available to super_admin users.",
            )}
          </p>
        </section>
      </main>
      }
    >
      <UserProjectionContent />
    </RoleGuard>
  );
}
