"use client";

import { useState } from "react";
import { m, useReducedMotion } from "framer-motion";
import { Check, CheckCircle2, Clock, Copy, Tag, Ticket, XCircle } from "lucide-react";
import { Container } from "@/components/common/Container";
import { EmptyState } from "@/components/app/EmptyState";
import { useAllCoupons, type NormCoupon } from "@/hooks/queries/useCoupon";
import { useTranslation } from "@/hooks/useTranslation";
import { cn, formatCurrency } from "@/lib/utils";

function CopyButton({ text, variant = "light" }: { text: string; variant?: "light" | "dark" }) {
  const { t } = useTranslation();
  const [copied, setCopied] = useState(false);
  function handleCopy() {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }
  return (
    <button
      type="button"
      onClick={handleCopy}
      aria-label={copied ? t("app.couponsPage.copiedAria") : t("app.couponsPage.copyAria")}
      className={cn(
        "inline-flex items-center gap-1.5 rounded-lg border px-2 py-0.5 text-xs font-semibold transition-all duration-200",
        copied
          ? "border-emerald-300 bg-emerald-50 text-emerald-600 dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-400"
          : variant === "dark"
            ? "border-white/30 bg-white/10 text-white hover:bg-white/20"
            : "border-slate-200 bg-slate-100 text-slate-500 hover:border-brand-300 hover:bg-brand-50 hover:text-brand-600 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400",
      )}
    >
      {copied
        ? <Check className="h-3 w-3" aria-hidden />
        : <Copy className="h-3 w-3" aria-hidden />}
      {copied ? t("app.couponsPage.copied") : t("app.couponsPage.copy")}
    </button>
  );
}

