'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { motion, Variants } from 'framer-motion';
import {
  ArrowLeft,
  Package,
  Clock,
  Truck,
  CheckCircle2,
  XCircle,
} from 'lucide-react';
import { RewardService, Redemption } from '@/lib/services/reward.service';
import { cn, formatDate } from '@/lib/utils';
import { toast } from 'sonner';

const fadeUp: Variants = {
  hidden: { opacity: 0, y: 16 },
  visible: (i = 0) => ({
    opacity: 1,
    y: 0,
    transition: { delay: i * 0.07, duration: 0.45, ease: [0.22, 1, 0.36, 1] },
  }),
};

const STATUS_MAP: Record<
  string,
  {
    label: string;
    bg: string;
    text: string;
    dot: string;
    icon: React.ElementType;
  }
> = {
  PENDING: {
    label: 'Menunggu',
    bg: 'bg-amber-500/10',
    text: 'text-amber-500',
    dot: 'bg-amber-500',
    icon: Clock,
  },
  APPROVED: {
    label: 'Diproses',
    bg: 'bg-blue-500/10',
    text: 'text-blue-500',
    dot: 'bg-blue-500',
    icon: Package,
  },
  SHIPPED: {
    label: 'Dikirim',
    bg: 'bg-violet-500/10',
    text: 'text-violet-500',
    dot: 'bg-violet-500',
    icon: Truck,
  },
  DELIVERED: {
    label: 'Terkirim',
    bg: 'bg-emerald-500/10',
    text: 'text-emerald-500',
    dot: 'bg-emerald-500',
    icon: CheckCircle2,
  },
  REJECTED: {
    label: 'Ditolak',
    bg: 'bg-rose-500/10',
    text: 'text-rose-500',
    dot: 'bg-rose-500',
    icon: XCircle,
  },
  COMPLETED: {
    label: 'Selesai',
    bg: 'bg-emerald-500/10',
    text: 'text-emerald-500',
    dot: 'bg-emerald-500',
    icon: CheckCircle2,
  },
};

export default function RewardHistoryPage() {
  const [history, setHistory] = useState<Redemption[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchHistory();
  }, []);

  const fetchHistory = async () => {
    try {
      const res = await RewardService.getTransactions();
      setHistory(res.data);
    } catch (_error) {
      toast.error('Gagal memuat riwayat penukaran.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-transparent relative overflow-hidden pb-24">
      {/* Background Glow Blobs */}
      <div className="fixed top-0 right-0 w-[500px] h-[500px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />
      <div className="fixed bottom-0 left-0 w-[400px] h-[400px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />

      <div className="relative z-10 max-w-5xl mx-auto space-y-6 pt-6 px-4 sm:px-6">
        {/* ── Header ── */}
        <motion.div
          initial="hidden"
          animate="visible"
          variants={fadeUp}
          custom={0}
          className="flex items-center gap-4 relative"
        >
          {/* Mascot Header */}
          <div className="absolute right-0 -top-8 pointer-events-none opacity-20 hidden md:block">
            <Image
              src="/mascots/salta-happy.avif"
              alt="Mascot"
              width={100}
              height={100}
              className="object-contain"
            />
          </div>

          <Link
            href="/dashboard/user/rewards"
            className="w-12 h-12 bg-white border border-gray-200 hover:border-yellow-400 hover:bg-yellow-50 rounded-2xl flex items-center justify-center transition-all shadow-sm relative z-10 shrink-0"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </Link>

          <div className="relative z-10">
            <h1 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-1">
              Riwayat <span className="text-yellow-600">Penukaran</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Pantau status penukaran poin Anda di sini.
            </p>
          </div>
        </motion.div>

        {/* ── History List ── */}
        {loading ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <div
                key={i}
                className="h-28 bg-white/40 animate-pulse rounded-3xl"
              />
            ))}
          </div>
        ) : history.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl shadow-sm">
            <Image
              src="/mascots/salta-saltu-salto-please-pose.avif"
              alt="Belum Ada Riwayat"
              width={160}
              height={160}
              className="opacity-70 mb-4"
            />
            <p className="font-bold text-gray-900 text-lg tracking-wide mb-1">
              Belum Ada Riwayat
            </p>
            <p className="text-sm font-medium text-gray-500">
              Anda belum pernah menukarkan poin.
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {history.map((tx, i) => {
              const statusCfg = STATUS_MAP[tx.status] || STATUS_MAP['PENDING'];

              return (
                <motion.div
                  key={tx.id}
                  initial="hidden"
                  animate="visible"
                  variants={fadeUp}
                  custom={i + 1}
                  className="flex flex-col sm:flex-row gap-5 bg-white/60 backdrop-blur-xl border border-gray-200 p-5 rounded-3xl shadow-sm hover:shadow-md transition-shadow relative overflow-hidden group"
                >
                  {/* Left Accent */}
                  <div
                    className={cn(
                      'absolute left-0 top-0 bottom-0 w-1',
                      statusCfg.bg
                    )}
                  />

                  {/* Icon / Image */}
                  <div className="w-20 h-20 bg-gray-50 border border-gray-100 rounded-2xl flex items-center justify-center shrink-0">
                    <Package className="w-10 h-10 text-gray-300 group-hover:scale-110 transition-transform" />
                  </div>

                  {/* Info */}
                  <div className="flex-1 flex flex-col justify-center">
                    <div className="flex flex-wrap items-start justify-between gap-2 mb-1">
                      <h4 className="font-bold text-gray-900 text-lg leading-tight">
                        {tx.pointItem?.name}
                      </h4>
                      <span
                        className={cn(
                          'inline-flex items-center gap-1.5 px-3 py-1 text-[10px] font-bold uppercase tracking-widest border rounded-full border-transparent',
                          statusCfg.bg,
                          statusCfg.text
                        )}
                      >
                        <span
                          className={cn(
                            'w-1.5 h-1.5 rounded-full',
                            statusCfg.dot
                          )}
                        />
                        {statusCfg.label}
                      </span>
                    </div>

                    <div className="text-xs font-medium text-gray-500 mb-3">
                      {formatDate(tx.created_at, {
                        day: 'numeric',
                        month: 'long',
                        year: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </div>

                    <div className="inline-flex w-fit items-center gap-1.5 bg-yellow-50 border border-yellow-200 text-yellow-700 px-3 py-1 rounded-xl text-xs font-bold shadow-sm">
                      -{tx.points_used} Poin
                    </div>
                  </div>

                  {/* Delivery Info if Physical */}
                  {tx.type === 'PHYSICAL' && (
                    <div className="sm:w-72 p-4 bg-gray-50 border border-gray-100 rounded-2xl flex flex-col justify-center">
                      <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-1.5 flex items-center gap-1.5">
                        <Truck className="w-3.5 h-3.5" />
                        Alamat Pengiriman
                      </p>
                      <p className="text-xs text-gray-700 font-medium line-clamp-2">
                        {tx.shipping_address || '-'}
                      </p>
                      {tx.tracking_number && (
                        <div className="mt-3 pt-3 border-t border-gray-200">
                          <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-1">
                            Nomor Resi
                          </p>
                          <p className="text-sm font-mono font-black text-gray-900 tracking-wider bg-white px-2 py-1 border border-gray-200 rounded-lg inline-block shadow-sm">
                            {tx.tracking_number}
                          </p>
                        </div>
                      )}
                    </div>
                  )}
                </motion.div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
