"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { CalendarClock } from "lucide-react";
import { TopBar } from "@/components/ui/TopBar";
import { NetworkBadge } from "@/components/NetworkBadge";
import { Button } from "@/components/ui/Button";
import { GlassCard } from "@/components/ui/GlassCard";
import { Skeleton } from "@/components/ui/Skeleton";
import { getNetwork } from "@/lib/mock-data";
import { getPackageSpecs } from "@/lib/package-specs";
import { fetchPackageBySlug } from "@/lib/data/packages";
import { Package } from "@/lib/types";
import { cn } from "@/lib/cn";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

export default function PackageDetailsPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const { t } = useTranslation();
  const [pkg, setPkg] = useState<Package | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    let active = true;
    setLoading(true);
    setNotFound(false);

    fetchPackageBySlug(params.id)
      .then((result) => {
        if (!active) return;
        if (result) setPkg(result);
        else setNotFound(true);
      })
      .catch(() => active && setNotFound(true))
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, [params.id]);

  if (loading) {
    return (
      <div className="flex flex-1 flex-col">
        <TopBar title={t("packages.title")} />
        <div className="flex flex-1 flex-col gap-6 px-4 pb-32 pt-4">
          <div className="flex flex-col items-center gap-3">
            <Skeleton className="h-20 w-44 !rounded-3xl" />
            <Skeleton className="h-6 w-40" />
            <Skeleton className="h-4 w-28" />
          </div>
          <Skeleton className="h-20 w-full !rounded-4xl" />
          <Skeleton className="h-48 w-full !rounded-4xl" />
        </div>
      </div>
    );
  }

  if (notFound || !pkg) {
    return (
      <div className="flex flex-1 flex-col">
        <TopBar title={t("packages.title")} />
        <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted">
          {t("packageDetail.notFound")}
        </div>
      </div>
    );
  }

  const network = getNetwork(pkg.network)!;
  const specs = getPackageSpecs(pkg, t);

  return (
    <div className="flex flex-1 flex-col">
      <TopBar title={network.label} />

      <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pb-32">
        <div className="flex flex-col items-center gap-3 pt-4 text-center">
          <NetworkBadge network={pkg.network} size="lg" />
          <div>
            <p className={cn("text-xs font-semibold uppercase tracking-wide", network.textColorClass)}>
              {network.label}
            </p>
            <h1 className="font-display text-2xl font-semibold tracking-tight">
              {pkg.name}
            </h1>
            {pkg.tagline && <p className="mt-1 text-sm text-muted">{pkg.tagline}</p>}
          </div>
          <div className="flex items-center gap-2 rounded-full bg-black/5 px-3 py-1.5 text-xs font-medium text-muted dark:bg-white/5">
            <CalendarClock size={13} />
            {t("packageDetail.validFor")} {pkg.validity}
          </div>
        </div>

        <GlassCard className="flex flex-col items-center gap-1 !py-6">
          {pkg.discountPercentage != null && (
            <span className="mb-1 rounded-full bg-danger px-2.5 py-1 text-[11px] font-bold text-white">
              {pkg.discountPercentage}% {t("common.off")} &middot; {t("packageDetail.save")} Rs {pkg.discountAmount?.toLocaleString()}
            </span>
          )}
          <div className="flex items-baseline gap-2">
            {pkg.originalPrice != null && (
              <span className="font-mono text-lg text-muted line-through tnum">
                Rs {pkg.originalPrice.toLocaleString()}
              </span>
            )}
            <span className={cn("font-mono text-3xl font-bold tnum", pkg.originalPrice != null && "text-danger")}>
              Rs {pkg.price.toLocaleString()}
            </span>
            <span className="text-sm text-muted">/ {pkg.validity}</span>
          </div>
        </GlassCard>

        <div>
          <p className="mb-3 text-sm font-medium text-muted">{t("packageDetail.whatsIncluded")}</p>
          <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
            {specs.map((spec) => (
              <div key={spec.key} className="flex items-center gap-3 px-3 py-3.5">
                <span className="flex h-10 w-10 items-center justify-center rounded-2xl bg-black/5 dark:bg-white/5">
                  <spec.icon size={18} strokeWidth={2} className="text-muted" />
                </span>
                <span className="flex-1 text-sm text-muted">{spec.label}</span>
                <span className="text-sm font-semibold">{spec.value}</span>
              </div>
            ))}
          </GlassCard>
        </div>

        <div className="rounded-3xl border border-dashed border-ink/10 px-4 py-3.5 text-xs leading-relaxed text-muted dark:border-white/10">
          {t("packageDetail.afterPayment")}
        </div>
      </div>

      <div className="sticky bottom-0 flex items-center gap-3 border-t border-black/5 bg-paper/90 px-4 py-4 pb-safe backdrop-blur-xl dark:border-white/5 dark:bg-ink/90">
        <div className="flex-1">
          <p className="text-[10.5px] font-medium uppercase tracking-wide text-muted">
            {t("packageDetail.price")}
          </p>
          <div className="flex items-baseline gap-2">
            <p className={cn("tnum font-mono text-lg font-semibold", pkg.originalPrice != null && "text-danger")}>
              Rs {pkg.price.toLocaleString()}
            </p>
            {pkg.originalPrice != null && (
              <p className="tnum font-mono text-xs text-muted line-through">
                Rs {pkg.originalPrice.toLocaleString()}
              </p>
            )}
          </div>
        </div>
        <Button size="lg" onClick={() => router.push(`/buy/${pkg.id}`)}>
          {t("packageDetail.buyNow")}
        </Button>
      </div>
    </div>
  );
}
