"use client";

import { useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { motion } from "motion/react";
import { ChevronDown, ChevronLeft, ChevronRight, Search } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

export type DesignationPerson = {
  id: string;
  name: string;
  position?: string | null;
  overallScore: number;
  grade: string;
  totalHours?: number;
  hasData?: boolean;
};

const GROUPS_PER_PAGE = 4;
const PREVIEW_COUNT = 5;

function scoreBarColor(score: number): string {
  if (score >= 80) return "bg-emerald-500/80";
  if (score >= 70) return "bg-primary/80";
  if (score >= 60) return "bg-amber-500/80";
  return "bg-destructive/70";
}

export function DesignationPerformancePanel({
  people,
  title = "Designation-wise performance",
  subtitle = "Who is performing best within each designation",
  className,
  headerExtra,
}: {
  people: DesignationPerson[];
  title?: string;
  subtitle?: string;
  className?: string;
  headerExtra?: ReactNode;
}) {
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(0);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});

  const groups = useMemo(() => {
    const map = new Map<string, DesignationPerson[]>();
    for (const person of people) {
      if (person.hasData === false) continue;
      const key = (person.position || "").trim() || "Unspecified";
      const list = map.get(key);
      if (list) list.push(person);
      else map.set(key, [person]);
    }

    const q = query.trim().toLowerCase();
    let rows = Array.from(map.entries()).map(([position, members]) => {
      const ranked = [...members].sort(
        (a, b) => b.overallScore - a.overallScore,
      );
      const avg =
        ranked.reduce((s, e) => s + e.overallScore, 0) / (ranked.length || 1);
      return {
        position,
        people: ranked,
        count: ranked.length,
        avgOverall: Math.round(avg * 10) / 10,
      };
    });

    if (q) {
      rows = rows.filter(
        (g) =>
          g.position.toLowerCase().includes(q) ||
          g.people.some((p) => p.name.toLowerCase().includes(q)),
      );
    }

    rows.sort((a, b) => a.position.localeCompare(b.position));
    return rows;
  }, [people, query]);

  const pageCount = Math.max(1, Math.ceil(groups.length / GROUPS_PER_PAGE));
  const safePage = Math.min(page, pageCount - 1);
  const pageGroups = groups.slice(
    safePage * GROUPS_PER_PAGE,
    safePage * GROUPS_PER_PAGE + GROUPS_PER_PAGE,
  );

  return (
    <section
      className={cn(
        "rounded-xl border border-border bg-card overflow-hidden",
        className,
      )}
    >
      <div className="px-4 py-3 border-b border-border flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
        <div className="min-w-0">
          <h3 className="text-sm font-semibold text-foreground">{title}</h3>
          <p className="text-xs text-muted-foreground mt-0.5">{subtitle}</p>
        </div>
        {headerExtra}
      </div>

      <div className="p-4 space-y-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
          <Input
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setPage(0);
            }}
            placeholder="Search designation or employee…"
            className="pl-9 h-9"
          />
        </div>

        {pageGroups.length === 0 ? (
          <p className="text-sm text-muted-foreground py-10 text-center">
            No scored employees match this search.
          </p>
        ) : (
          <div className="space-y-3">
            {pageGroups.map((group) => {
              const isOpen = expanded[group.position] ?? false;
              const visible = isOpen
                ? group.people
                : group.people.slice(0, PREVIEW_COUNT);
              const maxScore = group.people[0]?.overallScore || 100;

              return (
                <motion.div
                  key={group.position}
                  layout
                  className="rounded-xl border border-border bg-muted/20 overflow-hidden"
                >
                  <div className="flex items-center justify-between gap-3 px-3 py-2.5 border-b border-border/60">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">
                        {group.position}
                      </p>
                      <p className="text-[11px] text-muted-foreground tabular-nums">
                        {group.count} {group.count === 1 ? "person" : "people"}{" "}
                        · avg {group.avgOverall.toFixed(1)}%
                      </p>
                    </div>
                    <Badge variant="outline" className="tabular-nums shrink-0">
                      Top {group.people[0]?.overallScore.toFixed(1) ?? "—"}%
                    </Badge>
                  </div>

                  <ul className="divide-y divide-border/50">
                    {visible.map((person, index) => {
                      const widthPct = Math.max(
                        4,
                        Math.round((person.overallScore / maxScore) * 100),
                      );
                      return (
                        <li
                          key={person.id}
                          className="px-3 py-2.5 flex items-center gap-3"
                        >
                          <span className="w-5 text-[11px] tabular-nums text-muted-foreground shrink-0">
                            {index + 1}
                          </span>
                          <div className="min-w-0 flex-1 space-y-1.5">
                            <div className="flex items-center justify-between gap-2">
                              <Link
                                href={`/dashboard/users/${person.id}`}
                                className="text-sm font-medium text-foreground hover:text-primary truncate"
                              >
                                {person.name}
                              </Link>
                              <span className="text-xs tabular-nums text-muted-foreground shrink-0">
                                {person.grade} ·{" "}
                                {person.overallScore.toFixed(1)}%
                              </span>
                            </div>
                            <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                              <div
                                className={cn(
                                  "h-full rounded-full transition-[width]",
                                  scoreBarColor(person.overallScore),
                                )}
                                style={{ width: `${widthPct}%` }}
                              />
                            </div>
                          </div>
                        </li>
                      );
                    })}
                  </ul>

                  {group.people.length > PREVIEW_COUNT ? (
                    <div className="px-3 py-2 border-t border-border/60">
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-8 w-full text-xs"
                        onClick={() =>
                          setExpanded((prev) => ({
                            ...prev,
                            [group.position]: !isOpen,
                          }))
                        }
                      >
                        {isOpen
                          ? "Show top 5"
                          : `Show all ${group.people.length}`}
                        <ChevronDown
                          className={cn(
                            "ml-1.5 h-3.5 w-3.5 transition-transform",
                            isOpen && "rotate-180",
                          )}
                        />
                      </Button>
                    </div>
                  ) : null}
                </motion.div>
              );
            })}
          </div>
        )}

        {groups.length > GROUPS_PER_PAGE ? (
          <div className="flex items-center justify-between gap-2 pt-1">
            <p className="text-xs text-muted-foreground tabular-nums">
              {groups.length} designations · page {safePage + 1}/{pageCount}
            </p>
            <div className="flex items-center gap-1">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8"
                disabled={safePage <= 0}
                onClick={() => setPage((p) => Math.max(0, p - 1))}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8"
                disabled={safePage >= pageCount - 1}
                onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        ) : null}
      </div>
    </section>
  );
}
