'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Video, X, Clock, Timer, UserCircle2 } from 'lucide-react';
import { StatusPill } from '@sehat/ui';
import {
  APPOINTMENT_STATUS_LABEL,
  type Appointment,
  type AppointmentStatus,
} from '@/lib/api-types';
import { formatElapsed, formatInTimezone, formatScheduledAt } from '@/lib/date-utils';

/** Same call URL fallback used by the lobby. */
const CALL_BASE_URL =
  process.env.NEXT_PUBLIC_CALL_BASE_URL ?? '/call';

const STATUS_TONE: Record<
  AppointmentStatus,
  React.ComponentProps<typeof StatusPill>['tone']
> = {
  pending: 'warning',
  allocated: 'info',
  confirmed: 'info',
  in_progress: 'brand',
  completed: 'success',
  cancelled: 'neutral',
  no_show: 'danger',
};

interface StickyHeaderProps {
  appointment: Appointment;
  /** Display name override (uses EMR demographics when available). */
  patientName?: string | null;
  /** Optional age string like "34 yr". */
  patientAge?: string | null;
  /** Optional gender string like "female". */
  patientGender?: string | null;
  /** Called when doctor confirms end of consultation. */
  onEndConsult?: () => void;
}

/**
 * Sticky title strip that hugs the top of the viewport while the doctor
 * scrolls through the EMR / SOAP / prescription panels. Surfaces:
 *  • patient identity + age/gender chip
 *  • status pill (pulses when in-progress)
 *  • scheduled time + elapsed-minutes timer when call is live
 *  • Join call + End consultation CTAs
 */
