"use client";

import Link from "next/link";
import type { DeliveryRow, ModeCount } from "@/lib/attendance-report";
import {
  CardTitle,
  DeliveryChip,
  EmptyState,
  GlassCard,
  LegendDot,
  deliveryMeta,
  fa,
  faPct,
} from "./AttendancePrimitives";

/**
 * تفکیک حضوری / مجازی.
 *
 * ستون فقرات درخواست گزارش: هر جلسه یک نوع دارد (حضوری، مجازی، آفلاین،
 * ترکیبی) و ثبت حضور، ثبت‌نشده‌ها و تکمیل لیست برای هر نوع جدا دیده می‌شود.
 */
export function AttendanceDeliveryPanel({
  rows,
  sessions,
  hrefFor,
}: {
  rows: DeliveryRow[];
  sessions: { total: number; by_mode: ModeCount[] };
  hrefFor: (mode: DeliveryRow) => string;
}) {
  return (
    <GlassCard>
      <CardTitle
        kicker="نوع کلاس"
        title="حضوری در برابر مجازی"
        action={
          <span className="text-[11px] font-bold text-slate-400">
            {fa(sessions.total)} جلسه در این محدوده
          </span>
        }
      />

      {rows.length === 0 ? (
        <EmptyState>در این محدوده جلسه‌ای ثبت نشده است.</EmptyState>
      ) : (
        <>
          <SessionShareBar rows={rows} total={sessions.total} />

          <div className="mt-4 grid gap-2 sm:grid-cols-2">
            {rows.map((row) => (
              <DeliveryTile key={row.mode} row={row} href={hrefFor(row)} />
            ))}
          </div>

          <div className="mt-3 flex flex-wrap gap-3 text-[11px] text-slate-500">
            {rows.map((row) => (
              <LegendDot
                key={row.mode}
                color={deliveryMeta(row.mode).color}
                label={`${row.label} · ${fa(row.sessions)} جلسه`}
              />
            ))}
          </div>
        </>
      )}
    </GlassCard>
  );
}

function SessionShareBar({ rows, total }: { rows: DeliveryRow[]; total: number }) {
  if (total === 0) return null;
  return (
    <div className="flex h-3 overflow-hidden rounded-full bg-slate-100" dir="ltr">
      {rows.map((row) => (
        <span
          key={row.mode}
          title={`${row.label}: ${fa(row.sessions)} جلسه`}
          style={{
            width: `${(row.sessions / total) * 100}%`,
            background: deliveryMeta(row.mode).color,
          }}
        />
      ))}
    </div>
  );
}

function DeliveryTile({ row, href }: { row: DeliveryRow; href: string }) {
  const meta = deliveryMeta(row.mode);

  return (
    <Link
      href={href}
      className="block rounded-2xl border border-slate-100 bg-white/70 p-3 transition hover:border-teal-200 hover:bg-teal-50/40"
    >
      <div className="mb-2 flex items-center justify-between gap-2">
        <DeliveryChip mode={row.mode} label={row.label} />
        <span className="text-[11px] tabular-nums text-slate-500">
          {fa(row.sessions)} جلسه · {fa(row.total)} نفر-جلسه
        </span>
      </div>

      <div className="mb-2 flex items-baseline gap-2">
        <span className="text-2xl font-black tabular-nums" style={{ color: meta.color }}>
          {faPct(row.presence_rate)}
        </span>
        <span className="text-[11px] font-bold text-slate-500">نرخ حضور</span>
      </div>

      <dl className="grid grid-cols-2 gap-x-3 gap-y-1 text-[11px]">
        <Cell label="حاضر" value={fa(row.present)} tone="text-emerald-700" />
        <Cell label="تأخیر" value={fa(row.late)} tone="text-amber-700" />
        <Cell label="غایب" value={fa(row.absent)} tone="text-rose-700" />
        <Cell label="خروج موقت" value={fa(row.temporary_exit)} tone="text-violet-700" />
        <Cell
          label="ثبت‌نشده"
          value={`${fa(row.unchecked)} · ${faPct(row.unchecked_pct)}`}
          tone="text-slate-700"
        />
        <Cell
          label="لیست تکمیل"
          value={`${fa(row.lists.complete)} از ${fa(row.lists.total)}`}
          tone="text-teal-700"
        />
      </dl>

      <p className="mt-2 text-[10px] text-slate-400">
        میانگین تأخیر ارسال لیست {fa(row.lists.avg_delay_minutes)} دقیقه · به‌موقع{" "}
        {faPct(row.lists.on_time_pct)}
      </p>
    </Link>
  );
}

function Cell({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div className="flex items-center justify-between gap-1">
      <dt className="text-slate-400">{label}</dt>
      <dd className={`font-bold tabular-nums ${tone}`}>{value}</dd>
    </div>
  );
}
