"use client";

import { useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { motion } from "motion/react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import {
  ArrowRight,
  Building2,
  CalendarCheck,
  Clock,
  ShieldAlert,
  TrendingUp,
  Users,
  Network,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DatePicker } from "@/components/ui/date-picker";
import { AppSpinner } from "@/components/ui/app-loader";
import { AnalyticsChartTooltip } from "@/components/ui/analytics-chart-tooltip";
import { staggerContainer, staggerItem } from "@/lib/motion";
import { useManagerAnalytics } from "@/hooks/use-manager-analytics";
import { getPerformanceGrade } from "@/lib/scoring-utils";
import { cn } from "@/lib/utils";
import { DASHBOARD_DEFAULT_DATE_FROM, DASHBOARD_DEFAULT_DATE_TO } from "@/lib/date-utils";

const CHART_COLORS = [
  "hsl(var(--chart-1))",
  "hsl(var(--chart-2))",
  "hsl(var(--chart-3))",
  "hsl(var(--chart-4))",
];

const HEALTH_COLORS = {
  strong: "hsl(142 50% 42%)",
  onTrack: "hsl(var(--chart-1))",
  coaching: "hsl(38 80% 48%)",
  atRisk: "hsl(0 62% 50%)",
};

function scoreTone(score: number) {
  if (score >= 80) return "text-emerald-600 dark:text-emerald-400";
  if (score >= 70) return "text-primary";
  if (score >= 60) return "text-amber-600 dark:text-amber-400";
  return "text-red-600 dark:text-red-400";
}

function healthBucket(score: number): keyof typeof HEALTH_COLORS {
  if (score >= 80) return "strong";
  if (score >= 70) return "onTrack";
  if (score >= 60) return "coaching";
  return "atRisk";
}

function roleLabel(role?: string | null) {
  switch (role) {
    case "MANAGER":
      return "Manager";
    case "UNIT_LEAD":
      return "Unit Lead";
    case "UPPER_MANAGEMENT":
      return "Top Management";
    case "SUPER_ADMIN":
      return "Super Admin";
    default:
      return role || "User";
  }
}

function Metric({
  label,
  value,
  hint,
  icon: Icon,
}: {
  label: string;
  value: ReactNode;
  hint?: string;
  icon: typeof Users;
}) {
  return (
    <div className="px-4 py-3.5 min-w-0">
      <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
        <Icon className="h-3 w-3 text-primary" />
        {label}
      </div>
      <div className="mt-1 text-xl font-semibold tracking-tight tabular-nums text-foreground">
        {value}
      </div>
      {hint ? (
        <p className="mt-0.5 text-xs text-muted-foreground truncate">{hint}</p>
      ) : null}
    </div>
  );
}

function ChartCard({
  title,
  subtitle,
  children,
  className,
}: {
  title: string;
  subtitle?: string;
  children: ReactNode;
  className?: string;
}) {
  return (
    <motion.section
      variants={staggerItem}
      className={cn(
        "rounded-xl border border-border bg-card overflow-visible",
        className,
      )}
    >
      <div className="px-4 py-3 border-b border-border">
        <h3 className="text-sm font-semibold text-foreground">{title}</h3>
        {subtitle ? (
          <p className="text-xs text-muted-foreground mt-0.5">{subtitle}</p>
        ) : null}
      </div>
      <div className="p-4 overflow-visible">{children}</div>
    </motion.section>
  );
}

