'use client';

import Image from 'next/image';
import Link from 'next/link';
import { motion, Variants } from 'framer-motion';
import {
  User,
  Mail,
  Phone,
  ShoppingCart,
  Package,
  Truck,
  CheckCircle2,
  Clock,
  Edit3,
  Shield,
  XCircle,
  RotateCcw,
  ChevronRight,
  TrendingUp,
  Award,
  ShoppingBag,
  ArrowUpRight,
} from 'lucide-react';
import { useUser } from '@/store/auth.store';
import { useMyOrders } from '@/hooks/useUser';
import { formatIDR, formatDate, cn } from '@/lib/utils';
import { Order } from '@/types';

// ── Animation ─────────────────────────────────────────────────────────
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] },
  }),
};

// ── Status config (shared with orders page) ───────────────────────────
type StatusKey = Order['status'];

const STATUS_CONFIG: Record<
  StatusKey,
  {
    icon: React.ElementType;
    iconColor: string;
    badgeText: string;
    badgeBg: string;
    badgeBorder: string;
    label: string;
    glowColor: string;
  }
> = {
  pending: {
    icon: Clock,
    iconColor: 'text-amber-400',
    badgeText: 'text-amber-400',
    badgeBg: 'bg-amber-500/10',
    badgeBorder: 'border-amber-500/20',
    label: 'Menunggu',
    glowColor: 'rgba(245,158,11,0.12)',
  },
  confirmed: {
    icon: Shield,
    iconColor: 'text-cyan-400',
    badgeText: 'text-cyan-400',
    badgeBg: 'bg-cyan-500/10',
    badgeBorder: 'border-cyan-500/20',
    label: 'Dikonfirmasi',
    glowColor: 'rgba(6,182,212,0.12)',
  },
  processing: {
    icon: Package,
    iconColor: 'text-blue-400',
    badgeText: 'text-blue-400',
    badgeBg: 'bg-blue-500/10',
    badgeBorder: 'border-blue-500/20',
    label: 'Diproses',
    glowColor: 'rgba(59,130,246,0.12)',
  },
  shipped: {
    icon: Truck,
    iconColor: 'text-violet-400',
    badgeText: 'text-violet-400',
    badgeBg: 'bg-violet-500/10',
    badgeBorder: 'border-violet-500/20',
    label: 'Dikirim',
    glowColor: 'rgba(139,92,246,0.12)',
  },
  delivered: {
    icon: CheckCircle2,
    iconColor: 'text-emerald-400',
    badgeText: 'text-emerald-400',
    badgeBg: 'bg-emerald-500/10',
    badgeBorder: 'border-emerald-500/20',
    label: 'Terkirim',
    glowColor: 'rgba(52,211,153,0.12)',
  },
  completed: {
    icon: CheckCircle2,
    iconColor: 'text-emerald-400',
    badgeText: 'text-emerald-400',
    badgeBg: 'bg-emerald-500/10',
    badgeBorder: 'border-emerald-500/20',
    label: 'Selesai',
    glowColor: 'rgba(52,211,153,0.12)',
  },
  cancelled: {
    icon: XCircle,
    iconColor: 'text-rose-400',
    badgeText: 'text-rose-400',
    badgeBg: 'bg-rose-500/10',
    badgeBorder: 'border-rose-500/20',
    label: 'Dibatalkan',
    glowColor: 'rgba(251,113,133,0.12)',
  },
  refunded: {
    icon: RotateCcw,
    iconColor: 'text-fuchsia-400',
    badgeText: 'text-fuchsia-400',
    badgeBg: 'bg-fuchsia-500/10',
    badgeBorder: 'border-fuchsia-500/20',
    label: 'Dikembalikan',
    glowColor: 'rgba(232,121,249,0.12)',
  },
};

// ── Glass card wrapper ─────────────────────────────────────────────────
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 border border-white/50 bg-white/60 backdrop-blur-md overflow-hidden shadow-sm rounded-2xl',
        accentTop && 'border-t-4 border-t-[#FFD738]',
        className
      )}
    >
      {children}
    </motion.div>
  );
}

