'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, Copy, CheckCircle2, Clock, Tag } from 'lucide-react';
import { RewardService, UserVoucher } from '@/lib/services/reward.service';
import { formatDate, formatIDR } 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] },
  }),
};

export default function VouchersPage() {
  const [vouchers, setVouchers] = useState<UserVoucher[]>([]);
  const [loading, setLoading] = useState(true);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

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

  const fetchVouchers = async () => {
    try {
      const res = await RewardService.getVouchers();
      setVouchers(res.data);
    } catch (_error) {
      toast.error('Gagal memuat voucher.');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (code: string) => {
    navigator.clipboard.writeText(code);
    setCopiedCode(code);
    toast.success('Kode voucher disalin!');
    setTimeout(() => setCopiedCode(null), 2000);
  };

  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/stacking-salta-saltu-salto.avif"
              alt="Mascot"
              width={140}
              height={140}
              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">
              Voucher <span className="text-yellow-600">Saya</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Daftar voucher diskon yang Anda miliki.
            </p>
          </div>
        </motion.div>

        {/* ── Voucher List ── */}
        {loading ? (
          <div className="grid sm:grid-cols-2 gap-6">
            {[1, 2].map((i) => (
              <div
                key={i}
                className="h-40 bg-white/40 animate-pulse rounded-3xl"
              />
            ))}
          </div>
        ) : vouchers.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/salto-happy.avif"
              alt="Belum Ada Voucher"
              width={120}
              height={120}
              className="opacity-70 mb-4"
            />
            <p className="font-bold text-gray-900 text-lg tracking-wide mb-1">
              Belum Ada Voucher
            </p>
            <p className="text-sm font-medium text-gray-500">
              Tukar poin Anda untuk mendapatkan voucher.
            </p>
          </div>
        ) : (
          <div className="grid sm:grid-cols-2 gap-6">
            {vouchers.map((v, i) => (
              <motion.div
                key={v.id}
                initial="hidden"
                animate="visible"
                variants={fadeUp}
                custom={i + 1}
                className="flex bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl shadow-sm hover:shadow-md transition-shadow relative"
              >
                {/* Left edge accent */}
                <div className="w-4 bg-yellow-400 rounded-l-3xl shrink-0 relative flex flex-col items-center justify-between py-6">
                  {/* Dashed cutout effect (optional styling approach) */}
                  <div className="w-1.5 h-1.5 rounded-full bg-white opacity-50" />
                  <div className="w-1.5 h-1.5 rounded-full bg-white opacity-50" />
                  <div className="w-1.5 h-1.5 rounded-full bg-white opacity-50" />
                </div>

                <div className="p-6 flex-1 flex flex-col justify-center border-l border-dashed border-gray-300">
                  <div className="flex items-start justify-between mb-3">
                    <h4 className="font-bold text-gray-900 text-lg leading-tight">
                      {v.pointItem?.name || 'Voucher Diskon'}
                    </h4>
                    <span className="flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-bold uppercase tracking-widest bg-emerald-500/10 text-emerald-600 rounded-full border border-emerald-500/20">
                      <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full" />{' '}
                      Aktif
                    </span>
                  </div>

                  {/* Discount Display */}
                  <div className="flex items-center gap-2 mb-3">
                    <Tag className="w-4 h-4 text-emerald-500" />
                    <span className="text-sm font-black text-emerald-600">
                      Diskon{' '}
                      {v.discount_type === 'PERCENTAGE'
                        ? `${v.discount_value}%`
                        : formatIDR(Number(v.discount_value))}
                    </span>
                  </div>

                  <div className="flex items-center gap-2 text-xs font-medium text-gray-500 mb-4">
                    <Clock className="w-3.5 h-3.5" />
                    Berlaku hingga:{' '}
                    {formatDate(v.valid_until, {
                      day: 'numeric',
                      month: 'long',
                      year: 'numeric',
                    })}
                  </div>

                  <div className="flex items-center gap-3">
                    <div className="flex-1 px-4 py-3 border border-gray-200 bg-white rounded-xl text-center font-mono font-bold text-gray-800 tracking-widest shadow-inner">
                      {v.code}
                    </div>
                    <button
                      onClick={() => copyToClipboard(v.code)}
                      className="p-3 bg-gray-900 hover:bg-gray-800 text-white rounded-xl transition-colors shadow-sm flex items-center gap-2"
                    >
                      {copiedCode === v.code ? (
                        <>
                          <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                          <span className="text-xs font-bold pr-1">
                            Disalin
                          </span>
                        </>
                      ) : (
                        <>
                          <Copy className="w-4 h-4" />
                          <span className="text-xs font-bold pr-1">Salin</span>
                        </>
                      )}
                    </button>
                  </div>

                  {/* Usage hint */}
                  <p className="mt-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">
                    Gunakan kode ini di halaman checkout.
                  </p>
                </div>
              </motion.div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