export function ManagerHomeDashboard() {
  const { data: session } = useSession();
  const [dateFrom, setDateFrom] = useState(DASHBOARD_DEFAULT_DATE_FROM);
  const [dateTo, setDateTo] = useState(DASHBOARD_DEFAULT_DATE_TO);
  const { data, loading, error, reload } = useManagerAnalytics(
    dateFrom,
    dateTo,
  );

  const systemRole = session?.user?.role;
  const displayRole = roleLabel(systemRole);

  const deptChart = useMemo(() => {
    if (!data) return [];
    return data.byDepartment.map((d) => ({
      name: d.label.length > 12 ? `${d.label.slice(0, 10)}…` : d.label,
      fullName: d.label,
      overall: d.avgOverall,
      attendance: d.avgAttendance,
      hours: Math.round(d.totalHours || 0),
      people: d.headcount,
    }));
  }, [data]);

  const leadChart = useMemo(() => {
    if (!data) return [];
    return [...data.byLead]
      .filter((l) => l.scoredCount > 0 || l.headcount > 0)
      .sort((a, b) => b.avgOverall - a.avgOverall)
      .slice(0, 8)
      .map((l) => ({
        name: (l.lead?.name || l.label || "").split(" ")[0],
        fullName: l.lead?.name || l.label,
        overall: l.avgOverall,
        people: l.headcount,
        hours: Math.round(l.totalHours || 0),
      }));
  }, [data]);

  const performanceHealth = useMemo(() => {
    const buckets = {
      strong: { key: "strong", label: "Strong (80+)", count: 0 },
      onTrack: { key: "onTrack", label: "On track (70–79)", count: 0 },
      coaching: { key: "coaching", label: "Needs coaching (60–69)", count: 0 },
      atRisk: { key: "atRisk", label: "At risk (<60)", count: 0 },
    };
    const scored = (data?.employees || []).filter((e) => e.hasData);
    for (const e of scored) {
      buckets[healthBucket(e.overallScore)].count += 1;
    }
    const total = scored.length || 1;
    return Object.values(buckets).map((b) => ({
      ...b,
      pct: Math.round((b.count / total) * 1000) / 10,
      fill: HEALTH_COLORS[b.key as keyof typeof HEALTH_COLORS],
    }));
  }, [data]);

  if (loading && !data) {
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center gap-3">
        <AppSpinner className="h-8 w-8" />
        <p className="text-sm text-muted-foreground">
          Building your organization overview…
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-xl border border-border bg-card p-8 text-center space-y-3">
        <p className="text-sm text-destructive">{error}</p>
        <Button variant="outline" size="sm" onClick={reload}>
          Retry
        </Button>
      </div>
    );
  }

  if (!data) return null;

  const { overview } = data;
  const managedDepts =
    data.meta.managedDepartments?.length || overview.departmentCount;

  return (
    <motion.div
      className="space-y-5"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      <motion.div variants={staggerItem} className="space-y-4">
        <div className="space-y-1 min-w-0">
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-2xl font-semibold tracking-tight text-foreground">
              Dashboard
            </h2>
            <Badge variant="secondary" className="tabular-nums">
              {displayRole}
            </Badge>
          </div>
          <p className="text-sm text-muted-foreground max-w-2xl">
            Welcome back, {session?.user?.name || "there"}. Bird&apos;s-eye view
            of your managed departments, team leads, and workforce health.
          </p>
        </div>
        <div className="flex flex-nowrap items-center gap-2 overflow-x-auto pb-0.5">
          <DatePicker
            value={dateFrom}
            onChange={setDateFrom}
            max={dateTo}
            className="shrink-0"
            buttonClassName="h-9 w-[140px]"
          />
          <span className="shrink-0 text-xs text-muted-foreground">to</span>
          <DatePicker
            value={dateTo}
            onChange={setDateTo}
            min={dateFrom}
            className="shrink-0"
            buttonClassName="h-9 w-[140px]"
          />
          <Button
            variant="ghost"
            size="sm"
            className="h-9 shrink-0 text-xs"
            onClick={() => {
              setDateFrom(DASHBOARD_DEFAULT_DATE_FROM);
              setDateTo(DASHBOARD_DEFAULT_DATE_TO);
            }}
          >
            Reset
          </Button>
          <Button asChild size="sm" className="h-9 shrink-0">
            <Link href="/dashboard/analytics">
              Open Analytics
              <ArrowRight className="ml-1.5 h-3.5 w-3.5" />
            </Link>
          </Button>
        </div>
      </motion.div>

      <motion.div
        variants={staggerItem}
        className="rounded-xl border border-border bg-card overflow-hidden shadow-sm"
      >
        <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 divide-x divide-y xl:divide-y-0 divide-border">
          <Metric
            label="Workforce"
            value={overview.headcount}
            hint={`${overview.scoredCount} scored`}
            icon={Users}
          />
          <Metric
            label="Avg overall"
            value={
              <span className={scoreTone(overview.avgOverall)}>
                {overview.avgOverall.toFixed(1)}%
                <span className="ml-1 text-sm font-medium text-muted-foreground">
                  {getPerformanceGrade(overview.avgOverall)}
                </span>
              </span>
            }
            hint="Weighted team average"
            icon={TrendingUp}
          />
          <Metric
            label="Attendance"
            value={`${overview.avgAttendance.toFixed(1)}%`}
            hint="Average present rate"
            icon={CalendarCheck}
          />
          <Metric
            label="Hours logged"
            value={`${overview.totalHours.toFixed(0)}h`}
            hint={
              overview.expectedHours > 0
                ? `${overview.hoursUtilization}% of expected`
                : "Period total"
            }
            icon={Clock}
          />
          <Metric
            label="Departments"
            value={managedDepts}
            hint={`${overview.leadCount} team leads`}
            icon={Building2}
          />
          <Metric
            label="Needs attention"
            value={overview.needsAttention.length}
            hint="Score under 70% or gaps"
            icon={ShieldAlert}
          />
        </div>
      </motion.div>

      <div className="grid gap-4 xl:grid-cols-3">
        <ChartCard
          title="Department performance"
          subtitle="Average overall score by department"
          className="xl:col-span-2"
        >
          {deptChart.length === 0 ? (
            <p className="text-sm text-muted-foreground py-10 text-center">
              No department data in this range.
            </p>
          ) : (
            <div className="h-72">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={deptChart}
                  margin={{ top: 8, right: 8, left: 0, bottom: 8 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    className="stroke-border"
                  />
                  <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                  <YAxis domain={[0, 100]} tick={{ fontSize: 11 }} />
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        labelFormatter={(_, payload) =>
                          String(payload?.[0]?.payload?.fullName || "")
                        }
                        valueFormatter={(v, name, item) => {
                          if (typeof v === "number") {
                            if (name === "Overall") {
                              return `${v.toFixed(1)}% · ${item.payload?.people ?? 0} people`;
                            }
                            if (name === "Attendance") {
                              return `${v.toFixed(1)}%`;
                            }
                          }
                          return v;
                        }}
                      />
                    }
                  />
                  <Bar
                    dataKey="overall"
                    name="Overall"
                    fill={CHART_COLORS[0]}
                    radius={[6, 6, 0, 0]}
                  />
                  <Bar
                    dataKey="attendance"
                    name="Attendance"
                    fill={CHART_COLORS[1]}
                    radius={[6, 6, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </ChartCard>

        <ChartCard
          title="Performance health"
          subtitle="Workforce score bands in your scope"
        >
          {performanceHealth.every((b) => b.count === 0) ? (
            <p className="text-sm text-muted-foreground py-10 text-center">
              No scored employees yet.
            </p>
          ) : (
            <div className="space-y-4 py-1">
              <div className="flex h-4 w-full overflow-hidden rounded-full bg-muted">
                {performanceHealth
                  .filter((b) => b.count > 0)
                  .map((b) => (
                    <div
                      key={b.key}
                      className="h-full"
                      style={{
                        width: `${b.pct}%`,
                        backgroundColor: b.fill,
                      }}
                      title={`${b.label}: ${b.count}`}
                    />
                  ))}
              </div>
              <ul className="space-y-2">
                {performanceHealth.map((b) => (
                  <li
                    key={b.key}
                    className="flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm"
                  >
                    <span className="inline-flex items-center gap-2">
                      <span
                        className="h-2.5 w-2.5 rounded-sm"
                        style={{ backgroundColor: b.fill }}
                      />
                      {b.label}
                    </span>
                    <span className="font-semibold tabular-nums">
                      {b.count}{" "}
                      <span className="font-normal text-muted-foreground">
                        ({b.pct}%)
                      </span>
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </ChartCard>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <ChartCard
          title="Team lead performance"
          subtitle="Average overall score by unit / team lead"
        >
          {leadChart.length === 0 ? (
            <p className="text-sm text-muted-foreground py-10 text-center">
              No team leads in your managed scope.
            </p>
          ) : (
            <div className="h-72">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={leadChart}
                  layout="vertical"
                  margin={{ top: 4, right: 12, left: 8, bottom: 4 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    className="stroke-border"
                  />
                  <XAxis
                    type="number"
                    domain={[0, 100]}
                    tick={{ fontSize: 11 }}
                  />
                  <YAxis
                    type="category"
                    dataKey="name"
                    width={72}
                    tick={{ fontSize: 11 }}
                  />
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        labelFormatter={(_, payload) =>
                          String(payload?.[0]?.payload?.fullName || "")
                        }
                        valueFormatter={(v, _name, item) =>
                          typeof v === "number"
                            ? `${v.toFixed(1)}% · ${item.payload?.people ?? 0} people`
                            : v
                        }
                      />
                    }
                  />
                  <Bar
                    dataKey="overall"
                    name="Overall"
                    fill={CHART_COLORS[2]}
                    radius={[0, 6, 6, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </ChartCard>

        <ChartCard
          title="Department hours"
          subtitle="Logged hours by department in the selected range"
        >
          {deptChart.length === 0 ? (
            <p className="text-sm text-muted-foreground py-10 text-center">
              No hours data in this range.
            </p>
          ) : (
            <div className="h-72">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={deptChart}
                  margin={{ top: 8, right: 8, left: 0, bottom: 8 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    className="stroke-border"
                  />
                  <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                  <YAxis tick={{ fontSize: 11 }} />
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        labelFormatter={(_, payload) =>
                          String(payload?.[0]?.payload?.fullName || "")
                        }
                        valueFormatter={(v) =>
                          typeof v === "number" ? `${v}h` : v
                        }
                      />
                    }
                  />
                  <Bar
                    dataKey="hours"
                    name="Hours"
                    fill={CHART_COLORS[3]}
                    radius={[6, 6, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </ChartCard>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="px-4 py-3 border-b border-border flex items-center justify-between gap-2">
            <div>
              <h3 className="text-sm font-semibold text-foreground">
                Top performers
              </h3>
              <p className="text-xs text-muted-foreground">
                Highest overall scores in your scope
              </p>
            </div>
            <Network className="h-4 w-4 text-muted-foreground" />
          </div>
          <ul className="divide-y divide-border">
            {overview.topPerformers.length === 0 ? (
              <li className="px-4 py-8 text-sm text-muted-foreground text-center">
                No scored performers yet.
              </li>
            ) : (
              overview.topPerformers.map((e: any, i: number) => (
                <li key={e.id}>
                  <Link
                    href={`/dashboard/users/${e.id}`}
                    className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40 transition-colors"
                  >
                    <span className="w-5 text-xs tabular-nums text-muted-foreground">
                      {i + 1}
                    </span>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-foreground truncate">
                        {e.name}
                      </p>
                      <p className="text-xs text-muted-foreground truncate">
                        {e.position || "—"} · {e.department || "—"}
                      </p>
                    </div>
                    <span
                      className={cn(
                        "text-sm font-semibold tabular-nums",
                        scoreTone(e.overallScore),
                      )}
                    >
                      {e.overallScore.toFixed(1)}%
                    </span>
                  </Link>
                </li>
              ))
            )}
          </ul>
        </motion.section>

        <motion.section
          variants={staggerItem}
          className="rounded-xl border border-border bg-card overflow-hidden"
        >
          <div className="px-4 py-3 border-b border-border flex items-center justify-between gap-2">
            <div>
              <h3 className="text-sm font-semibold text-foreground">
                Needs attention
              </h3>
              <p className="text-xs text-muted-foreground">
                Lowest scores or open performance gaps
              </p>
            </div>
            <ShieldAlert className="h-4 w-4 text-amber-500" />
          </div>
          <ul className="divide-y divide-border">
            {overview.needsAttention.length === 0 ? (
              <li className="px-4 py-8 text-sm text-muted-foreground text-center">
                No attention flags in this range.
              </li>
            ) : (
              overview.needsAttention.map((e: any) => (
                <li key={e.id}>
                  <Link
                    href={`/dashboard/users/${e.id}`}
                    className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-foreground truncate">
                        {e.name}
                      </p>
                      <p className="text-xs text-muted-foreground truncate">
                        {e.alerts?.[0] || e.position || "—"}
                      </p>
                    </div>
                    <span
                      className={cn(
                        "text-sm font-semibold tabular-nums",
                        scoreTone(e.overallScore),
                      )}
                    >
                      {e.overallScore.toFixed(1)}%
                    </span>
                  </Link>
                </li>
              ))
            )}
          </ul>
        </motion.section>
      </div>
    </motion.div>
  );
}
