import Link from "next/link";
import { ArrowRight, GitFork, Calendar, Clock, BarChart2 } from "lucide-react";
import { formatCurrency } from "@/lib/formatters/currency";
import type { OpenTripRoute, ScheduleType } from "@/types/trip";
import styles from "./RouteCard.module.css";

interface RouteCardProps {
  route: OpenTripRoute;
  mountainId: string;
  /** Filter jenis jadwal yang sedang aktif di halaman ini — diteruskan ke halaman detail tanggal. */
  scheduleType?: ScheduleType;
}

export default function RouteCard({ route, mountainId, scheduleType }: RouteCardProps) {
  // Fallback aman bila API belum mengembalikan schedule_types/schedule_type_labels, atau bahkan
  // next_trip.schedule_type (backend lama sebelum field-field ini ditambahkan) — turunkan apa yang
  // bisa didapat, lalu buang entri yang tetap undefined agar tidak merender badge kosong/tanpa key valid.
  const rawScheduleTypes =
    route.schedule_types ?? (route.next_trip ? [route.next_trip.schedule_type] : []);
  const rawScheduleTypeLabels =
    route.schedule_type_labels ?? (route.next_trip ? [route.next_trip.schedule_type_label] : []);
  const scheduleTypeBadges = rawScheduleTypes
    .map((type, idx) => ({ type, label: rawScheduleTypeLabels[idx] }))
    .filter((badge): badge is { type: ScheduleType; label: string } => Boolean(badge.type && badge.label));

  // Saat filter "Semua", backend memecah jalur dengan jadwal campuran jadi kartu terpisah per
  // jenis — kartu ini pasti punya persis 1 badge, jadi pakai jenis itu sendiri (bukan filter
  // level halaman) supaya "Lihat Tanggal" pada kartu Weekend membawa ke tanggal Weekend saja.
  const cardScheduleType = scheduleTypeBadges.length === 1 ? scheduleTypeBadges[0].type : scheduleType;
  const domIdSuffix = cardScheduleType ? `-${cardScheduleType.toLowerCase()}` : "";
  const href = cardScheduleType
    ? `/open-trip/gunung/${mountainId}/${route.id}?schedule_type=${cardScheduleType}`
    : `/open-trip/gunung/${mountainId}/${route.id}`;

  const hasPhysicalSpecs = Boolean(route.estimated_duration || route.difficulty_label);

  return (
    <article className={styles.routeCard} id={`route-card-${route.id}${domIdSuffix}`}>
      <div className={styles.iconContainer} aria-hidden="true">
        <GitFork size={22} className={styles.routeIcon} />
      </div>

      <div className={styles.routeBody}>
        <h3 className={styles.routeName}>{route.name}</h3>

        {route.description && <p className={styles.routeDesc}>{route.description}</p>}

        {/* ── 1. Jadwal & Ketersediaan Badges ──────────────────────────── */}
        <div className={styles.badgeRow}>
          <span
            className={styles.scheduleBadge}
            title={`${route.open_schedule_count} jadwal keberangkatan open trip tersedia`}
          >
            <span className={styles.statusDot} aria-hidden="true" />
            <span>{route.open_schedule_count} Jadwal Tersedia</span>
          </span>

          {scheduleTypeBadges.map(({ type, label }, idx) => (
            <span
              key={`${type}-${idx}`}
              className={`${styles.typeBadge} ${
                type === "WEEKEND" ? styles.typeWeekend : styles.typeWeekday
              }`}
              title={
                type === "WEEKEND"
                  ? "Jadwal keberangkatan akhir pekan (Weekend)"
                  : "Jadwal keberangkatan hari kerja (Weekday)"
              }
            >
              <Calendar size={12} className={styles.badgeIcon} aria-hidden="true" />
              <span>Jadwal {label}</span>
            </span>
          ))}
        </div>

        {/* ── 2. Karakteristik Fisik Jalur (Estimasi Waktu & Kesulitan) ── */}
        {hasPhysicalSpecs && (
          <div className={styles.specsBox} aria-label="Informasi fisik rute pendakian">
            {route.estimated_duration && (
              <div className={styles.specItem} title="Estimasi waktu tempuh pendakian">
                <div className={styles.specIconWrap} aria-hidden="true">
                  <Clock size={15} />
                </div>
                <div className={styles.specContent}>
                  <span className={styles.specLabel}>Estimasi Waktu</span>
                  <strong className={styles.specValue}>{route.estimated_duration}</strong>
                </div>
              </div>
            )}

            {route.estimated_duration && route.difficulty_label && (
              <div className={styles.specDivider} aria-hidden="true" />
            )}

            {route.difficulty_label && (
              <div className={styles.specItem} title="Tingkat kesulitan medan pendakian">
                <div className={styles.specIconWrap} aria-hidden="true">
                  <BarChart2 size={15} />
                </div>
                <div className={styles.specContent}>
                  <span className={styles.specLabel}>Tingkat Kesulitan</span>
                  <strong className={styles.specValue}>{route.difficulty_label}</strong>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      <div className={styles.footer}>
        {route.next_trip && (
          <div className={styles.priceContainer}>
            <span className={styles.priceLabel}>Mulai</span>
            <span className={styles.priceValue}>{formatCurrency(route.next_trip.price)}</span>
          </div>
        )}

        <Link
          href={href}
          className={styles.ctaButton}
          id={`route-card-${route.id}${domIdSuffix}-cta`}
          aria-label={`Lihat jadwal dan tanggal ${route.name}`}
        >
          <span>Lihat Tanggal</span>
          <ArrowRight size={15} className={styles.arrowIcon} aria-hidden="true" />
        </Link>
      </div>
    </article>
  );
}
