import { Users, AlertTriangle, CheckCircle2 } from "lucide-react";
import { useQueries, useQuery } from "@tanstack/react-query";
import {
  getChildPositions,
  getEmployeesUnderPosition,
} from "@/user-management/services/api/positionService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useAuth } from "@/shared/context/AuthContext";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Avatar, AvatarFallback } from "@/shared/common/ui/avatar";
import { Badge } from "@/shared/common/ui/badge";
import type { PositionDto } from "@/user-management/dto/positions/positionDto";

/**
 * Direct reports of the currently-active position.
 *
 * 1. GET /positions/children/:myPositionId → direct child positions
 *    (each item has parentPositionId === myPositionId)
 * 2. For each child position, GET /positions/current/:childPositionId/employees
 *    → employees holding that position
 *
 * This bypasses the buggy /employees/immediate-child endpoint which was
 * returning peers (rows sharing the same position_id) instead of children.
 */
export const MyTeamPanel = () => {
  const { user, selectedPositionId } = useAuth();
  const localizedName = useLocalizedName();

  // Resolve the active position so we can use its `id` (not employeePositionId).
  const allPositions =
    user?.employee?.flatMap((emp) => emp.positions ?? []) ?? [];
  const activePosition =
    allPositions.find(
      (p) =>
        p.employeePositionId === selectedPositionId ||
        p.id === selectedPositionId,
    ) ?? allPositions[0];
  const myPositionId = activePosition?.id;

  const {
    data: childrenResp,
    isLoading: childrenLoading,
    error: childrenError,
  } = useQuery({
    queryKey: ["positionChildren", myPositionId],
    queryFn: () => getChildPositions(myPositionId!),
    enabled: !!myPositionId,
  });

  const childPositions: PositionDto[] = childrenResp?.data?.items ?? [];

  // Fetch employees per direct-child position in parallel.
  const employeeQueries = useQueries({
    queries: childPositions.map((cp) => ({
      queryKey: ["positionEmployees", cp.id],
      queryFn: () => getEmployeesUnderPosition(cp.id),
      enabled: !!cp.id,
    })),
  });

  if (childrenLoading) {
    return <Skeleton className="h-32 w-full rounded-xl mb-6" />;
  }

  if (childrenError) {
    return (
      <Card className="mb-6 border-red-200 bg-red-50">
        <CardContent className="p-4 text-sm text-red-700">
          Failed to load child positions:{" "}
          {(childrenError as Error).message}
        </CardContent>
      </Card>
    );
  }

  const totalEmployees = employeeQueries.reduce(
    (sum, q) => sum + ((q.data?.data?.items?.length ?? q.data?.data?.length) || 0),
    0,
  );

  return (
    <Card className="mb-6">
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <Users className="h-5 w-5" />
          My Team
          <Badge variant="secondary" className="ml-1">
            {totalEmployees}
          </Badge>
        </CardTitle>

        <div className="flex flex-wrap gap-2 text-xs mt-2 text-gray-500">
          <span>
            Acting as position id: <code>{myPositionId ?? "—"}</code>
          </span>
          <span>·</span>
          <span>
            {childPositions.length} direct child position
            {childPositions.length === 1 ? "" : "s"}
          </span>
        </div>
      </CardHeader>

      <CardContent>
        {childPositions.length === 0 ? (
          <p className="text-sm text-gray-500">
            No child positions exist under your current position.
          </p>
        ) : (
          <div className="space-y-4">
            {childPositions.map((cp, idx) => {
              const empQuery = employeeQueries[idx];
              const employeesRaw =
                empQuery?.data?.data?.items ?? empQuery?.data?.data ?? [];
              const employees = Array.isArray(employeesRaw) ? employeesRaw : [];

              // Sanity-check: every returned position should have
              // parentPositionId === myPositionId. Anything else is suspicious.
              const isCorrectChild = cp.parentPositionId === myPositionId;

              return (
                <div
                  key={cp.id}
                  className={`rounded-xl border p-3 ${
                    isCorrectChild
                      ? "bg-white"
                      : "bg-amber-50 border-amber-200"
                  }`}
                >
                  <div className="flex items-center gap-2 mb-3">
                    <Badge variant="outline">
                      {localizedName(cp.name) || cp.key}
                    </Badge>
                    {!isCorrectChild && (
                      <span
                        className="inline-flex items-center gap-1 text-xs text-amber-700"
                        title={`Expected parentPositionId=${myPositionId}, got ${cp.parentPositionId}`}
                      >
                        <AlertTriangle className="h-3 w-3" /> wrong parent
                      </span>
                    )}
                    <span className="text-xs text-gray-500 ml-auto">
                      {empQuery?.isLoading
                        ? "loading…"
                        : `${employees.length} employee${employees.length === 1 ? "" : "s"}`}
                    </span>
                  </div>

                  {empQuery?.error ? (
                    <p className="text-xs text-red-600">
                      Failed to load employees for this position
                    </p>
                  ) : employees.length === 0 && !empQuery?.isLoading ? (
                    <p className="text-xs text-gray-500">
                      No employees currently hold this position.
                    </p>
                  ) : (
                    <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-2">
                      {employees.map((emp: any) => {
                        const name = localizedName(emp.name);
                        const initials = name
                          ?.split(" ")
                          .map((s: string) => s[0])
                          .filter(Boolean)
                          .slice(0, 2)
                          .join("")
                          .toUpperCase();
                        return (
                          <li
                            key={emp.id}
                            className="flex items-center gap-2 rounded-lg border bg-white p-2 shadow-sm"
                          >
                            <Avatar className="h-8 w-8">
                              <AvatarFallback>
                                {initials || "?"}
                              </AvatarFallback>
                            </Avatar>
                            <div className="min-w-0">
                              <p className="font-medium truncate text-xs">
                                {name}
                              </p>
                            </div>
                            <CheckCircle2 className="h-3 w-3 text-green-500 ml-auto" />
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
};
