'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { motion, AnimatePresence, Variants } from 'framer-motion';
import {
  Award,
  Gift,
  Ticket,
  ArrowRight,
  Clock,
  AlertCircle,
  X,
  MapPin,
  ChevronRight,
} from 'lucide-react';
import { useUser } from '@/store/auth.store';
import { useAuthStore } from '@/store/auth.store';
import { RewardService, PointItem } from '@/lib/services/reward.service';
import { cn, 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] },
  }),
};

function GlassCard({
  children,
  className,
  accentTop,
  custom,
}: {
  children: React.ReactNode;
  className?: string;
  accentTop?: boolean;
  custom?: number;
}) {
  return (
    <motion.div
      initial="hidden"
      animate="visible"
      variants={fadeUp}
      custom={custom}
      className={cn(
        'relative bg-white/60 backdrop-blur-xl border border-gray-200 overflow-hidden shadow-sm rounded-3xl',
        accentTop && 'border-t-4 border-t-yellow-400',
        className
      )}
    >
      {children}
    </motion.div>
  );
}

export default function RewardsPage() {
  const user = useUser();
  const updateUser = useAuthStore((s) => s.updateUser);
  const [items, setItems] = useState<PointItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [redeeming, setRedeeming] = useState<number | null>(null);

  // Shipping address modal state
  const [showAddressModal, setShowAddressModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState<PointItem | null>(null);
  const [shippingAddress, setShippingAddress] = useState('');

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

  const fetchItems = async () => {
    try {
      const res = await RewardService.getItems();
      setItems(res.data);
    } catch (error) {
      console.error(error);
      toast.error('Gagal memuat daftar hadiah.');
    } finally {
      setLoading(false);
    }
  };

  const handleRedeemClick = (item: PointItem) => {
    if (!user || (user.points ?? 0) < item.point_cost) {
      toast.error('Poin tidak mencukupi.');
      return;
    }

    if (item.type === 'PHYSICAL') {
      // Open modal for shipping address
      setSelectedItem(item);
      setShippingAddress('');
      setShowAddressModal(true);
    } else {
      // Voucher: redeem directly
      executeRedeem(item);
    }
  };

  const handleAddressSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedItem) return;
    if (!shippingAddress.trim()) {
      toast.error('Alamat pengiriman wajib diisi.');
      return;
    }
    executeRedeem(selectedItem, shippingAddress.trim());
    setShowAddressModal(false);
  };

  const executeRedeem = async (item: PointItem, address?: string) => {
    setRedeeming(item.id);
    try {
      const res = await RewardService.redeemItem({
        point_item_id: item.id,
        shipping_address: address,
      });
      if (res.success) {
        toast.success(res.message);
        fetchItems(); // refresh stock

        // Update user points in auth store
        if (res.updated_points !== undefined) {
          updateUser({ points: res.updated_points });
        }
      } else {
        toast.error(res.message);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Gagal menukar poin');
    } finally {
      setRedeeming(null);
    }
  };

  const physicalItems = items.filter((i) => i.type === 'PHYSICAL');
  const voucherItems = items.filter((i) => i.type === 'VOUCHER');

  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">
              Tukar <span className="text-yellow-600">Poin</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Tukarkan poin Anda dengan voucher dan hadiah eksklusif.
            </p>
          </div>

          {/* Mascot in Header */}
          <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/stacking-salta-saltu-salto.avif"
              alt="Mascots"
              width={200}
              height={200}
              className="w-full h-auto object-contain"
            />
          </div>

          <div className="flex gap-2 relative z-10">
            <Link
              href="/dashboard/user/rewards/history"
              className="flex items-center gap-2 px-5 py-3 bg-white border border-gray-200 hover:border-yellow-400 hover:bg-yellow-50 text-gray-600 hover:text-yellow-700 text-xs font-bold rounded-xl shadow-sm transition-all shrink-0"
            >
              <Clock className="w-4 h-4" />
              Riwayat
            </Link>
            <Link
              href="/dashboard/user/rewards/vouchers"
              className="flex items-center gap-2 px-5 py-3 bg-gray-900 hover:bg-gray-800 text-white text-xs font-bold rounded-xl shadow-sm transition-colors shrink-0"
            >
              <Ticket className="w-4 h-4 text-yellow-400" />
              Voucher Saya
            </Link>
          </div>
        </motion.div>

        {/* ── Points Summary ── */}
        <GlassCard custom={1} accentTop className="p-6 sm:p-8">
          <div className="flex flex-col md:flex-row items-center justify-between gap-6">
            <div className="flex items-center gap-5">
              <div className="w-16 h-16 bg-yellow-50 rounded-2xl flex items-center justify-center border border-yellow-200 shadow-sm">
                <Award className="w-8 h-8 text-yellow-600" />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-1">
                  Saldo Poin Anda
                </p>
                <h3 className="text-4xl font-black text-gray-900 tracking-tight leading-none">
                  {user?.points || 0}{' '}
                  <span className="text-lg text-yellow-600">Poin</span>
                </h3>
              </div>
            </div>
            <div className="p-4 border border-blue-200 bg-blue-50/50 rounded-2xl max-w-sm flex gap-3 shadow-sm">
              <AlertCircle className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
              <p className="text-xs text-blue-800 font-medium leading-relaxed">
                Kumpulkan lebih banyak poin dari setiap transaksi belanja Anda.
                1 Poin = Rp 1.000 belanja.
              </p>
            </div>
          </div>
        </GlassCard>

        {/* ── Voucher Items ── */}
        <div className="pt-4">
          <h3 className="text-xl font-black text-gray-900 tracking-tight mb-4 flex items-center gap-2">
            <Ticket className="w-5 h-5 text-yellow-500" /> Voucher Diskon
          </h3>
          {loading ? (
            <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => (
                <div
                  key={i}
                  className="h-44 bg-white/40 animate-pulse rounded-3xl"
                />
              ))}
            </div>
          ) : voucherItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center p-12 text-center bg-white/40 rounded-3xl border border-gray-200">
              <Image
                src="/mascots/salta-saltu-salto-please-pose.avif"
                alt="No Vouchers"
                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">
                Saat ini tidak ada voucher diskon yang tersedia.
              </p>
            </div>
          ) : (
            <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-6">
              {voucherItems.map((item, i) => (
                <GlassCard
                  key={item.id}
                  custom={i + 2}
                  className="flex flex-col group border-l-4 border-l-emerald-400"
                >
                  <div className="p-6 flex-1 relative overflow-hidden">
                    <div className="absolute -right-6 -top-6 text-emerald-400/10 group-hover:scale-110 transition-transform duration-500">
                      <Ticket className="w-32 h-32" />
                    </div>
                    <h4 className="font-bold text-gray-900 text-lg leading-tight relative z-10 mb-1">
                      {item.name}
                    </h4>
                    <p className="text-xs font-medium text-gray-500 relative z-10">
                      Diskon{' '}
                      <span className="font-bold text-emerald-600">
                        {item.discount_type === 'PERCENTAGE'
                          ? `${item.discount_value}%`
                          : formatIDR(item.discount_value || 0)}
                      </span>
                    </p>
                    <div className="mt-4 inline-flex items-center gap-1.5 px-3 py-1.5 bg-yellow-50 border border-yellow-200 text-yellow-700 text-xs font-bold rounded-xl shadow-sm">
                      <Award className="w-3.5 h-3.5" />
                      {item.point_cost} Poin
                    </div>
                  </div>
                  <button
                    onClick={() => handleRedeemClick(item)}
                    disabled={
                      redeeming === item.id ||
                      (user?.points ?? 0) < item.point_cost
                    }
                    className="w-full p-4 bg-emerald-500 hover:bg-emerald-600 disabled:bg-gray-200 disabled:text-gray-400 disabled:cursor-not-allowed text-white font-bold text-sm tracking-wide flex items-center justify-center gap-2 transition-colors border-t border-emerald-600/20"
                  >
                    {redeeming === item.id ? 'Memproses...' : 'Tukar Poin'}
                    <ChevronRight className="w-4 h-4" />
                  </button>
                </GlassCard>
              ))}
            </div>
          )}
        </div>

        {/* ── Physical Items ── */}
        <div className="pt-8">
          <h3 className="text-xl font-black text-gray-900 tracking-tight mb-4 flex items-center gap-2">
            <Gift className="w-5 h-5 text-yellow-500" /> Hadiah Fisik
          </h3>
          {loading ? (
            <div className="grid sm:grid-cols-2 md:grid-cols-4 gap-6">
              {[1, 2, 3, 4].map((i) => (
                <div
                  key={i}
                  className="h-64 bg-white/40 animate-pulse rounded-3xl"
                />
              ))}
            </div>
          ) : physicalItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center p-12 text-center bg-white/40 rounded-3xl border border-gray-200">
              <Image
                src="/mascots/salto-happy.avif"
                alt="No Items"
                width={120}
                height={120}
                className="opacity-70 mb-4"
              />
              <p className="font-bold text-gray-900 text-lg tracking-wide mb-1">
                Belum Ada Hadiah Fisik
              </p>
              <p className="text-sm font-medium text-gray-500">
                Saat ini tidak ada barang fisik yang bisa ditukar.
              </p>
            </div>
          ) : (
            <div className="grid sm:grid-cols-2 md:grid-cols-4 gap-6">
              {physicalItems.map((item, i) => (
                <GlassCard
                  key={item.id}
                  custom={i + 4}
                  className="flex flex-col group overflow-hidden"
                >
                  {/* Image Placeholder */}
                  <div className="aspect-square bg-gray-50 flex items-center justify-center relative border-b border-gray-100 group-hover:bg-gray-100 transition-colors">
                    <Gift className="w-16 h-16 text-gray-300 group-hover:scale-110 group-hover:text-yellow-400 transition-all duration-500" />
                    <div className="absolute top-3 right-3 px-2.5 py-1 bg-white/80 backdrop-blur-md text-[10px] font-bold text-gray-600 uppercase tracking-widest rounded-lg border border-gray-200 shadow-sm">
                      Sisa {item.stock}
                    </div>
                  </div>
                  <div className="p-5 flex-1 flex flex-col justify-between">
                    <div>
                      <h4 className="font-bold text-gray-900 leading-tight">
                        {item.name}
                      </h4>
                    </div>
                    <div className="mt-4 flex flex-col gap-3">
                      <span className="inline-flex w-fit items-center gap-1.5 px-3 py-1 bg-yellow-50 border border-yellow-200 text-yellow-700 text-xs font-bold rounded-xl shadow-sm">
                        <Award className="w-3.5 h-3.5" />
                        {item.point_cost} Poin
                      </span>
                      <button
                        onClick={() => handleRedeemClick(item)}
                        disabled={
                          redeeming === item.id ||
                          (user?.points ?? 0) < item.point_cost
                        }
                        className="w-full py-2.5 bg-gray-900 hover:bg-gray-800 disabled:bg-gray-200 disabled:text-gray-400 text-white text-sm font-bold rounded-xl transition-colors flex items-center justify-center gap-1"
                      >
                        {redeeming === item.id ? 'Proses...' : 'Tukar'}
                      </button>
                    </div>
                  </div>
                </GlassCard>
              ))}
            </div>
          )}
        </div>

        {/* ── Shipping Address Modal (for Physical Items) ── */}
        <AnimatePresence>
          {showAddressModal && selectedItem && (
            <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/50 backdrop-blur-sm">
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                className="bg-white rounded-3xl shadow-xl border border-gray-200 w-full max-w-md overflow-hidden"
              >
                {/* Header */}
                <div className="px-6 py-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                  <div>
                    <h3 className="font-black text-gray-900 tracking-tight text-lg">
                      Alamat Pengiriman
                    </h3>
                    <p className="text-[11px] font-medium text-gray-500 mt-1 line-clamp-1">
                      {selectedItem.name}
                    </p>
                  </div>
                  <button
                    onClick={() => setShowAddressModal(false)}
                    className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded-full transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                {/* Form */}
                <form onSubmit={handleAddressSubmit} className="p-6 space-y-5">
                  <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-2xl flex gap-3 shadow-sm">
                    <MapPin className="w-5 h-5 text-yellow-600 shrink-0 mt-0.5" />
                    <p className="text-xs text-yellow-800 font-medium leading-relaxed">
                      Masukkan alamat lengkap untuk pengiriman hadiah Anda.
                      Pastikan alamat benar agar hadiah sampai dengan tepat.
                    </p>
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-gray-700 mb-2">
                      Alamat Lengkap <span className="text-rose-500">*</span>
                    </label>
                    <textarea
                      required
                      rows={4}
                      value={shippingAddress}
                      onChange={(e) => setShippingAddress(e.target.value)}
                      placeholder="Nama penerima, No. HP, Alamat jalan, RT/RW, Kelurahan, Kecamatan, Kota, Provinsi, Kode Pos"
                      className="w-full p-4 border border-gray-200 rounded-2xl text-sm bg-gray-50 resize-none focus:outline-none focus:ring-1 focus:ring-yellow-400 focus:border-yellow-400 transition-all placeholder:text-gray-400 shadow-sm"
                    />
                  </div>

                  <div className="flex gap-3 justify-end pt-2 border-t border-gray-100 mt-4">
                    <button
                      type="button"
                      onClick={() => setShowAddressModal(false)}
                      className="px-5 py-2.5 text-sm font-bold text-gray-600 hover:bg-gray-100 border border-transparent rounded-xl transition-colors"
                    >
                      Batal
                    </button>
                    <button
                      type="submit"
                      disabled={redeeming === selectedItem.id}
                      className="px-6 py-2.5 text-sm font-bold text-yellow-950 bg-yellow-400 rounded-xl hover:bg-yellow-500 disabled:opacity-50 transition-colors flex items-center gap-2 shadow-sm"
                    >
                      {redeeming === selectedItem.id
                        ? 'Memproses...'
                        : 'Konfirmasi'}
                      <ArrowRight className="w-4 h-4" />
                    </button>
                  </div>
                </form>
              </motion.div>
            </div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