// ── Stat card ──────────────────────────────────────────────────────────
function StatCard({
  label,
  value,
  icon: Icon,
  iconColor,
  glowColor,
  custom,
}: {
  label: string;
  value: string | number;
  icon: React.ElementType;
  iconColor: string;
  glowColor: string;
  custom: number;
}) {
  return (
    <GlassCard custom={custom} className="px-5 py-5">
      {/* Background glow */}
      <div
        className="absolute -top-4 -right-4 w-20 h-20 rounded-full blur-2xl pointer-events-none"
        style={{ background: glowColor }}
      />
      <div className="relative">
        <div
          className={cn(
            'w-9 h-9 border border-white/50 bg-white flex items-center justify-center mb-4 rounded-xl shadow-sm',
            iconColor
          )}
        >
          <Icon className="w-4 h-4" />
        </div>
        <p className="text-2xl font-black text-gray-900 leading-none mb-1">
          {value}
        </p>
        <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
          {label}
        </p>
      </div>
    </GlassCard>
  );
}

// ── Status badge (inline) ──────────────────────────────────────────────
function StatusBadge({ status }: { status: StatusKey }) {
  const cfg = STATUS_CONFIG[status];
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 px-2.5 py-0.5 text-[9px] font-black uppercase tracking-widest border',
        cfg.badgeBg,
        cfg.badgeText,
        cfg.badgeBorder
      )}
    >
      <span className="w-1 h-1 rounded-full bg-current animate-pulse" />
      {cfg.label}
    </span>
  );
}