function StatusBadge({ remaining }: { remaining: number }) {
  const { t } = useTranslation();
  if (remaining <= 0) {
    return (
      <span className="inline-flex items-center gap-1 rounded-full bg-rose-50 px-2.5 py-0.5 text-2xs font-bold uppercase tracking-wider text-rose-600 dark:bg-rose-500/15 dark:text-rose-400">
        <XCircle className="h-3 w-3" aria-hidden />
        {t("app.couponsPage.statusExhausted")}
      </span>
    );
  }
  if (remaining <= 5) {
    return (
      <span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2.5 py-0.5 text-2xs font-bold uppercase tracking-wider text-amber-600 dark:bg-amber-500/15 dark:text-amber-400">
        <Clock className="h-3 w-3" aria-hidden />
        {t("app.couponsPage.statusLeft").replace("{n}", String(remaining))}
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-0.5 text-2xs font-bold uppercase tracking-wider text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-400">
      <CheckCircle2 className="h-3 w-3" aria-hidden />
      {t("app.couponsPage.statusActive")}
    </span>
  );
}

function CouponCard({ coupon }: { coupon: NormCoupon }) {
  const { t } = useTranslation();
  const isPercent = coupon.coupon_type.toLowerCase().includes("percent");
  const exhausted = coupon.remaining <= 0;
  const shouldReduceMotion = useReducedMotion();

  return (
    <m.div
      whileHover={
        exhausted || shouldReduceMotion
          ? undefined
          : { y: -4, scale: 1.005, boxShadow: "0 16px 32px -12px rgb(0 0 0 / 0.18)" }
      }
      transition={{ duration: 0.18, ease: "easeOut" }}
      className={cn(
        "relative overflow-hidden rounded-2xl border p-5",
        exhausted
          ? "border-slate-200 bg-slate-50/60 opacity-60 dark:border-slate-800 dark:bg-slate-900/40"
          : "border-brand-100 bg-white shadow-soft dark:border-brand-500/20 dark:bg-slate-900/80",
      )}
    >
      {/* Ticket side notches */}
      <span aria-hidden className="absolute -start-2.5 top-1/2 h-5 w-5 -translate-y-1/2 rounded-full border border-slate-200 bg-slate-50 dark:border-slate-800 dark:bg-slate-950" />
      <span aria-hidden className="absolute -end-2.5 top-1/2 h-5 w-5 -translate-y-1/2 rounded-full border border-slate-200 bg-slate-50 dark:border-slate-800 dark:bg-slate-950" />
      {/* Dashed mid-line */}
      <span aria-hidden className="absolute start-3 end-3 top-1/2 border-t border-dashed border-slate-200 dark:border-slate-700" />

      <div className="relative">
        {/* Top half */}
        <div className="pb-5">
          <div className="flex items-start justify-between gap-3">
            <div className="flex items-center gap-3">
              <span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-brand-50 text-brand-600 dark:bg-brand-500/15 dark:text-brand-300">
                <Tag className="h-5 w-5" aria-hidden />
              </span>
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <p className="text-sm font-bold text-slate-900 dark:text-white">
                    {coupon.name}
                  </p>
                  <CopyButton text={coupon.name} />
                  {coupon.isPersonal && (
                    <span className="rounded-full bg-amber-50 px-2 py-0.5 text-2xs font-bold uppercase tracking-wider text-amber-600 dark:bg-amber-500/15 dark:text-amber-400">
                      {t("app.couponsPage.bonusBadge")}
                    </span>
                  )}
                </div>
                <p className="mt-0.5 text-xs capitalize text-slate-500 dark:text-slate-400">
                  {isPercent ? t("app.couponsPage.typePercent") : t("app.couponsPage.typeFixed")}
                </p>
              </div>
            </div>
            <StatusBadge remaining={coupon.remaining} />
          </div>
        </div>

        {/* Bottom half */}
        <div className="pt-5">
          <div className="flex items-start gap-6">
            <div className="flex-1">
              <p className="text-[length:var(--text-xs-fixed)] font-semibold capitalize tracking-wider text-slate-400 dark:text-slate-500">
                {t("app.couponsPage.discountLabel")}
              </p>
              <p className="mt-0.5 text-2xl font-bold tabular-nums text-brand-600 dark:text-brand-400">
                {isPercent
                  ? `${parseFloat(coupon.price).toFixed(2)}%`
                  : formatCurrency(parseFloat(coupon.price), "USD")}
              </p>
            </div>
            {parseFloat(coupon.max_limit) > 0 && (
              <div>
                <p className="text-[length:var(--text-xs-fixed)] font-semibold capitalize tracking-wider text-slate-400 dark:text-slate-500">
                  {t("app.couponsPage.maxLimitLabel")}
                </p>
                <p className="mt-0.5 text-[length:var(--text-sm-fixed)] font-bold tabular-nums text-slate-700 dark:text-slate-200">
                  {coupon.max_limit}
                </p>
              </div>
            )}
            <div>
              <p className="text-[length:var(--text-xs-fixed)] font-semibold capitalize tracking-wider text-slate-400 dark:text-slate-500">
                {t("app.couponsPage.remainingLabel")}
              </p>
              <p className="mt-0.5 text-[length:var(--text-sm-fixed)] font-bold tabular-nums text-slate-700 dark:text-slate-200">
                {coupon.remaining}
              </p>
            </div>
          </div>
        </div>
      </div>
    </m.div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
      {[1, 2, 3].map((i) => (
        <div
          key={i}
          className="h-44 animate-pulse rounded-2xl border border-slate-200 bg-slate-100 dark:border-slate-800 dark:bg-slate-800"
        />
      ))}
    </div>
  );
}

export default function CouponsPage() {
  const { t } = useTranslation();
  const { coupons: allCoupons, isLoading } = useAllCoupons();

  return (
    <Container className="max-w-full space-y-6">
      <header>
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white sm:text-3xl">
          {t("app.settings.tabs.coupons")}
        </h1>
        <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">
          {t("app.couponsPage.subtitle")}
        </p>
      </header>

      {isLoading ? (
        <LoadingSkeleton />
      ) : allCoupons.length === 0 ? (
        <EmptyState
          icon={Ticket}
          title={t("app.couponsPage.emptyTitle")}
          body={t("app.couponsPage.emptyBody")}
        />
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {allCoupons.map((c) => (
            <CouponCard key={c.id} coupon={c} />
          ))}
        </div>
      )}
    </Container>
  );
}
