"use client";

import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import {
  CheckCircleIcon,
  ExclamationTriangleFillIcon,
  RefreshIcon,
} from "@enode/ui/icons";
import { RowDivider } from "@enode/ui/list-rows";
import { RailPopover } from "./rail-popover";
import {
  syncLine,
  syncTone,
  type SyncLineInput,
  type SyncTone,
} from "./tablet-rail-model";
import {
  FeedbackStationsRow,
  TrainingStationsRow,
  type FeedbackStationsRowProps,
  type TrainingStationsRowProps,
} from "./training-stations-row";

/** Props of {@link StationsPopover}. */
export interface StationsPopoverProps {
  /** The rail item it opened from; null = closed. */
  anchor: HTMLElement | null;
  onClose: () => void;
  /** The "Training stations − n +" row; null (athletes, unknown role) shows a read-only line. */
  stations: TrainingStationsRowProps | null;
  /** The "Feedback stations − n +" row; null (athletes, unknown role) hides it. */
  feedbackStations: FeedbackStationsRowProps | null;
  /**
   * Open stations beyond the screen (training stations or columns in use that
   * the rail scrolls to); 0 hides the line. See `offScreenColumns`.
   */
  offScreen?: number;
  /** The schedule status with Sync now, for everyone. */
  schedule: ScheduleStatusRowProps;
}

/**
 * The rail's "Stations" menu: the Training stations stepper (the stations
 * that save, filled from the left), the Feedback stations stepper (the
 * stations next to them that only give live feedback — Today shows training
 * plus feedback stations side by side) and, under a divider, the schedule
 * status with Sync now ("Load workouts" in the old app).
 * An athlete sees a read-only line instead of the steppers. The schedule row
 * is an action, not a setting: every setting — device ones included — lives
 * in Settings (Account › Settings › This device), so this menu has no
 * Settings link: one place for settings.
 */
export function StationsPopover({
  anchor,
  onClose,
  stations,
  feedbackStations,
  offScreen = 0,
  schedule,
}: StationsPopoverProps) {
  const { t } = useTranslation();
  return (
    <RailPopover anchor={anchor} onClose={onClose} ariaLabel={t("Stations")}>
      {stations ? (
        <>
          <TrainingStationsRow {...stations} withIcon />
          {feedbackStations && <FeedbackStationsRow {...feedbackStations} />}
          {offScreen > 0 && (
            <p className="body-small px-4 pb-3 text-foreground-more-muted">
              {t(
                "{count, plural, one {# station is off screen. Swipe the stations sideways to reach it.} other {# stations are off screen. Swipe the stations sideways to reach them.}}",
                { count: offScreen },
              )}
            </p>
          )}
        </>
      ) : (
        <p className="body-normal px-4 py-3 text-foreground-muted">
          {t("Trainings on this device are saved to your history.")}
        </p>
      )}
      <RowDivider />
      <ScheduleStatusRow {...schedule} />
    </RailPopover>
  );
}

/** Props of {@link ScheduleStatusRow}. */
export interface ScheduleStatusRowProps {
  sync: SyncLineInput;
  /** Loads the schedule, renews the offline copy and sends what waits to upload. */
  onSync: () => void;
}

/**
 * The schedule status: a status icon, "Schedule up to date" with when it was
 * checked and what waits to upload, and a "Sync now" button. Sync now loads
 * the schedule, renews the offline copy and sends what waits to upload — one
 * button, since the coach cannot judge which direction is due, and both also
 * run by themselves. In the rail's Stations menu
 * (iPad) and on Settings → This device (every device; the phone's only place
 * for it).
 */
export function ScheduleStatusRow({ sync, onSync }: ScheduleStatusRowProps) {
  const { t, locale } = useTranslation();
  const line = syncLine(sync, t, locale);
  return (
    // Keyed off the row's own width: in the 320 px rail menu the button spans
    // the row under the status (edge to edge with the icons and the stepper
    // buttons above); in a wider Settings card it sits beside it, like a
    // stepper.
    <div className="@container px-4 py-3">
      <div className="flex flex-col gap-3 @sm:flex-row @sm:items-center">
        <div className="flex min-w-0 flex-1 items-start gap-3">
          <SyncToneIcon tone={syncTone(sync)} />
          <div className="min-w-0 flex-1">
            <p className="body-prominent text-foreground-default">{line.title}</p>
            <p className="body-small mt-0.5 text-foreground-more-muted">
              {line.detail}
            </p>
          </div>
        </div>
        <Button
          variant="neutral"
          size="rounded"
          onClick={onSync}
          busy={sync.loading || sync.syncing}
          leadingIcon={<RefreshIcon className="size-4" />}
          className="w-full shrink-0 whitespace-nowrap @sm:w-auto"
        >
          {t("Sync now")}
        </Button>
      </div>
    </div>
  );
}

/** The status mark in front of the schedule status; the title says it in words. */
function SyncToneIcon({ tone }: { tone: SyncTone }) {
  switch (tone) {
    case "checking":
      return (
        <span aria-hidden="true" className="flex size-5 shrink-0 items-center justify-center">
          <span className="size-4 animate-spin rounded-full border-2 border-surface-stroke border-t-foreground-default" />
        </span>
      );
    case "attention":
      return <ExclamationTriangleFillIcon className="size-5 shrink-0 text-feedback-warning" />;
    case "ok":
      return <CheckCircleIcon className="size-5 shrink-0 text-feedback-success" />;
  }
}
