'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Printer, AlertCircle } from 'lucide-react';
import { useTranslations, useFormatter } from 'next-intl';
import { trpc } from '@/lib/trpc/client';
import { SHIFTS, shiftWindow, todayWindow, type ShiftKey } from '@/lib/shifts';

// ── Duration helper ─────────────────────────────────────────────────────────

type TFn = ReturnType<typeof useTranslations<'report'>>;

function formatDuration(ms: number | null, t: TFn): string {
  if (ms === null) return t('duration.dash');
  const totalMin = Math.round(ms / 60_000);
  if (totalMin < 1) return t('duration.lessThan1Min');
  if (totalMin < 60) return t('duration.minutes', { n: totalMin });
  const h = Math.floor(totalMin / 60);
  const m = totalMin % 60;
  return m > 0 ? t('duration.hoursMinutes', { h, m }) : t('duration.hours', { h });
}

// ── Status ───────────────────────────────────────────────────────────────────

const STATUS_CLASS: Record<'OPEN' | 'CLAIMED', string> = {
  OPEN: 'bg-orange-100 text-orange-700',
  CLAIMED: 'bg-blue-100 text-blue-700',
};

// ── Metric card ──────────────────────────────────────────────────────────────

function MetricCard({ label, value, sub }: { label: string; value: string; sub?: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 print:border-gray-300">
      <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground print:text-gray-500">
        {label}
      </p>
      <p className="mt-1 text-2xl font-bold">{value}</p>
      {sub && <p className="mt-0.5 text-xs text-muted-foreground print:text-gray-500">{sub}</p>}
    </div>
  );
}

// ── Main component ───────────────────────────────────────────────────────────

type WindowState =
  | { type: 'shift'; key: ShiftKey; day: Date }
  | { type: 'today' }
  | { type: 'custom'; from: Date; to: Date };

function computeWindow(state: WindowState): { from: Date; to: Date } {
  const now = new Date();
  if (state.type === 'today') return todayWindow(now);
  if (state.type === 'shift') return shiftWindow(state.key, state.day);
  return { from: state.from, to: state.to };
}

