"use client";

import { useState } from "react";
import { Avatar } from "@/components/ui/Avatar";
import { Icon } from "@/components/ui/Icon";
import { ApprovalsPanel } from "@/components/personnel/ApprovalsPanel";
import type { Subordinate } from "@/lib/personnel/queries";
import type { PendingTimeDTO } from "@/lib/time/queries";
import type { AbsenceDTO } from "@/lib/absences/queries";
import type { AbsenceTypeDef } from "@/lib/settings";

const statusLabel: Record<string, string> = { ACTIVE: "Aktiv", INVITED: "Eingeladen", SUSPENDED: "Gesperrt" };

function fmtHM(sec: number): string {
  const h = Math.floor(sec / 3600);
  const m = Math.round((sec % 3600) / 60);
  return h > 0 ? `${h} Std. ${m} Min.` : `${m} Min.`;
}

/** Zeigt, ob gerade eine Zeiterfassung läuft — inklusive Startzeit. */
function ClockBadge({ since }: { since: string | null }) {
  if (!since) {
    return (
      <span className="clock-badge" data-on="false">
        <span className="clock-dot" />
        Ausgestempelt
      </span>
    );
  }
  const start = new Date(since);
  const time = start.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
  return (
    <span className="clock-badge" data-on="true" title={`Eingestempelt seit ${time} Uhr`}>
      <span className="clock-dot" />
      Eingestempelt · seit {time}
    </span>
  );
}
function fmtDate(iso: string): string {
  return new Date(iso).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" });
}

