"use client";

import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { apiGet } from "@/lib/api";
import type { MeDTO, ReportDTO, CompanyDTO, DepartmentDTO, KpiDTO } from "@/lib/types";
import { isManagerTier } from "@/lib/rbac";
import { formatMetric, progressPct } from "@/lib/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select } from "@/components/ui/select";
import { Progress, RadialProgress } from "@/components/ui/progress";
import { InfoHint } from "@/components/ui/info-hint";
import { PageHeader, StatCard, Spinner, EmptyState } from "@/components/common";

export function DashboardView() {
  const { data: session } = useSession();
  const role = session?.user?.role;
  const manager = isManagerTier(role);

  const [companyId, setCompanyId] = React.useState("");
  const [departmentId, setDepartmentId] = React.useState("");

  const me = useQuery({ queryKey: ["me"], queryFn: () => apiGet<MeDTO>("/api/me") });
  const report = useQuery({
    queryKey: ["reports", "dashboard"],
    queryFn: () => apiGet<ReportDTO>("/api/reports"),
    enabled: manager,
  });
  const companies = useQuery({
    queryKey: ["companies"],
    queryFn: () => apiGet<CompanyDTO[]>("/api/companies"),
  });
  const departments = useQuery({
    queryKey: ["departments"],
    queryFn: () => apiGet<DepartmentDTO[]>("/api/departments"),
  });
  const deptKpis = useQuery({
    queryKey: ["kpis", "department", companyId, departmentId],
    queryFn: () =>
      apiGet<KpiDTO[]>(
        `/api/kpis?type=DEPARTMENT${companyId ? `&companyId=${companyId}` : ""}${
          departmentId ? `&departmentId=${departmentId}` : ""
        }`
      ),
  });

  if (me.isLoading) return <Spinner />;
  const data = me.data;
  const companyName = (id: string) =>
    companies.data?.find((c) => c.id === id)?.name ?? "Unassigned";
  const deptName = (id: string) =>
    departments.data?.find((d) => d.id === id)?.name ?? "Unassigned";
  const scopeLabel =
    [departmentId && deptName(departmentId), companyId && companyName(companyId)]
      .filter(Boolean)
      .join(" · ") || "All companies & departments";

  return (
    <div>
      <PageHeader
        title={`Welcome, ${session?.user?.name?.split(" ")[0] ?? ""}`}
        subtitle={
          data?.user.position
            ? `${data.user.position} · personal performance`
            : "Team performance overview"
        }
      >
        <Select
          className="h-9 w-auto text-sm"
          value={departmentId}
          onChange={(e) => setDepartmentId(e.target.value)}
        >
          <option value="">All departments</option>
          {(departments.data ?? []).map((d) => (
            <option key={d.id} value={d.id}>
              {d.name}
            </option>
          ))}
        </Select>
        <Select
          className="h-9 w-auto text-sm"
          value={companyId}
          onChange={(e) => setCompanyId(e.target.value)}
        >
          <option value="">All companies</option>
          {(companies.data ?? []).map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </Select>
      </PageHeader>

      {/* Personal stats */}
      <div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatCard label="My Tasks" value={data?.stats.tasksTotal ?? 0} hint="assigned to me"
          info="Total number of tasks currently assigned to you, across all statuses." />
        <StatCard
          label="Completed"
          value={data?.stats.tasksCompleted ?? 0}
          accent="success"
          hint="all-time"
          info="How many of your tasks are marked Completed (all-time, not just this month)."
        />
        <StatCard
          label="In Progress"
          value={data?.stats.inProgress ?? 0}
          accent="warning"
          info="Your tasks currently in the In Progress status."
        />
        <StatCard
          label="KPI Delta Logged"
          value={data?.stats.totalDelta ?? 0}
          accent="primary"
          hint="attributed value"
          info="The total KPI impact you've logged from your tasks (sum of the metric values attributed via 'Log KPI impact' in the Weekly Log)."
        />
      </div>

      {/* Personal KPI rings (FR-4) */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>My Personal KPIs</CardTitle>
        </CardHeader>
        <CardContent>
          {data && data.personalKpis.length > 0 ? (
            <div className="grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-4">
              {data.personalKpis.map((k) => (
                <div key={k.id} className="flex flex-col items-center gap-2 text-center">
                  <RadialProgress value={k.pct} sublabel={`${k.pct}%`} />
                  <div>
                    <div className="flex items-center justify-center gap-1 text-sm font-medium">
                      {k.name}
                      {k.description && <InfoHint text={k.description} />}
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {formatMetric(k.currentValue, k.unit)} / {formatMetric(k.targetValue, k.unit)}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No personal KPIs yet"
              description={
                data?.user.position
                  ? `No PERSONAL indicators are assigned to the position "${data.user.position}" yet.`
                  : "Personal KPIs are matched to a staff position. Admin/Manager accounts don't have one."
              }
            />
          )}
        </CardContent>
      </Card>

      {/* Department KPIs — scoped by the company/department selector (all users) */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Department KPIs · {scopeLabel}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {deptKpis.isLoading ? (
            <Spinner />
          ) : deptKpis.data && deptKpis.data.length > 0 ? (
            deptKpis.data.map((k) => {
              const pct = progressPct(k.currentValue, k.targetValue);
              return (
                <div key={k.id}>
                  <div className="mb-1 flex items-center justify-between text-sm">
                    <span className="font-medium">
                      {k.name}
                      {!companyId && (
                        <span className="ml-2 text-xs text-muted-foreground">
                          {k.company?.name ?? "Unassigned"}
                        </span>
                      )}
                    </span>
                    <span className="text-muted-foreground">
                      {formatMetric(k.currentValue, k.unit)} / {formatMetric(k.targetValue, k.unit)} ({pct}%)
                    </span>
                  </div>
                  <Progress value={pct} />
                </div>
              );
            })
          ) : (
            <EmptyState
              title="No department KPIs"
              description={
                companyId
                  ? "This company/department has no KPI indicators yet."
                  : "No department KPI indicators have been created yet."
              }
            />
          )}
        </CardContent>
      </Card>

      {/* Team section (manager-tier) */}
      {manager && (
        <>
          <div className="mb-3 grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatCard
              label="Team Score"
              value={`${report.data?.teamScore ?? 0}%`}
              accent="primary"
              hint="weighted KPI attainment"
              info="Overall department-KPI attainment, weighted by each KPI's weightage (%). 100% means every KPI hit its target."
            />
            <StatCard label="Team Tasks" value={report.data?.totals.tasks ?? 0}
              info="Total tasks across all staff (in the current report scope)." />
            <StatCard
              label="Team Completed"
              value={report.data?.totals.completed ?? 0}
              accent="success"
              info="Tasks across the team marked Completed."
            />
            <StatCard label="Active Staff" value={report.data?.totals.staff ?? 0}
              info="Number of active staff members counted in this view." />
          </div>
        </>
      )}
    </div>
  );
}
