'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { AnimatePresence, motion, Variants } from 'framer-motion';
import {
  Users,
  Award,
  Package,
  Gift,
  AlertCircle,
  History,
  ArrowRight,
} from 'lucide-react';
import {
  RewardService,
  RewardSummary,
  PointTransaction,
  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; color: string; bg: string }> =
  {
    PENDING: {
      label: 'Menunggu',
      color: 'text-amber-700',
      bg: 'bg-amber-500/10',
    },
    APPROVED: {
      label: 'Diproses',
      color: 'text-blue-700',
      bg: 'bg-blue-500/10',
    },
    SHIPPED: {
      label: 'Dikirim',
      color: 'text-violet-700',
      bg: 'bg-violet-500/10',
    },
    DELIVERED: {
      label: 'Terkirim',
      color: 'text-emerald-700',
      bg: 'bg-emerald-500/10',
    },
    REJECTED: {
      label: 'Ditolak',
      color: 'text-rose-700',
      bg: 'bg-rose-500/10',
    },
    COMPLETED: {
      label: 'Selesai',
      color: 'text-emerald-700',
      bg: 'bg-emerald-500/10',
    },
  };

interface UserHistoryData {
  user: {
    id: string;
    name: string;
    email: string;
    points: number;
  };
  history: PointTransaction[];
  redemptions: Redemption[];
}

