import { useMemo, useState } from "react";
import { Activity, AlertCircle, BarChart3, Info } from "lucide-react";
import { useLocalizedName } from "@/shared/common/localizedName";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Progress } from "@/shared/common/ui/progress";
import {
  ReportFilterOption,
  SectorReportFilters,
} from "@/record-management/components/sectorReports/SectorReportFilters";
import { RecordSummarySection } from "@/record-management/components/sectorReports/RecordSummarySection";
import { SectorOverviewTable } from "@/record-management/components/sectorReports/SectorOverviewTable";
import { MonthlyActivitySection } from "@/record-management/components/sectorReports/MonthlyActivitySection";
import {
  useChildPositions,
  usePositionsByRankAndUnit,
  useSectorReport,
} from "@/record-management/components/sectorReports/useSectorReport";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUnit } from "@/user-management/hooks/useUnit";
import {
  LocalizedText,
  RecordPeriodTotals,
} from "@/record-management/components/sectorReports/types";

const emptyTotals: RecordPeriodTotals = {
  today: 0,
  thisWeek: 0,
  thisMonth: 0,
  allTime: 0,
};

const SECTOR_POSITION_RANK = 1;

const sumTotals = (items: RecordPeriodTotals[]) =>
  items.reduce<RecordPeriodTotals>(
    (total, item) => ({
      today: total.today + item.today,
      thisWeek: total.thisWeek + item.thisWeek,
      thisMonth: total.thisMonth + item.thisMonth,
      allTime: total.allTime + item.allTime,
    }),
    { ...emptyTotals },
  );

