"use client";

import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { Printer, Building2, User, ArrowUp, ArrowDown, Minus } from "lucide-react";
import { apiGet } from "@/lib/api";
import type { MonthlyReportDTO, MonthlyReportKpi } from "@/lib/types";
import { isManagerTier } from "@/lib/rbac";
import { formatMetric } from "@/lib/utils";
import { KPI_CATEGORY_LABEL } from "@/lib/labels";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { PageHeader, StatCard, Spinner, EmptyState } from "@/components/common";

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

function scoreColor(pct: number): string {
  if (pct >= 90) return "text-success";
  if (pct >= 60) return "text-warning";
  return "text-destructive";
}

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

  const today = new Date();
  const [year, setYear] = React.useState(today.getFullYear());
  const [month, setMonth] = React.useState(today.getMonth() + 1);
  const years = [today.getFullYear() - 1, today.getFullYear(), today.getFullYear() + 1];

  const report = useQuery({
    queryKey: ["monthly-report", year, month],
    queryFn: () => apiGet<MonthlyReportDTO>(`/api/reports/monthly?year=${year}&month=${month}`),
    enabled: manager,
  });

  if (!manager) {
    return (
      <EmptyState
        title="Manager access required"
        description="The monthly report is available to Manager, Admin and Super Admin roles."
      />
    );
  }

  const data = report.data;
  const printedOn = today.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });

  return (
    <div>
      <PageHeader title="Monthly KPI Report" subtitle="Department & personal performance for the selected month">
        <Select className="no-print h-8 w-auto text-xs" value={String(month)} onChange={(e) => setMonth(Number(e.target.value))}>
          {MONTHS.map((m, i) => (
            <option key={m} value={i + 1}>{m}</option>
          ))}
        </Select>
        <Select className="no-print h-8 w-auto text-xs" value={String(year)} onChange={(e) => setYear(Number(e.target.value))}>
          {years.map((y) => (
            <option key={y} value={y}>{y}</option>
          ))}
        </Select>
        <Button className="no-print" onClick={() => window.print()}>
          <Printer className="size-4" /> Print / Save PDF
        </Button>
      </PageHeader>

      {report.isLoading || !data ? (
        <Spinner />
      ) : (
        <div className="print-area space-y-6">
          {/* Print-only report heading */}
          <div className="hidden print:block">
            <h1 className="text-2xl font-bold">Monthly KPI Report</h1>
            <p className="text-sm">
              {MONTHS[month - 1]} {year} · Generated {printedOn}
            </p>
            <hr className="my-3" />
          </div>

          <div className="text-sm text-muted-foreground print:hidden">
            Reporting period: <span className="font-medium text-foreground">{MONTHS[month - 1]} {year}</span>
          </div>

          {/* Summary scorecards */}
          <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatCard label="Department Score" value={`${data.departmentScore}%`} accent="primary" hint="weighted" />
            <StatCard label="Personal Score" value={`${data.personalScore}%`} accent="primary" hint="average" />
            <StatCard label="Department KPIs" value={data.totals.departmentKpis} />
            <StatCard label="Staff Tracked" value={data.totals.staff} />
          </div>

          {/* ── Department section ── */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Building2 className="size-4" /> Department KPIs by Company
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-5">
              {data.department.length === 0 ? (
                <EmptyState title="No department KPIs" />
              ) : (
                data.department.map((g) => (
                  <div key={g.companyId ?? "_none"} className="break-inside-avoid">
                    <div className="mb-1.5 flex items-center justify-between border-b border-border pb-1">
                      <span className="text-sm font-semibold">{g.companyName}</span>
                      <span className={`text-sm font-bold ${scoreColor(g.score)}`}>{g.score}%</span>
                    </div>
                    <KpiTable kpis={g.kpis} />
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          {/* ── Personal section ── */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <User className="size-4" /> Personal KPIs by Staff
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-5">
              {data.personal.length === 0 ? (
                <EmptyState title="No personal KPIs" />
              ) : (
                data.personal.map((g) => (
                  <div key={g.userId ?? "_none"} className="break-inside-avoid">
                    <div className="mb-1.5 flex items-center justify-between border-b border-border pb-1">
                      <span className="text-sm font-semibold">
                        {g.name}
                        {g.position && <span className="font-normal text-muted-foreground"> · {g.position}</span>}
                      </span>
                      <span className={`text-sm font-bold ${scoreColor(g.score)}`}>{g.score}%</span>
                    </div>
                    <KpiTable kpis={g.kpis} />
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          <p className="hidden text-xs text-muted-foreground print:block">
            Marketing KPI &amp; Task Tracking System — confidential.
          </p>
        </div>
      )}
    </div>
  );
}

function MoMCell({ k }: { k: MonthlyReportKpi }) {
  if (k.prevActual === null) return <span className="text-muted-foreground">—</span>;
  // Direction is judged by attainment (toward target), not raw value, so it's
  // correct for cost KPIs (where lower is better) too.
  const prevPct = k.target ? Math.min(100, Math.round((k.prevActual / k.target) * 100)) : 0;
  const improved = k.pct >= prevPct;
  const flat = (k.delta ?? 0) === 0;
  const Icon = flat ? Minus : improved ? ArrowUp : ArrowDown;
  const color = flat ? "text-muted-foreground" : improved ? "text-success" : "text-destructive";
  const sign = (k.delta ?? 0) > 0 ? "+" : "";
  return (
    <span className={`inline-flex items-center justify-end gap-0.5 ${color}`}>
      <Icon className="size-3" />
      {sign}
      {formatMetric(k.delta ?? 0, k.unit)}
    </span>
  );
}

function KpiTable({ kpis }: { kpis: MonthlyReportKpi[] }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="text-left text-xs uppercase text-muted-foreground">
            <th className="py-1.5 pr-3">KPI</th>
            <th className="py-1.5 pr-3 text-right">Target</th>
            <th className="py-1.5 pr-3 text-right">Actual</th>
            <th className="py-1.5 pr-3 text-right">vs last mo</th>
            <th className="py-1.5 text-right">Attainment</th>
          </tr>
        </thead>
        <tbody>
          {kpis.map((k) => (
            <React.Fragment key={k.id}>
              <tr className="border-t border-border">
                <td className="py-1.5 pr-3">
                  <div className="font-medium">{k.name}</div>
                  <div className="flex flex-wrap gap-1">
                    {k.category && k.category !== "OTHER" && (
                      <Badge variant="outline">{KPI_CATEGORY_LABEL[k.category] ?? k.category}</Badge>
                    )}
                    {k.channels.map((c) => (
                      <span key={c} className="text-[11px] text-muted-foreground">{c}</span>
                    ))}
                  </div>
                </td>
                <td className="py-1.5 pr-3 text-right">{formatMetric(k.target, k.unit)}</td>
                <td className="py-1.5 pr-3 text-right">{formatMetric(k.actual, k.unit)}</td>
                <td className="py-1.5 pr-3 text-right text-xs">
                  <MoMCell k={k} />
                </td>
                <td className={`py-1.5 text-right font-semibold ${scoreColor(k.pct)}`}>{k.pct}%</td>
              </tr>
              {k.note && (
                <tr>
                  <td colSpan={5} className="pb-1.5 pr-3">
                    <div className={`rounded-md border px-2 py-1 text-[11px] ${k.pct < 60 ? "border-warning/40 bg-warning/10 text-warning" : "border-border bg-secondary/40 text-muted-foreground"}`}>
                      <span className="font-semibold">Remark: </span>{k.note}
                    </div>
                  </td>
                </tr>
              )}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
}