export function StickyHeader({
  appointment,
  patientName,
  patientAge,
  patientGender,
  onEndConsult,
}: StickyHeaderProps) {
  const dt = formatScheduledAt(appointment.scheduledAt);
  const doctorTz = appointment.doctorTimezone ?? null;
  const patientTz = appointment.timezone;
  const showDualTz =
    !!doctorTz && doctorTz !== patientTz;
  const doctorView = doctorTz
    ? formatInTimezone(appointment.scheduledAt, doctorTz)
    : null;
  const patientView = formatInTimezone(appointment.scheduledAt, patientTz);
  const isLive = appointment.status === 'in_progress';
  const isJoinable =
    appointment.status === 'confirmed' ||
    appointment.status === 'allocated' ||
    appointment.status === 'pending' ||
    appointment.status === 'in_progress';

  // Live elapsed timer — counts seconds since `scheduledAt` while the call is
  // in progress. We keep it client-side only; the wall-clock authority lives
  // on the backend appointment record.
  const [elapsed, setElapsed] = useState<number>(0);
  useEffect(() => {
    if (!isLive) return;
    const start = new Date(appointment.scheduledAt).getTime();
    const tick = () => setElapsed(Math.floor((Date.now() - start) / 1000));
    tick();
    const id = window.setInterval(tick, 1000);
    return () => window.clearInterval(id);
  }, [isLive, appointment.scheduledAt]);

  const displayName =
    patientName ||
    appointment.patientName ||
    `Patient ${appointment.patientId.slice(0, 8)}`;

  // Join-call handler — records the doctor as joined on the backend before
  // sending them to the call UI. Mirrors the lobby's Start button so both
  // entry points trigger the same call-start flow.
  const [joining, setJoining] = useState<boolean>(false);
  const handleJoinClick = useCallback(
    async (e: React.MouseEvent<HTMLAnchorElement>) => {
      e.preventDefault();
      if (joining) return;
      setJoining(true);
      try {
        await fetch(`/api/appointments/${appointment.id}/call/start`, {
          method: 'POST',
        }).catch(() => null);
      } finally {
        window.location.href = `${CALL_BASE_URL}/${appointment.id}`;
      }
    },
    [appointment.id, joining],
  );

  return (
    <div className="sticky top-0 z-30 -mx-6 border-b border-denseSurface-border bg-white/85 px-6 py-3 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-white/70">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex min-w-0 items-center gap-3">
          <Link
            href="/appointments"
            className="inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-md border border-denseSurface-border text-ink-2 transition-colors hover:bg-denseSurface-bg hover:text-ink-1"
            aria-label="Back to appointments"
          >
            <ArrowLeft className="h-4 w-4" />
          </Link>
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="truncate font-display text-lg font-bold text-ink-1">
                {displayName}
              </h1>
              {patientAge || patientGender ? (
                <span className="rounded border border-denseSurface-border bg-denseSurface-bg px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-ink-2">
                  {[patientAge, patientGender].filter(Boolean).join(' · ')}
                </span>
              ) : null}
              <StatusPill tone={STATUS_TONE[appointment.status]} dot={isLive}>
                {APPOINTMENT_STATUS_LABEL[appointment.status]}
              </StatusPill>
              {appointment.noShowBy === 'doctor' ? (
                <StatusPill tone="danger">
                  Patient reported you didn&apos;t join
                </StatusPill>
              ) : null}
              {appointment.rescheduleRequestedAt ? (
                <StatusPill tone="warning">Reschedule requested</StatusPill>
              ) : null}
            </div>
            <p className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-ink-2">
              {showDualTz && doctorView ? (
                <>
                  <span
                    className="inline-flex items-center gap-1"
                    title="Your local time"
                  >
                    <Clock className="h-3 w-3 text-ink-3" />
                    <span className="font-semibold text-ink-1">You:</span>{' '}
                    {doctorView.date} · {doctorView.time}{' '}
                    <span className="text-ink-3">
                      ({doctorView.tz || doctorTz})
                    </span>
                  </span>
                  <span
                    className="inline-flex items-center gap-1"
                    title="Patient's local time"
                  >
                    <span className="font-semibold text-ink-1">Patient:</span>{' '}
                    {patientView.date} · {patientView.time}{' '}
                    <span className="text-ink-3">
                      ({patientView.tz || patientTz})
                    </span>
                  </span>
                </>
              ) : (
                <span className="inline-flex items-center gap-1">
                  <Clock className="h-3 w-3 text-ink-3" />
                  {dt.date} · {dt.time}{' '}
                  <span className="text-ink-3">({patientTz})</span>
                </span>
              )}
              <span className="text-ink-3">{appointment.specialtyName}</span>
              {appointment.displayNumber ? (
                <span
                  className="inline-flex items-center gap-1 rounded bg-denseSurface-bg px-1.5 py-0.5 font-mono text-[11px] font-semibold text-ink-2"
                  title="Readable appointment number"
                >
                  {appointment.displayNumber}
                </span>
              ) : null}
              {isLive ? (
                <span className="inline-flex items-center gap-1 rounded bg-brand-50 px-1.5 py-0.5 font-mono text-[11px] font-semibold text-brand-700">
                  <Timer className="h-3 w-3" />
                  {formatElapsed(elapsed)}
                </span>
              ) : null}
            </p>
          </div>
        </div>

        <div className="flex flex-shrink-0 items-center gap-2">
          <Link
            href={`/patients/${appointment.patientId}`}
            className="inline-flex items-center gap-1.5 rounded-md border border-denseSurface-border bg-white px-3 py-1.5 text-sm font-semibold text-ink-1 hover:bg-denseSurface-bg"
          >
            <UserCircle2 className="h-4 w-4" />
            View patient profile
          </Link>
          {isJoinable ? (
            <a
              href={`${CALL_BASE_URL}/${appointment.id}`}
              onClick={handleJoinClick}
              aria-busy={joining}
              className="inline-flex items-center gap-1.5 rounded-md bg-brand-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-brand-600 aria-busy:opacity-70"
            >
              <Video className="h-4 w-4" />
              {joining ? 'Joining…' : isLive ? 'Rejoin call' : 'Join call'}
            </a>
          ) : null}
          {isLive ? (
            <button
              type="button"
              onClick={onEndConsult}
              className="inline-flex items-center gap-1.5 rounded-md border border-danger-500/40 bg-danger-500/5 px-3 py-1.5 text-sm font-semibold text-danger-500 transition-colors hover:bg-danger-500/10"
            >
              <X className="h-4 w-4" /> End consultation
            </button>
          ) : null}
        </div>
      </div>
    </div>
  );
}
