import { useState, type ReactNode } from "react";
import { Globe2 } from "lucide-react";
import { formatTrackingDate } from "../../lib/dashboard";

export function WelcomePanel({
  name,
  avatarUrl,
  date,
  timezone,
  children,
}: {
  name: string;
  avatarUrl: string | null;
  date?: string;
  timezone: string;
  children: ReactNode;
}) {
  const [failedAvatar, setFailedAvatar] = useState<string | null>(null);
  // The API date already belongs to the account's timezone. Keep its date parts
  // intact instead of interpreting them in the browser's timezone.
  const day = date ? new Date(`${date}T12:00:00Z`) : null;

  return (
    <section className="ds-welcome-panel" aria-labelledby="dashboard-title">
      <div className="ds-welcome-content">
        <div className="ds-welcome-identity">
          <div className="ds-avatar">
            {avatarUrl && failedAvatar !== avatarUrl ? (
              <img
                src={avatarUrl}
                alt={`${name}’s Discord avatar`}
                width={64}
                height={64}
                onError={() => setFailedAvatar(avatarUrl)}
              />
            ) : (
              <span aria-label={`${name}’s avatar`} role="img">
                {Array.from(name.trim())[0]?.toUpperCase() || "?"}
              </span>
            )}
          </div>
          <p className="ds-eyebrow">YOUR DAILY CHECK-IN</p>
        </div>
        <h1 id="dashboard-title" className="type-display">
          Welcome back, <em>{name}.</em>
        </h1>
        <p className="ds-welcome-subtitle">Make time for today.</p>
        {children}
      </div>
      <div className="ds-welcome-calendar">
        {day && date ? (
          <time className="ds-date-sheet" dateTime={date} aria-label={formatTrackingDate(date)}>
            <span className="ds-date-month">
              {day.toLocaleDateString("en", { month: "long", timeZone: "UTC" })}
              <span className="ds-muted">{day.getUTCFullYear()}</span>
            </span>
            <span className="ds-date-number type-display">{day.getUTCDate()}</span>
            <span className="ds-date-weekday">
              {day.toLocaleDateString("en", { weekday: "long", timeZone: "UTC" })}
            </span>
            <span className="ds-date-caption ds-eyebrow">TODAY, AT YOUR OWN PACE</span>
          </time>
        ) : (
          <p className="ds-muted" role="status">Your day is loading…</p>
        )}
        <p className="ds-welcome-timezone">
          <Globe2 size={16} aria-hidden="true" />
          <span>{timezone}</span>
        </p>
      </div>
    </section>
  );
}