export default function SectorReportsPage() {
  const [unitId, setUnitId] = useState("");
  const [sectorId, setSectorId] = useState("");
  const [groupId, setGroupId] = useState("");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const localizedName = useLocalizedName();
  const { userDetails } = useAuthUser();
  const organizationId = userDetails?.employee?.[0]?.organizationId ?? "";
  const { getList } = useUnit();

  const { data: unitsResponse, isLoading: unitsLoading } = getList(
    organizationId,
    { take: 1000, skip: 0 },
    Boolean(organizationId),
  );

  const { data: sectorPositions = [], isLoading: sectorsLoading } =
    usePositionsByRankAndUnit(unitId, SECTOR_POSITION_RANK);
  const { data, isLoading, isFetching, isError, refetch } = useSectorReport({
    unitId: unitId || undefined,
    positionId: groupId || sectorId || undefined,
    from: fromDate || undefined,
    to: toDate || undefined,
  });

  const nameOf = (name: LocalizedText) =>
    typeof name === "string"
      ? name
      : localizedName({ am: name?.am ?? "", en: name?.en ?? "" }) || "—";

  const positions = useMemo<ReportFilterOption[]>(
    () =>
      sectorPositions.map((position) => ({
        id: String(position.id),
        label: localizedName(position.name) || position.key || "Unnamed sector",
        parentId: position.parentPositionId,
        unitId: position.unitId ? String(position.unitId) : null,
      })),
    [sectorPositions, localizedName],
  );

  const units = useMemo<ReportFilterOption[]>(
    () =>
      (unitsResponse?.data?.items ?? []).map((unit: any) => ({
        id: String(unit.id),
        label: localizedName(unit.name) || unit.key || "Unnamed unit",
      })),
    [unitsResponse?.data?.items, localizedName],
  );

  const parentIds = useMemo(
    () => new Set(positions.map((item) => item.parentId).filter(Boolean)),
    [positions],
  );
  const sectors = useMemo(() => {
    const topLevel = positions.filter(
      (item) => !item.parentId || parentIds.has(item.id),
    );
    return topLevel.length ? topLevel : positions;
  }, [positions, parentIds]);
  const selectedSector = sectors.find((item) => item.id === sectorId);
  const { data: childPositions = [], isLoading: groupsLoading } =
    useChildPositions(selectedSector?.id ?? "");

  const groups = useMemo<ReportFilterOption[]>(() => {
    const byUnitId = new Map<string, ReportFilterOption>();
    childPositions.forEach((position: any) => {
      if (!position.unitId) return;
      if (!byUnitId.has(position.id)) {
        byUnitId.set(position.id, {
          id: position.id,
          label:
            localizedName(position?.name) ||
            position.unit?.key ||
            "Unnamed group",
        });
      }
    });
    return Array.from(byUnitId.values());
  }, [childPositions, localizedName, units]);

  const reports = data?.items ?? [];
  const incoming = sumTotals(reports.map((item) => item.incoming));
  const outgoing = sumTotals(reports.map((item) => item.outgoing));
  const monthlyTotal = incoming.thisMonth + outgoing.thisMonth;
  const processingBalance = monthlyTotal
    ? Math.round(
        (Math.min(incoming.thisMonth, outgoing.thisMonth) /
          Math.max(incoming.thisMonth, outgoing.thisMonth)) *
          100,
      )
    : 0;
  const outgoingShare = monthlyTotal
    ? Math.round((outgoing.thisMonth / monthlyTotal) * 100)
    : 0;

  return (
    <main className="mx-auto w-full max-w-[1440px] space-y-6 px-4 py-5 sm:px-6 lg:px-8">
      <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="mb-1 flex items-center gap-2 text-primary">
            <BarChart3 className="size-5" />
            <span className="text-sm font-semibold">Record activity</span>
          </div>
          <h1 className="text-2xl font-bold tracking-tight">Sector reports</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Monitor incoming and outgoing record activity across sectors
          </p>
          {selectedSector && (
            <p className="mt-3 text-xs text-muted-foreground">
              Viewing:{" "}
              <span className="font-semibold text-foreground">
                {groups.find((item) => item.id === groupId)?.label ??
                  selectedSector.label}
              </span>
            </p>
          )}
        </div>
        <SectorReportFilters
          units={units}
          sectors={sectors}
          groups={groups}
          unitId={unitId}
          sectorId={sectorId}
          groupId={groupId}
          fromDate={fromDate}
          toDate={toDate}
          loading={sectorsLoading || unitsLoading || groupsLoading}
          refreshing={isFetching}
          onUnitChange={(value) => {
            setUnitId(value);
            setSectorId("");
            setGroupId("");
          }}
          onSectorChange={(value) => {
            setSectorId(value);
            setGroupId("");
          }}
          onGroupChange={setGroupId}
          onFromDateChange={(value) => {
            setFromDate(value);
            if (toDate && value > toDate) setToDate(value);
          }}
          onToDateChange={setToDate}
          onReset={() => {
            setUnitId("");
            setSectorId("");
            setGroupId("");
            setFromDate("");
            setToDate("");
          }}
          onRefresh={() => refetch()}
        />
      </div>

      {!unitId ? (
        <div className="rounded-xl border bg-card p-12 text-center">
          <BarChart3 className="mx-auto mb-3 size-8 text-muted-foreground" />
          <p className="font-semibold">Select a unit</p>
          <p className="text-sm text-muted-foreground">
            Choose a unit to view its sectors and record activity.
          </p>
        </div>
      ) : isLoading ? (
        <div className="space-y-4">
          <Skeleton className="h-56 w-full rounded-xl" />
          <Skeleton className="h-56 w-full rounded-xl" />
        </div>
      ) : isError ? (
        <div className="flex min-h-48 flex-col items-center justify-center gap-3 rounded-xl border bg-card p-8 text-center">
          <AlertCircle className="size-8 text-destructive" />
          <div>
            <p className="font-semibold">Unable to load sector activity</p>
            <p className="text-sm text-muted-foreground">
              Check the reporting service and try again.
            </p>
          </div>
          <Button variant="outline" onClick={() => refetch()}>
            Try again
          </Button>
        </div>
      ) : reports.length === 0 ? (
        <div className="rounded-xl border bg-card p-12 text-center">
          <BarChart3 className="mx-auto mb-3 size-8 text-muted-foreground" />
          <p className="font-semibold">No report data found</p>
          <p className="text-sm text-muted-foreground">
            There is no record activity for the selected scope.
          </p>
        </div>
      ) : (
        <div className="space-y-6">
          <div>
            <p className="text-3xl font-semibold tracking-tight text-emerald-900 dark:text-emerald-400">
              {monthlyTotal.toLocaleString()}
            </p>
            <p className="mt-1 text-[10px] font-semibold uppercase tracking-[0.2em] text-muted-foreground">
              Total record volume — this month
            </p>
          </div>

          <div className="grid gap-3 lg:grid-cols-[1fr_1fr_2fr]">
            <RecordSummarySection
              direction="incoming"
              totals={incoming}
              allTimeLabel={fromDate || toDate ? "Selected range" : undefined}
            />
            <RecordSummarySection
              direction="outgoing"
              totals={outgoing}
              allTimeLabel={fromDate || toDate ? "Selected range" : undefined}
            />
            <section className="rounded-lg border bg-card p-5 shadow-sm">
              <div className="flex items-center justify-between border-b pb-3">
                <h2 className="text-sm font-semibold">Performance index</h2>
                <Info className="size-4 text-muted-foreground" />
              </div>
              <div className="mt-5 grid gap-6 sm:grid-cols-[100px_1fr] sm:items-center">
                <div
                  className="relative mx-auto flex size-24 items-center justify-center rounded-full bg-[conic-gradient(hsl(var(--primary))_0_var(--score),hsl(var(--muted))_var(--score)_100%)] [--score:0%]"
                  style={
                    {
                      "--score": `${processingBalance}%`,
                    } as React.CSSProperties
                  }
                >
                  <div className="flex size-16 items-center justify-center rounded-full bg-card text-lg font-semibold">
                    {processingBalance}%
                  </div>
                </div>
                <div className="space-y-5">
                  <div>
                    <div className="mb-2 flex justify-between text-xs">
                      <span>Processing balance</span>
                      <strong>{processingBalance}%</strong>
                    </div>
                    <Progress value={processingBalance} className="h-1.5" />
                  </div>
                  <div>
                    <div className="mb-2 flex justify-between text-xs">
                      <span>Outgoing share</span>
                      <strong>{outgoingShare}%</strong>
                    </div>
                    <Progress value={outgoingShare} className="h-1.5" />
                  </div>
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    <Activity className="size-3.5 text-primary" />
                    {reports.length} active reporting entries
                  </div>
                </div>
              </div>
            </section>
          </div>
          <MonthlyActivitySection reports={reports} getName={nameOf} />
          <SectorOverviewTable
            reports={reports}
            getName={nameOf}
            hasDateRange={Boolean(fromDate || toDate)}
            onSelect={
              sectorId
                ? undefined
                : (id) => {
                    setSectorId(id);
                    setGroupId("");
                    window.scrollTo({ top: 0, behavior: "smooth" });
                  }
            }
          />
        </div>
      )}
    </main>
  );
}