function localDateStr(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function localDateTimeStr(d: Date): string {
  return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

const DATE_TIME_FMT = { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' } as const;
const DATE_FMT = { day: '2-digit', month: '2-digit' } as const;

export function ReportView() {
  const t = useTranslations('report');
  const tc = useTranslations('common');
  const format = useFormatter();

  const [windowState, setWindowState] = useState<WindowState>({ type: 'today' });
  const [dayInput, setDayInput] = useState(() => localDateStr(new Date()));
  const [customActive, setCustomActive] = useState(false);
  const [customPending, setCustomPending] = useState(() => {
    const now = new Date();
    const midnight = new Date(now);
    midnight.setHours(0, 0, 0, 0);
    return { from: localDateTimeStr(midnight), to: localDateTimeStr(now) };
  });

  // Stabilise the window so the query key only changes when the user picks a
  // new window. Without this, the 'today' mode recomputes `to = new Date()` on
  // every render → new query key → fetch loop. Re-selecting "Today" refreshes.
  const win = useMemo(() => computeWindow(windowState), [windowState]);

  const { data, isLoading, error } = trpc.maintenanceRequest.report.useQuery(
    { from: win.from, to: win.to },
    { staleTime: 30_000 },
  );

  function selectShift(key: ShiftKey) {
    const day = new Date(dayInput + 'T00:00:00');
    setCustomActive(false);
    setWindowState({ type: 'shift', key, day });
  }

  function selectToday() {
    setCustomActive(false);
    setWindowState({ type: 'today' });
  }

  function applyCustom() {
    const from = new Date(customPending.from);
    const to = new Date(customPending.to);
    if (isNaN(from.getTime()) || isNaN(to.getTime()) || to <= from) return;
    setWindowState({ type: 'custom', from, to });
  }

  const activeShift = windowState.type === 'shift' ? windowState.key : null;

  const range = `${format.dateTime(win.from, DATE_TIME_FMT)} → ${format.dateTime(win.to, DATE_TIME_FMT)}`;

  const windowLabelText =
    windowState.type === 'today'
      ? t('windowLabel.today', { range })
      : windowState.type === 'shift'
      ? t(`windowLabel.${windowState.key}`, { range })
      : t('windowLabel.custom', { range });

  return (
    <div className="min-h-screen bg-background print:bg-white">
      {/* ── Header (hidden in print) ── */}
      <header className="sticky top-0 z-10 border-b border-border bg-card px-4 py-3 print:hidden">
        <div className="mx-auto flex max-w-4xl items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <Link
              href="/maintenance"
              className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
            >
              <ArrowLeft className="h-4 w-4" />
              {t('backToQueue')}
            </Link>
            <span className="text-muted-foreground">/</span>
            <h1 className="text-lg font-bold">{t('title')}</h1>
          </div>
          <button
            onClick={() => window.print()}
            className="flex items-center gap-1.5 rounded-lg bg-muted px-3 py-1.5 text-sm font-medium hover:bg-accent"
          >
            <Printer className="h-4 w-4" />
            {t('print')}
          </button>
        </div>
      </header>

      {/* ── Print header (only in print) ── */}
      <div className="hidden print:block px-8 pt-6 pb-2">
        <p className="text-lg font-bold">{t('printHeader')}</p>
        <p className="text-sm text-gray-600">{range}</p>
      </div>

      {/* ── Window selector (hidden in print) ── */}
      <div className="border-b border-border bg-muted/30 px-4 py-3 print:hidden">
        <div className="mx-auto max-w-4xl space-y-3">
          {/* Shift shortcuts + day picker */}
          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={selectToday}
              className={`rounded-full px-3 py-1 text-sm font-medium transition-colors ${
                windowState.type === 'today'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-card border border-border hover:bg-accent'
              }`}
            >
              {t('today')}
            </button>
            {(Object.keys(SHIFTS) as ShiftKey[]).map((key) => (
              <button
                key={key}
                onClick={() => selectShift(key)}
                className={`rounded-full px-3 py-1 text-sm font-medium transition-colors ${
                  activeShift === key
                    ? 'bg-primary text-primary-foreground'
                    : 'bg-card border border-border hover:bg-accent'
                }`}
              >
                {t(`shiftButton.${key}`)}
              </button>
            ))}

            <input
              type="date"
              value={dayInput}
              onChange={(e) => {
                setDayInput(e.target.value);
                if (windowState.type === 'shift') {
                  const day = new Date(e.target.value + 'T00:00:00');
                  setWindowState({ type: 'shift', key: windowState.key, day });
                }
              }}
              className="rounded-lg border border-border bg-card px-2 py-1 text-sm"
            />

            <button
              onClick={() => setCustomActive((v) => !v)}
              className={`rounded-full px-3 py-1 text-sm font-medium transition-colors ${
                customActive || windowState.type === 'custom'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-card border border-border hover:bg-accent'
              }`}
            >
              {t('custom')}
            </button>
          </div>

          {/* Custom range inputs */}
          {customActive && (
            <div className="flex flex-wrap items-center gap-2">
              <input
                type="datetime-local"
                value={customPending.from}
                onChange={(e) => setCustomPending((p) => ({ ...p, from: e.target.value }))}
                className="rounded-lg border border-border bg-card px-2 py-1 text-sm"
              />
              <span className="text-sm text-muted-foreground">{t('customUntil')}</span>
              <input
                type="datetime-local"
                value={customPending.to}
                onChange={(e) => setCustomPending((p) => ({ ...p, to: e.target.value }))}
                className="rounded-lg border border-border bg-card px-2 py-1 text-sm"
              />
              <button
                onClick={applyCustom}
                className="rounded-lg bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90"
              >
                {t('customApply')}
              </button>
            </div>
          )}

          {/* Active window label */}
          <p className="text-xs text-muted-foreground">{windowLabelText}</p>
        </div>
      </div>

      {/* ── Body ── */}
      <main className="mx-auto max-w-4xl px-4 py-6 print:px-8 print:py-4">
        {isLoading && (
          <p className="py-16 text-center text-muted-foreground">{tc('loading')}</p>
        )}

        {error && (
          <div className="flex items-center gap-2 rounded-xl border border-destructive/30 bg-destructive/10 p-4 text-destructive">
            <AlertCircle className="h-5 w-5 shrink-0" />
            <p className="text-sm">{error.message}</p>
          </div>
        )}

        {data && data.totals.created === 0 && (
          <div className="py-16 text-center text-muted-foreground">
            <p className="text-lg">{t('emptyWindow')}</p>
          </div>
        )}

        {data && data.totals.created > 0 && (
          <div className="space-y-8 print:space-y-6">
            {/* Summary cards */}
            <section>
              <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
                {t('sections.summary')}
              </h2>
              <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 print:grid-cols-3">
                <MetricCard label={t('metrics.created')} value={String(data.totals.created)} />
                <MetricCard label={t('metrics.resolved')} value={String(data.totals.resolved)} />
                <MetricCard
                  label={t('metrics.open')}
                  value={String(data.totals.open + data.totals.claimed)}
                  sub={
                    data.totals.open > 0 || data.totals.claimed > 0
                      ? t('metrics.openSub', { open: data.totals.open, claimed: data.totals.claimed })
                      : undefined
                  }
                />
                <MetricCard
                  label={t('metrics.responseAvg')}
                  value={formatDuration(data.responseMs.avg, t)}
                  sub={
                    data.responseMs.count > 0
                      ? t('metrics.requestsSub', { count: data.responseMs.count })
                      : t('metrics.noData')
                  }
                />
                <MetricCard
                  label={t('metrics.resolutionAvg')}
                  value={formatDuration(data.resolutionMs.avg, t)}
                  sub={
                    data.resolutionMs.count > 0
                      ? t('metrics.requestsSub', { count: data.resolutionMs.count })
                      : t('metrics.noData')
                  }
                />
                <MetricCard
                  label={t('metrics.responseMax')}
                  value={formatDuration(data.responseMs.max, t)}
                />
              </div>
            </section>

            {/* By workstation */}
            {data.byWorkstation.length > 0 && (
              <section>
                <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
                  {t('sections.byWorkstation')}
                </h2>
                <div className="overflow-hidden rounded-xl border border-border print:border-gray-300">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-border bg-muted/50 text-left print:bg-gray-50 print:border-gray-300">
                        <th className="px-4 py-2 font-medium">{t('table.code')}</th>
                        <th className="px-4 py-2 font-medium">{t('table.name')}</th>
                        <th className="px-4 py-2 font-medium">{t('table.area')}</th>
                        <th className="px-4 py-2 text-right font-medium">{t('table.requests')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.byWorkstation.map((ws, i) => (
                        <tr
                          key={ws.workstationId}
                          className={`border-b border-border last:border-0 print:border-gray-200 ${
                            i % 2 === 0 ? '' : 'bg-muted/20'
                          }`}
                        >
                          <td className="px-4 py-2 font-mono text-xs">{ws.code}</td>
                          <td className="px-4 py-2">{ws.name}</td>
                          <td className="px-4 py-2 text-muted-foreground print:text-gray-500">
                            {ws.area}
                          </td>
                          <td className="px-4 py-2 text-right font-medium">{ws.count}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </section>
            )}

            {/* By area */}
            {data.byArea.length > 1 && (
              <section>
                <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
                  {t('sections.byArea')}
                </h2>
                <div className="flex flex-wrap gap-3">
                  {data.byArea.map((a) => (
                    <div
                      key={a.area}
                      className="rounded-lg border border-border bg-card px-4 py-2 print:border-gray-300"
                    >
                      <span className="font-medium">{a.area}</span>
                      <span className="ml-2 text-muted-foreground print:text-gray-500">
                        {a.count}
                      </span>
                    </div>
                  ))}
                </div>
              </section>
            )}

            {/* Still open */}
            <section>
              <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground print:text-gray-500">
                {t('sections.stillOpen')}
              </h2>
              {data.stillOpen.length === 0 ? (
                <p className="text-sm text-green-600">{t('allClear')}</p>
              ) : (
                <div className="space-y-2">
                  {data.stillOpen.map((r) => (
                    <div
                      key={r.id}
                      className="flex flex-col gap-1 rounded-xl border border-border bg-card px-4 py-3 print:border-gray-300 sm:flex-row sm:items-center sm:gap-4"
                    >
                      <div className="min-w-0 flex-1">
                        <p className="font-medium">
                          {r.code} — {r.name}{' '}
                          <span className="text-xs text-muted-foreground print:text-gray-500">
                            · {r.area}
                          </span>
                        </p>
                        <p className="mt-0.5 line-clamp-1 text-sm text-muted-foreground print:text-gray-500">
                          {r.description}
                        </p>
                        <p className="mt-0.5 text-xs text-muted-foreground print:text-gray-500">
                          {t('stillOpenReportedBy', {
                            email: r.reportedByEmail,
                            date: format.dateTime(new Date(r.createdAt), DATE_FMT),
                          })}
                        </p>
                      </div>
                      <span
                        className={`shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium print:border print:bg-transparent ${STATUS_CLASS[r.status]}`}
                      >
                        {tc(`status.${r.status.toLowerCase() as 'open' | 'claimed'}`)}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </section>
          </div>
        )}
      </main>
    </div>
  );
}