// ── Order row ──────────────────────────────────────────────────────────
function OrderRow({ order, index }: { order: Order; index: number }) {
  const cfg = STATUS_CONFIG[order.status];
  const Icon = cfg.icon;
  return (
    <motion.div
      initial={{ opacity: 0, x: -8 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ delay: 0.35 + index * 0.06, duration: 0.35 }}
    >
      <Link href={`/dashboard/user/orders/${order.order_number}`}>
        <div className="group flex items-center gap-4 px-5 py-4 hover:bg-white/80 transition-colors border-b border-gray-200/50 last:border-0 relative overflow-hidden">
          {/* Left glow on hover */}
          <div
            className="absolute left-0 top-0 bottom-0 w-0.5 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
            style={{ background: cfg.glowColor.replace('0.12', '0.9') }}
          />

          {/* Icon */}
          <div
            className={cn(
              'w-9 h-9 border border-gray-200 bg-white flex items-center justify-center shrink-0 rounded-xl shadow-sm',
              cfg.iconColor
            )}
          >
            <Icon className="w-4 h-4" />
          </div>

          {/* Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1 flex-wrap">
              <span className="text-xs font-black text-gray-900 font-mono uppercase tracking-wider">
                {order.order_number}
              </span>
              <StatusBadge status={order.status} />
            </div>
            <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
              {formatDate(order.created_at, {
                day: 'numeric',
                month: 'short',
                year: 'numeric',
              })}
            </p>
          </div>

          {/* Amount + chevron */}
          <div className="flex items-center gap-2 shrink-0">
            <span className="text-sm font-black text-gray-900">
              {formatIDR(
                Number(order.total) + Number(order.payment?.unique_code || 0)
              )}
            </span>
            <div className="w-7 h-7 border border-gray-200 bg-white rounded-lg flex items-center justify-center text-gray-400 group-hover:border-[#FFD738]/40 group-hover:text-[#FFD738] group-hover:translate-x-0.5 transition-all duration-200 shadow-sm">
              <ChevronRight className="w-3.5 h-3.5" />
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────
export default function UserDashboardPage() {
  const user = useUser();

  // Fetch latest orders
  const { data: ordersData, isLoading: ordersLoading } = useMyOrders({
    page: 1,
    per_page: 5,
  });
  const orders = ordersData?.data ?? [];
  const meta = ordersData?.meta;

  // Derived stats from real data
  const totalOrders = meta?.total ?? 0;
  const deliveredCount = orders.filter(
    (o) => o.status === 'delivered' || o.status === 'completed'
  ).length;
  const ongoingCount = orders.filter((o) =>
    ['pending', 'confirmed', 'processing', 'shipped'].includes(o.status)
  ).length;
  const totalSpend = orders.reduce((acc, o) => acc + Number(o.total ?? 0), 0);

  return (
    <div className="max-w-5xl mx-auto space-y-5">
      {/* ── Greeting ── */}
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeUp}
        custom={0}
      >
        <div className="flex items-end justify-between gap-4 flex-wrap">
          <div>
            <p className="text-[10px] font-black text-[#FFD738] uppercase tracking-widest mb-1">
              Selamat Datang Kembali
            </p>
            <h2 className="text-4xl font-black text-gray-900 uppercase  tracking-tighter leading-none">
              Halo,{' '}
              <span className="text-[#FFD738]">
                {user?.name?.split(' ')[0]}
              </span>
            </h2>
            <p className="text-xs font-bold text-gray-500 uppercase tracking-widest mt-2">
              Kelola profil dan pantau pesanan Anda di sini.
            </p>
          </div>
          <Link
            href="/products"
            className="flex items-center gap-2 px-5 py-3 bg-[#FFD738] hover:bg-white text-[#1C1D1F] text-xs font-black uppercase tracking-widest transition-colors shrink-0"
            style={{
              clipPath:
                'polygon(10px 0%, 100% 0%, calc(100% - 10px) 100%, 0% 100%)',
            }}
          >
            Mulai Belanja
            <ArrowUpRight className="w-3.5 h-3.5" />
          </Link>
        </div>
      </motion.div>

      {/* ── Stat cards ── */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <StatCard
          custom={1}
          label="Total Pesanan"
          value={totalOrders}
          icon={ShoppingCart}
          iconColor="text-[#FFD738]"
          glowColor="rgba(255,215,56,0.08)"
        />
        <StatCard
          custom={2}
          label="Selesai"
          value={deliveredCount}
          icon={CheckCircle2}
          iconColor="text-emerald-400"
          glowColor="rgba(52,211,153,0.08)"
        />
        <StatCard
          custom={3}
          label="Dalam Proses"
          value={ongoingCount}
          icon={Truck}
          iconColor="text-violet-400"
          glowColor="rgba(139,92,246,0.08)"
        />
        <StatCard
          custom={4}
          label="Total Belanja"
          value={formatIDR(totalSpend)}
          icon={TrendingUp}
          iconColor="text-blue-400"
          glowColor="rgba(59,130,246,0.08)"
        />
      </div>

      {/* ── Main 2-col ── */}
      <div className="grid lg:grid-cols-3 gap-5">
        {/* Profile card */}
        <GlassCard accentTop custom={5} className="flex flex-col">
          {/* Header banner */}
          <div className="relative px-6 pt-6 pb-14 overflow-hidden bg-[#FFD738]/5">
            {/* Pattern */}
            <div
              className="absolute inset-0 opacity-30"
              style={{
                backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.75' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`,
                backgroundSize: '120px',
              }}
            />
            <div className="relative flex items-center justify-between">
              <span className="text-[10px] font-black text-gray-500 uppercase tracking-widest">
                Profil Saya
              </span>
              <Link
                href="/dashboard/user/profile"
                className="flex items-center gap-1.5 px-3 py-1.5 border border-yellow-200 bg-white/50 text-yellow-700 hover:border-[#FFD738] hover:bg-white hover:text-yellow-600 text-[9px] font-black uppercase tracking-widest transition-all rounded-lg shadow-sm"
              >
                <Edit3 className="w-2.5 h-2.5" />
                Edit
              </Link>
            </div>
          </div>

          {/* Avatar — overlapping the banner */}
          <div className="px-6 -mt-10 mb-4">
            <div className="relative inline-block">
              {user?.avatar_url ? (
                <Image
                  src={user.avatar_url}
                  alt={user.name || ''}
                  width={56}
                  height={56}
                  className="w-14 h-14 object-cover border-2 border-[#FFD738]"
                />
              ) : (
                <div className="w-14 h-14 bg-[#FFD738] flex items-center justify-center border-2 border-[#1C1D1F]">
                  <User className="w-6 h-6 text-[#1C1D1F]" />
                </div>
              )}
              {/* Online indicator */}
              <div
                className={cn(
                  'absolute -bottom-0.5 -right-0.5 w-4 h-4 border-2 border-[#1C1D1F] flex items-center justify-center',
                  user?.status === 'active' ? 'bg-emerald-500' : 'bg-white/20'
                )}
              >
                <span className="w-1.5 h-1.5 bg-white rounded-full" />
              </div>
            </div>
          </div>

          {/* User info */}
          <div className="px-6 pb-6 flex-1 space-y-4">
            <div>
              <div className="absolute right-0 top-10 pointer-events-none opacity-20 hidden md:block">
                <Image
                  src="/mascots/capt-yodi-chill-pose.avif"
                  alt="Captain Yodi"
                  className="w-24 h-24 object-contain"
                  width={500}
                  height={500}
                />
              </div>
              <p className="text-base font-black text-gray-900 uppercase  tracking-tight leading-none relative z-10">
                {user?.name}
              </p>
              <div className="flex items-center gap-2 mt-2 flex-wrap">
                <span className="text-[9px] font-black text-[#FFD738] border border-[#FFD738]/30 bg-[#FFD738]/10 px-2 py-0.5 uppercase tracking-widest">
                  {user?.user_type}
                </span>
                {user?.is_email_verified && (
                  <span className="text-[9px] font-black text-emerald-400 border border-emerald-500/20 bg-emerald-500/10 px-2 py-0.5 uppercase tracking-widest flex items-center gap-1">
                    <Shield className="w-2 h-2" />
                    Terverifikasi
                  </span>
                )}
              </div>
            </div>

            {/* Contact fields */}
            <div className="space-y-2.5">
              {[
                {
                  icon: Mail,
                  value: user?.email,
                  placeholder: 'Email belum diisi',
                },
                {
                  icon: Phone,
                  value: user?.phone,
                  placeholder: 'Telepon belum diisi',
                },
              ].map(({ icon: Icon, value, placeholder }) => (
                <div
                  key={placeholder}
                  className="flex items-center gap-3 p-3 border border-gray-200 bg-white/50 rounded-xl shadow-sm z-10 relative"
                >
                  <Icon className="w-3.5 h-3.5 text-[#FFD738] shrink-0" />
                  <span
                    className={cn(
                      'text-xs font-bold truncate',
                      value ? 'text-gray-700' : 'text-gray-400'
                    )}
                  >
                    {value || placeholder}
                  </span>
                </div>
              ))}
            </div>

            {/* Points strip */}
            <div className="flex items-center justify-between border border-yellow-200 bg-yellow-50 rounded-xl shadow-sm px-4 py-3 z-10 relative">
              <div className="flex items-center gap-2">
                <Award className="w-3.5 h-3.5 text-yellow-600" />
                <span className="text-[10px] font-black text-yellow-700 uppercase tracking-widest">
                  Poin Saya
                </span>
              </div>
              <span className="text-sm font-black text-yellow-600">0 Poin</span>
            </div>
          </div>
        </GlassCard>

        {/* ── Order history panel ── */}
        <GlassCard accentTop custom={6} className="lg:col-span-2 flex flex-col">
          {/* Header */}
          <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200/50 bg-white/40 rounded-t-2xl">
            <div className="flex items-center gap-2">
              <ShoppingBag className="w-3.5 h-3.5 text-[#FFD738]" />
              <span className="text-[10px] font-black text-gray-500 uppercase tracking-widest">
                Pesanan Terakhir
              </span>
            </div>
            <Link
              href="/dashboard/user/orders"
              className="flex items-center gap-1 text-[10px] font-black text-[#FFD738]/60 hover:text-[#FFD738] uppercase tracking-widest transition-colors"
            >
              Lihat Semua
              <ArrowUpRight className="w-3 h-3" />
            </Link>
          </div>

          {/* Loading */}
          {ordersLoading && (
            <div className="divide-y divide-white/4">
              {Array.from({ length: 4 }).map((_, i) => (
                <div
                  key={i}
                  className="flex items-center gap-4 px-5 py-4 animate-pulse"
                >
                  <div className="w-9 h-9 bg-white/5" />
                  <div className="flex-1 space-y-2">
                    <div className="h-2.5 bg-white/5 w-1/3" />
                    <div className="h-2 bg-white/5 w-1/4" />
                  </div>
                  <div className="h-3 bg-white/5 w-16" />
                </div>
              ))}
            </div>
          )}

          {/* Empty */}
          {!ordersLoading && orders.length === 0 && (
            <div className="flex-1 flex flex-col items-center justify-center py-16 text-center">
              <div className="w-14 h-14 border border-gray-200 bg-white flex items-center justify-center mb-4 rounded-xl shadow-sm">
                <ShoppingCart className="w-6 h-6 text-gray-400" />
              </div>
              <p className="font-black text-gray-900 uppercase  text-base tracking-tight">
                Belum Ada Pesanan
              </p>
              <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-1 mb-5">
                Mulai berbelanja untuk melihat riwayat
              </p>
              <Link
                href="/products"
                className="px-6 py-2.5 bg-[#FFD738] text-[#1C1D1F] text-[10px] font-black uppercase tracking-widest hover:bg-white transition-colors"
              >
                Belanja Sekarang
              </Link>
            </div>
          )}

          {/* Orders list */}
          {!ordersLoading && orders.length > 0 && (
            <div className="flex-1 divide-y-0">
              {orders.map((order, i) => (
                <OrderRow key={order.id} order={order} index={i} />
              ))}
            </div>
          )}

          {/* Footer pagination hint */}
          {!ordersLoading && meta && meta.total > 5 && (
            <div className="px-5 py-3 border-t border-gray-200/50 bg-white/40 flex items-center justify-between rounded-b-2xl">
              <span className="text-[10px] font-black text-gray-500 uppercase tracking-widest">
                Menampilkan 5 dari {meta.total} pesanan
              </span>
              <Link
                href="/dashboard/user/orders"
                className="text-[10px] font-black text-yellow-600 hover:text-yellow-700 uppercase tracking-widest transition-colors flex items-center gap-1"
              >
                Semua Pesanan <ChevronRight className="w-3 h-3" />
              </Link>
            </div>
          )}
        </GlassCard>
      </div>

      {/* ── Quick links strip ── */}
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeUp}
        custom={7}
        className="grid grid-cols-2 sm:grid-cols-4 gap-3"
      >
        {[
          {
            label: 'Pesanan Saya',
            icon: ShoppingBag,
            href: '/dashboard/user/orders',
            color: 'text-violet-400',
            glow: 'rgba(139,92,246,0.06)',
          },
          {
            label: 'Klaim Hadiah',
            icon: Award,
            href: '/dashboard/user/rewards',
            color: 'text-[#FFD738]',
            glow: 'rgba(255,215,56,0.06)',
          },
          {
            label: 'Riwayat Transaksi',
            icon: TrendingUp,
            href: '/dashboard/user/history',
            color: 'text-emerald-400',
            glow: 'rgba(52,211,153,0.06)',
          },
          {
            label: 'Edit Profil',
            icon: Edit3,
            href: '/dashboard/user/profile',
            color: 'text-blue-400',
            glow: 'rgba(59,130,246,0.06)',
          },
        ].map(({ label, icon: Icon, href, color, glow }) => (
          <Link key={label} href={href}>
            <div className="group border border-white/50 bg-white/60 hover:bg-white hover:border-yellow-400 px-4 py-4 flex items-center gap-3 transition-all duration-200 relative overflow-hidden rounded-xl shadow-sm">
              <div
                className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
                style={{
                  background: `radial-gradient(ellipse at left center, ${glow}, transparent 70%)`,
                }}
              />
              <Icon className={cn('w-4 h-4 shrink-0 relative', color)} />
              <span className="text-[10px] font-black text-gray-600 group-hover:text-gray-900 uppercase tracking-widest transition-colors relative">
                {label}
              </span>
              <ChevronRight className="w-3 h-3 text-gray-300 group-hover:text-yellow-600 ml-auto relative transition-all group-hover:translate-x-0.5" />
            </div>
          </Link>
        ))}
      </motion.div>
    </div>
  );
}
