'use client';

/**
 * AppointmentJourney — visual 5-step lifecycle stepper.
 *
 *   1. Pending      — request submitted, doctor not yet allocated
 *   2. Confirmed    — slot locked, doctor allocated
 *   3. In progress  — call session active
 *   4. Completed    — call ended, notes/Rx in post-call window (editable)
 *   5. Finalized    — doctor signed; locked to all but admin
 *
 * Two variants:
 *   `full`     — horizontal stepper with circles + labels, for detail pages.
 *   `compact`  — single pill showing current step + tiny dots, for list rows
 *                and call headers where vertical space is tight.
 *
 * Two themes via `tone`:
 *   `light` (default) — for the doctor + admin portals' white pages.
 *   `dark`            — for the patient portal's gradient hero. Kept for
 *                       symmetry; the patient copy lives in its own portal.
 */

import { Check, Clock, PhoneCall, ClipboardCheck, ShieldCheck } from 'lucide-react';

export type AppointmentJourneyStep =
  | 'pending'
  | 'confirmed'
  | 'in_progress'
  | 'completed'
  | 'finalized';

const STEPS: Array<{
  key: AppointmentJourneyStep;
  label: string;
  icon: typeof Clock;
}> = [
  { key: 'pending', label: 'Pending', icon: Clock },
  { key: 'confirmed', label: 'Confirmed', icon: Check },
  { key: 'in_progress', label: 'In progress', icon: PhoneCall },
  { key: 'completed', label: 'Completed', icon: ClipboardCheck },
  { key: 'finalized', label: 'Finalized', icon: ShieldCheck },
];

/**
 * Resolve the current journey step from raw appointment fields. Same logic
 * is used on every portal so the steppers stay in lockstep.
 */
export function resolveJourneyStep(opts: {
  status: string;
  noteSignedAt?: string | null;
}): AppointmentJourneyStep {
  if (opts.noteSignedAt) return 'finalized';
  if (opts.status === 'completed') return 'completed';
  if (opts.status === 'in_progress') return 'in_progress';
  if (opts.status === 'cancelled' || opts.status === 'pending') return 'pending';
  return 'confirmed';
}

interface Palette {
  container: string;
  connectorDone: string;
  connectorTodo: string;
  doneCircle: string;
  doneLabel: string;
  activeCircle: string;
  activeLabel: string;
  todoCircle: string;
  todoLabel: string;
  // Compact pill variant
  compactWrap: string;
  compactDotOn: string;
  compactDotOff: string;
}

const PALETTES: Record<'light' | 'dark', Palette> = {
  light: {
    container:
      'border-denseSurface-border bg-white text-ink-1 shadow-sm',
    connectorDone: 'bg-emerald-500',
    connectorTodo: 'bg-denseSurface-border',
    doneCircle: 'bg-emerald-500 text-white ring-emerald-500',
    doneLabel: 'text-emerald-700',
    activeCircle: 'bg-brand-500 text-white ring-brand-500',
    activeLabel: 'text-brand-700',
    todoCircle: 'bg-denseSurface-bg text-ink-3 ring-denseSurface-border',
    todoLabel: 'text-ink-3',
    compactWrap:
      'border-denseSurface-border bg-white text-ink-2 shadow-sm',
    compactDotOn: 'bg-brand-500',
    compactDotOff: 'bg-denseSurface-border',
  },
  dark: {
    container: 'border-white/15 bg-white/5 text-white',
    connectorDone: 'bg-emerald-400',
    connectorTodo: 'bg-white/15',
    doneCircle: 'bg-emerald-500 text-white ring-emerald-500',
    doneLabel: 'text-emerald-200',
    activeCircle: 'bg-brand text-white ring-brand',
    activeLabel: 'text-white',
    todoCircle: 'bg-white/10 text-white/60 ring-white/20',
    todoLabel: 'text-white/50',
    compactWrap: 'border-white/20 bg-white/10 text-white/90 backdrop-blur',
    compactDotOn: 'bg-white',
    compactDotOff: 'bg-white/30',
  },
};

export function AppointmentJourney({
  current,
  variant = 'full',
  tone = 'light',
  className,
}: {
  current: AppointmentJourneyStep;
  variant?: 'full' | 'compact';
  tone?: 'light' | 'dark';
  className?: string;
}) {
  const currentIdx = STEPS.findIndex((s) => s.key === current);
  const p = PALETTES[tone];

  if (variant === 'compact') {
    const active = STEPS[currentIdx] ?? STEPS[0]!;
    const Icon = active.icon;
    return (
      <div
        className={`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-medium ${p.compactWrap} ${className ?? ''}`}
      >
        <Icon className="h-3.5 w-3.5" />
        <span>{active.label}</span>
        <span className="ml-1 flex items-center gap-0.5">
          {STEPS.map((_, i) => (
            <span
              key={i}
              className={`h-1.5 w-1.5 rounded-full ${
                i <= currentIdx ? p.compactDotOn : p.compactDotOff
              }`}
            />
          ))}
        </span>
      </div>
    );
  }

  return (
    <ol
      className={`flex w-full items-center justify-between gap-1 rounded-2xl border p-3 ${p.container} ${className ?? ''}`}
      aria-label="Appointment progress"
    >
      {STEPS.map((step, i) => {
        const Icon = step.icon;
        const isDone = i < currentIdx;
        const isActive = i === currentIdx;
        return (
          <li key={step.key} className="flex flex-1 items-center">
            <div className="flex flex-col items-center">
              <div
                className={`flex h-8 w-8 items-center justify-center rounded-full ring-2 transition ${
                  isActive ? p.activeCircle : isDone ? p.doneCircle : p.todoCircle
                }`}
                aria-current={isActive ? 'step' : undefined}
              >
                {isDone ? <Check className="h-4 w-4" /> : <Icon className="h-4 w-4" />}
              </div>
              <p
                className={`mt-1.5 text-center text-[11px] font-semibold ${
                  isActive ? p.activeLabel : isDone ? p.doneLabel : p.todoLabel
                }`}
              >
                {step.label}
              </p>
            </div>
            {i < STEPS.length - 1 ? (
              <div
                className={`mx-1 h-0.5 flex-1 ${
                  i < currentIdx ? p.connectorDone : p.connectorTodo
                }`}
                aria-hidden
              />
            ) : null}
          </li>
        );
      })}
    </ol>
  );
}