export default function AdminRewardReportsPage() {
  const [summary, setSummary] = useState<RewardSummary | null>(null);
  const [loading, setLoading] = useState(true);

  const [recentRedemptions, setRecentRedemptions] = useState<Redemption[]>([]);

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

  const fetchData = async () => {
    try {
      const [summaryRes, txRes] = await Promise.all([
        RewardService.adminGetSummary(),
        RewardService.adminGetTransactions(),
      ]);
      setSummary(summaryRes.data);
      setRecentRedemptions(txRes.data.slice(0, 10)); // Take top 10 recent
    } catch (_error) {
      toast.error('Gagal memuat data laporan.');
    } 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-7xl 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 flex-col sm:flex-row sm:items-end justify-between gap-4 relative"
        >
          <div>
            <h1 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
              Laporan <span className="text-yellow-600">Loyalty</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Ringkasan penukaran poin dan performa program loyalty.
            </p>
          </div>

          {/* Mascot */}
          <div className="absolute right-64 -top-8 w-24 md:w-32 opacity-20 pointer-events-none hidden md:block z-0">
            <Image
              src="/mascots/saltu-cooking-pose.avif"
              alt="Saltu Mascot"
              width={200}
              height={200}
              className="w-full h-auto object-contain"
            />
          </div>
        </motion.div>

        {/* ── Summary Cards ── */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-6">
          {[
            {
              label: 'Poin Ditukar',
              value: summary?.total_points_redeemed ?? '-',
              icon: Award,
              color: 'text-yellow-600',
              bg: 'bg-yellow-50',
              borderColor: 'border-yellow-200',
            },
            {
              label: 'User Terlibat',
              value: summary?.unique_users ?? '-',
              icon: Users,
              color: 'text-blue-600',
              bg: 'bg-blue-50',
              borderColor: 'border-blue-200',
            },
            {
              label: 'Fisik Diklaim',
              value: summary?.total_physical_claimed ?? '-',
              icon: Package,
              color: 'text-emerald-600',
              bg: 'bg-emerald-50',
              borderColor: 'border-emerald-200',
            },
            {
              label: 'Voucher Diklaim',
              value: summary?.total_voucher_claimed ?? '-',
              icon: Gift,
              color: 'text-purple-600',
              bg: 'bg-purple-50',
              borderColor: 'border-purple-200',
            },
          ].map((stat, i) => (
            <motion.div
              key={i}
              initial="hidden"
              animate="visible"
              variants={fadeUp}
              custom={i + 1}
              className="bg-white/60 backdrop-blur-xl p-6 rounded-3xl shadow-sm border border-gray-200 flex flex-col justify-center"
            >
              <div className="flex items-center gap-4 mb-4">
                <div
                  className={cn(
                    'w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 border shadow-sm',
                    stat.bg,
                    stat.color,
                    stat.borderColor
                  )}
                >
                  <stat.icon className="w-6 h-6" />
                </div>
                <p className="text-[11px] font-bold text-gray-500 uppercase tracking-widest leading-tight">
                  {stat.label}
                </p>
              </div>
              <h3 className="text-3xl font-black text-gray-900 tracking-tight leading-none">
                {loading ? '-' : stat.value}
              </h3>
            </motion.div>
          ))}
        </div>

        {/* ── Pending Alert ── */}
        <AnimatePresence>
          {summary && summary.pending_count > 0 && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.3 }}
            >
              <div className="p-4 bg-amber-50 border border-amber-200 rounded-2xl flex items-center gap-3 shadow-sm mt-2">
                <AlertCircle className="w-5 h-5 text-amber-600 shrink-0" />
                <p className="text-sm font-bold text-amber-900">
                  Ada{' '}
                  <span className="text-amber-600">
                    {summary.pending_count}
                  </span>{' '}
                  penukaran menunggu verifikasi pengiriman.
                </p>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* ── Recent Redemptions ── */}
        <motion.div
          initial="hidden"
          animate="visible"
          variants={fadeUp}
          custom={6}
          className="bg-white/60 backdrop-blur-xl p-6 md:p-8 rounded-3xl shadow-sm border border-gray-200 mt-6"
        >
          <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-8">
            <div>
              <h3 className="text-xl font-black text-gray-900 tracking-tight mb-1 flex items-center gap-2">
                <History className="w-5 h-5 text-yellow-500" /> Penukaran
                Terbaru
              </h3>
              <p className="text-sm font-medium text-gray-500">
                Daftar transaksi penukaran poin terbaru dari semua user.
              </p>
            </div>

            <Link
              href="/dashboard/admin/rewards/transactions"
              className="inline-flex items-center gap-2 px-5 py-2.5 bg-white border border-gray-200 rounded-xl hover:border-yellow-400 hover:bg-yellow-50 text-gray-600 hover:text-yellow-700 text-sm font-bold tracking-wide transition-all shadow-sm whitespace-nowrap"
            >
              Lihat Semua Transaksi
              <ArrowRight className="w-4 h-4" />
            </Link>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            {loading ? (
              <div className="col-span-full py-8 text-center text-sm font-medium text-gray-500">
                Memuat data penukaran...
              </div>
            ) : recentRedemptions.length === 0 ? (
              <div className="col-span-full flex flex-col items-center justify-center p-8 bg-gray-50/50 border border-gray-100 rounded-2xl">
                <Image
                  src="/mascots/salta-saltu-salto-please-pose.avif"
                  alt="Empty"
                  width={80}
                  height={80}
                  className="opacity-50 mb-3"
                />
                <p className="text-sm font-medium text-gray-500">
                  Belum ada transaksi penukaran.
                </p>
              </div>
            ) : (
              recentRedemptions.map((r) => {
                const statusCfg = STATUS_MAP[r.status] || STATUS_MAP['PENDING'];
                return (
                  <div
                    key={r.id}
                    className="flex flex-col p-5 bg-white border border-gray-200 rounded-2xl shadow-sm hover:border-yellow-200 transition-colors"
                  >
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gray-50 rounded-full flex items-center justify-center border border-gray-100 shrink-0">
                          <Users className="w-5 h-5 text-gray-400" />
                        </div>
                        <div>
                          <p className="text-sm font-bold text-gray-900 line-clamp-1">
                            {r.user?.name || 'User'}
                          </p>
                          <p className="text-[10px] font-medium text-gray-500">
                            {formatDate(r.created_at, {
                              day: 'numeric',
                              month: 'short',
                              year: 'numeric',
                              hour: '2-digit',
                              minute: '2-digit',
                            })}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="pt-3 border-t border-gray-100 mt-auto">
                      <div className="flex items-center justify-between gap-2 mb-2">
                        <div
                          className={cn(
                            'px-2 py-0.5 text-[9px] font-bold uppercase tracking-widest rounded-md border',
                            r.type === 'PHYSICAL'
                              ? 'bg-blue-500/10 text-blue-600 border-blue-500/20'
                              : 'bg-purple-500/10 text-purple-600 border-purple-500/20'
                          )}
                        >
                          {r.type}
                        </div>
                        <span
                          className={cn(
                            'px-2 py-0.5 text-[9px] font-bold uppercase tracking-widest rounded-full border',
                            statusCfg.bg,
                            statusCfg.color,
                            statusCfg.color
                              .replace('text', 'border')
                              .replace('700', '500/20')
                          )}
                        >
                          {statusCfg.label}
                        </span>
                      </div>
                      <div className="flex items-end justify-between">
                        <p className="text-sm font-bold text-gray-900 line-clamp-1 flex-1 pr-2">
                          {r.pointItem?.name || '-'}
                        </p>
                        <span className="text-xs font-black text-yellow-600 whitespace-nowrap">
                          -{r.points_used} Poin
                        </span>
                      </div>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </motion.div>
      </div>
    </div>
  );
}
