import type { Metadata } from "next";
import Link from "next/link";
import { fetchOlympusRepairStatus, type OlympusRepairStatus } from "@/lib/olympus/status";

type PageProps = {
  params: Promise<{
    token: string;
  }>;
};

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Reparaturstatus | Funktechnik Schubert",
  description: "Öffentlicher Reparaturstatus für Kunden von Funktechnik Schubert.",
  robots: {
    index: false,
    follow: false,
  },
};

function formatDate(value: string) {
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(new Date(value));
}

function StatusError({ title, text }: { title: string; text: string }) {
  return (
    <section className="status-page">
      <div className="container status-page-inner">
        <div className="status-card status-card-narrow">
          <p className="eyebrow">Reparaturstatus</p>
          <h1>{title}</h1>
          <p className="lead">{text}</p>
          <div className="actions">
            <Link className="button" href="/reparatur">Reparatur anfragen</Link>
            <Link className="button light" href="/kontakt">Kontakt aufnehmen</Link>
          </div>
        </div>
      </div>
    </section>
  );
}

function StatusTimeline({ status }: { status: OlympusRepairStatus }) {
  if (status.status_history_public.length === 0) {
    return <p className="status-muted">Noch keine Statushistorie vorhanden.</p>;
  }

  const latestIndex = status.status_history_public.length - 1;

  return (
    <ol className="public-status-timeline">
      {status.status_history_public.map((item, index) => (
        <li key={`${item.status}-${item.created_at}-${index}`} className={index === latestIndex ? "is-current" : ""}>
          <span className="timeline-dot" aria-hidden="true" />
          <div className="timeline-content">
            <div>
              <p className="timeline-title">{item.status_label}</p>
              {index === latestIndex && <span className="status-pill">Aktueller Status</span>}
            </div>
            <time dateTime={item.created_at}>{formatDate(item.created_at)}</time>
          </div>
        </li>
      ))}
    </ol>
  );
}

export default async function RepairStatusPage({ params }: PageProps) {
  const { token } = await params;
  const result = await fetchOlympusRepairStatus(token);

  if (!result.ok && result.reason === "invalid") {
    return (
      <StatusError
        title="Statuslink nicht aktiv"
        text="Dieser Statuslink ist ungültig oder nicht mehr aktiv."
      />
    );
  }

  if (!result.ok) {
    return (
      <StatusError
        title="Status momentan nicht abrufbar"
        text="Der Reparaturstatus ist momentan nicht abrufbar. Bitte versuchen Sie es später erneut oder kontaktieren Sie uns direkt."
      />
    );
  }

  const status = result.status;
  const device = `${status.device_manufacturer} ${status.device_model}`.trim();

  return (
    <section className="status-page">
      <div className="container status-page-inner">
        <div className="status-card">
          <p className="eyebrow">Reparaturstatus</p>
          <div className="status-title-row">
            <div>
              <h1>Reparaturstatus</h1>
              <p className="lead">Hier sehen Sie den aktuellen Stand Ihrer Reparatur.</p>
            </div>
            <span className="status-badge">{status.public_status_label}</span>
          </div>

          <dl className="status-summary">
            <div>
              <dt>Reparaturnummer</dt>
              <dd>{status.repair_number}</dd>
            </div>
            <div>
              <dt>Gerät</dt>
              <dd>{device || "Nicht angegeben"}</dd>
            </div>
            <div>
              <dt>Aktueller Status</dt>
              <dd>{status.public_status_label}</dd>
            </div>
            <div>
              <dt>Letzte Aktualisierung</dt>
              <dd>{formatDate(status.updated_at)}</dd>
            </div>
          </dl>

          <div className="status-timeline-section">
            <h2>Statusverlauf</h2>
            <StatusTimeline status={status} />
          </div>
        </div>
      </div>
    </section>
  );
}