export function PersonnelManager({
  subordinates,
  pendingTime,
  pendingAbs,
  absenceTypes,
}: {
  subordinates: Subordinate[];
  pendingTime: PendingTimeDTO[];
  pendingAbs: AbsenceDTO[];
  absenceTypes: AbsenceTypeDef[];
}) {
  const [tab, setTab] = useState<"team" | "overview" | "approvals">("team");
  const [detail, setDetail] = useState<Subordinate | null>(null);

  const pendingTotal = pendingTime.length + pendingAbs.length;
  const teamMonth = subordinates.reduce((s, u) => s + u.worktimeMonth, 0);
  const teamYear = subordinates.reduce((s, u) => s + u.worktimeYear, 0);
  const vacUsed = subordinates.reduce((s, u) => s + u.vacationUsed, 0);
  const vacTotal = subordinates.reduce((s, u) => s + u.vacationTotal, 0);
  const countPending = (id: string) =>
    pendingTime.filter((p) => p.userId === id).length + pendingAbs.filter((a) => a.userId === id).length;

  return (
    <div className="flex flex-col gap-5">
      <section className="grid grid-cols-2 gap-4 xl:grid-cols-4" data-reveal>
        <div className="stat-tile"><span className="stat-tile-value">{subordinates.length}</span><span className="stat-tile-label">Mitarbeitende</span></div>
        <div className="stat-tile"><span className="stat-tile-value">{pendingTotal}</span><span className="stat-tile-label">Offene Freigaben</span></div>
        <div className="stat-tile"><span className="stat-tile-value">{fmtHM(teamMonth)}</span><span className="stat-tile-label">Team-Zeit (Monat)</span></div>
        <div className="stat-tile"><span className="stat-tile-value">{Math.max(0, vacTotal - vacUsed)}</span><span className="stat-tile-label">Resturlaub gesamt</span></div>
      </section>

      <div className="seg" data-reveal style={{ alignSelf: "flex-start" }}>
        <button className="seg-btn" data-active={tab === "team"} onClick={() => setTab("team")}>
          <Icon name="users" size={15} /> Team
        </button>
        <button className="seg-btn" data-active={tab === "overview"} onClick={() => setTab("overview")}>
          <Icon name="dashboard" size={15} /> Übersicht
        </button>
        <button className="seg-btn" data-active={tab === "approvals"} onClick={() => setTab("approvals")}>
          <Icon name="check" size={15} /> Freigaben{pendingTotal ? ` · ${pendingTotal}` : ""}
        </button>
      </div>

      {tab === "team" ? (
        subordinates.length === 0 ? (
          <div className="card" data-reveal>
            <p className="text-muted text-sm">Dir sind aktuell keine Personen direkt unterstellt.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" data-reveal>
            {subordinates.map((u) => {
              const pending = countPending(u.id);
              return (
                <button key={u.id} className="person-card" onClick={() => setDetail(u)}>
                  <div className="flex items-center gap-3">
                    <Avatar name={u.name} src={u.avatarUrl} size={44} />
                    <div className="min-w-0 flex-1">
                      <div className="truncate font-bold">{u.name}</div>
                      <div className="text-muted truncate text-xs">{u.jobTitle ?? u.email}</div>
                    </div>
                    {pending > 0 ? <span className="badge person-card-pending">{pending} offen</span> : null}
                  </div>
                  <ClockBadge since={u.clockedInSince} />
                  <div className="person-card-stats">
                    <div><span className="person-card-val">{fmtHM(u.worktimeMonth)}</span><span className="person-card-lbl">Monat</span></div>
                    <div><span className="person-card-val">{Math.max(0, u.vacationTotal - u.vacationUsed)}</span><span className="person-card-lbl">Resturlaub</span></div>
                    <div><span className="status-badge" data-status={u.status}><span className="status-badge-dot" />{statusLabel[u.status] ?? u.status}</span></div>
                  </div>
                </button>
              );
            })}
          </div>
        )
      ) : null}

      {tab === "overview" ? (
        <section className="card" data-reveal>
          <h2 className="mb-4">Team-Übersicht</h2>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <div className="overview-stat"><Icon name="time" size={18} /><div><div className="font-bold">{fmtHM(teamYear)}</div><div className="text-muted text-xs">Gesamte Arbeitszeit dieses Jahr</div></div></div>
            <div className="overview-stat"><Icon name="time" size={18} /><div><div className="font-bold">{fmtHM(teamMonth)}</div><div className="text-muted text-xs">Arbeitszeit diesen Monat</div></div></div>
            <div className="overview-stat"><Icon name="absences" size={18} /><div><div className="font-bold">{vacUsed} / {vacTotal} Tage</div><div className="text-muted text-xs">Urlaub genutzt / gesamt</div></div></div>
            <div className="overview-stat"><Icon name="check" size={18} /><div><div className="font-bold">{pendingTotal} offen</div><div className="text-muted text-xs">{pendingTime.length} Zeit · {pendingAbs.length} Abwesenheit</div></div></div>
          </div>
        </section>
      ) : null}

      {tab === "approvals" ? (
        pendingTotal === 0 ? (
          <div className="card" data-reveal><p className="text-muted text-sm">Keine offenen Freigaben.</p></div>
        ) : (
          <ApprovalsPanel pendingTime={pendingTime} pendingAbs={pendingAbs} absenceTypes={absenceTypes} />
        )
      ) : null}

      {detail ? (
        <UserDetail
          user={detail}
          pendingTime={pendingTime.filter((p) => p.userId === detail.id)}
          pendingAbs={pendingAbs.filter((a) => a.userId === detail.id)}
          absenceTypes={absenceTypes}
          onClose={() => setDetail(null)}
        />
      ) : null}
    </div>
  );
}

function UserDetail({
  user,
  pendingTime,
  pendingAbs,
  absenceTypes,
  onClose,
}: {
  user: Subordinate;
  pendingTime: PendingTimeDTO[];
  pendingAbs: AbsenceDTO[];
  absenceTypes: AbsenceTypeDef[];
  onClose: () => void;
}) {
  const typeMeta = (k: string) => absenceTypes.find((t) => t.key === k) ?? { label: k, color: "#9ed7ff" };
  return (
    <div className="drawer-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="drawer animate-in">
        <div className="mb-5 flex items-center justify-between">
          <span className="eyebrow">Mitarbeiter(in)</span>
          <button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="Schließen">
            <Icon name="close" size={16} />
          </button>
        </div>

        <div className="mb-5 flex items-center gap-3">
          <Avatar name={user.name} src={user.avatarUrl} size={56} />
          <div className="min-w-0">
            <div className="text-lg font-bold">{user.name}</div>
            <div className="text-muted text-sm">{user.jobTitle ?? "—"}</div>
            <div className="text-muted text-xs">{user.email}</div>
            <div className="mt-2">
              <ClockBadge since={user.clockedInSince} />
            </div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="detail-stat"><span className="detail-stat-val">{fmtHM(user.worktimeMonth)}</span><span className="detail-stat-lbl">Zeit diesen Monat</span></div>
          <div className="detail-stat"><span className="detail-stat-val">{fmtHM(user.worktimeYear)}</span><span className="detail-stat-lbl">Zeit dieses Jahr</span></div>
          <div className="detail-stat"><span className="detail-stat-val">{user.vacationUsed} / {user.vacationTotal}</span><span className="detail-stat-lbl">Urlaub genutzt / gesamt</span></div>
          <div className="detail-stat"><span className="detail-stat-val">{Math.max(0, user.vacationTotal - user.vacationUsed)}</span><span className="detail-stat-lbl">Resturlaub</span></div>
        </div>

        <div className="field mt-5">
          <label className="label">Geplante Abwesenheiten</label>
          {user.plannedAbsences.length === 0 ? (
            <p className="text-muted text-sm">Kein geplanter Urlaub / keine Abwesenheit.</p>
          ) : (
            <div className="flex flex-col gap-1.5">
              {user.plannedAbsences.map((a) => {
                const tm = typeMeta(a.type);
                return (
                  <div key={a.id} className="approve-row">
                    <span className="absence-type" style={{ background: `${tm.color}22`, color: tm.color, borderColor: `${tm.color}55` }}>{tm.label}</span>
                    <span className="min-w-0 flex-1 truncate text-sm">
                      {fmtDate(a.startDate)}{a.startDate !== a.endDate ? ` – ${fmtDate(a.endDate)}` : ""}
                    </span>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div className="field mt-4">
          <label className="label">Rollen</label>
          <div className="flex flex-wrap gap-1.5">
            {user.roleNames.length ? user.roleNames.map((r, i) => <span key={i} className="badge">{r}</span>) : <span className="text-muted text-sm">—</span>}
          </div>
        </div>

        <div className="field mt-4">
          <label className="label">Offene Freigaben</label>
          {pendingTime.length + pendingAbs.length === 0 ? (
            <p className="text-muted text-sm">Keine offenen Anträge.</p>
          ) : (
            <div className="flex flex-col gap-1.5">
              {pendingTime.map((p) => (
                <div key={p.id} className="approve-row">
                  <Icon name="time" size={15} />
                  <span className="min-w-0 flex-1 truncate text-sm">{fmtDate(p.startedAt)} · {fmtHM(p.durationSeconds)}{p.note ? ` · ${p.note}` : ""}</span>
                  <span className="status-badge" data-status="INVITED"><span className="status-badge-dot" /> Zeit</span>
                </div>
              ))}
              {pendingAbs.map((a) => {
                const tm = typeMeta(a.type);
                return (
                  <div key={a.id} className="approve-row">
                    <span className="absence-type" style={{ background: `${tm.color}22`, color: tm.color, borderColor: `${tm.color}55` }}>{tm.label}</span>
                    <span className="min-w-0 flex-1 truncate text-sm">{fmtDate(a.startDate)}{a.startDate !== a.endDate ? ` – ${fmtDate(a.endDate)}` : ""}</span>
                  </div>
                );
              })}
              <p className="text-muted mt-1 text-xs">Freigabe im Tab „Freigaben".</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
