'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShoppingCart,
  Package,
  Truck,
  CheckCircle2,
  Clock,
  XCircle,
  ChevronRight,
  ShieldCheck,
  RotateCcw,
  SlidersHorizontal,
  ChevronDown,
  RefreshCw,
} from 'lucide-react';
import { useMyOrders } from '@/hooks/useUser';
import { Pagination } from '@/components/ui/pagination';
import { formatDate, formatIDR, cn } from '@/lib/utils';
import { Order } from '@/types';
import Link from 'next/link';

import Image from 'next/image';
// ── Status config ──────────────────────────────────────────────────────
const STATUS_OPTIONS = [
  { value: '', label: 'Semua Status' },
  { value: 'pending', label: 'Menunggu' },
  { value: 'confirmed', label: 'Dikonfirmasi' },
  { value: 'processing', label: 'Diproses' },
  { value: 'shipped', label: 'Dikirim' },
  { value: 'delivered', label: 'Terkirim' },
  { value: 'completed', label: 'Selesai' },
  { value: 'cancelled', label: 'Dibatalkan' },
  { value: 'refunded', label: 'Dikembalikan' },
];

type StatusKey = Order['status'];

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

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

// ── Status filter dropdown ─────────────────────────────────────────────
function StatusFilter({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const current =
    STATUS_OPTIONS.find((o) => o.value === value) ?? STATUS_OPTIONS[0];

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-2 px-5 py-3 border border-gray-200 bg-white/60 backdrop-blur-md rounded-xl hover:border-yellow-200 hover:bg-white text-gray-600 hover:text-gray-900 text-sm font-bold tracking-wide transition-all whitespace-nowrap shadow-sm"
      >
        <SlidersHorizontal className="w-4 h-4 text-gray-500" />
        {current.label}
        <ChevronDown
          className={cn(
            'w-4 h-4 text-gray-500 transition-transform duration-200',
            open && 'rotate-180'
          )}
        />
      </button>

      <AnimatePresence>
        {open && (
          <>
            <div
              className="fixed inset-0 z-10"
              onClick={() => setOpen(false)}
            />
            <motion.div
              initial={{ opacity: 0, y: 10, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 10, scale: 0.95 }}
              transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
              className="absolute right-0 top-full mt-2 z-20 bg-white border border-gray-200 shadow-xl rounded-xl py-2 min-w-[180px] overflow-hidden"
            >
              {STATUS_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => {
                    onChange(opt.value);
                    setOpen(false);
                  }}
                  className={cn(
                    'w-full text-left px-4 py-2.5 text-xs font-bold uppercase tracking-wider transition-colors',
                    value === opt.value
                      ? 'text-yellow-700 bg-yellow-50'
                      : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
                  )}
                >
                  {opt.label}
                </button>
              ))}
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

// ── Order card ─────────────────────────────────────────────────────────
function OrderCard({ order, index }: { order: Order; index: number }) {
  const cfg = STATUS_CONFIG[order.status];
  const Icon = cfg.icon;

  const paymentStatus = order.payment?.status;
  const canRetry = paymentStatus === 'failed' || paymentStatus === 'expired';
  const isPending = order.status === 'pending' || paymentStatus === 'pending';

  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{
        delay: index * 0.05,
        duration: 0.4,
        ease: [0.22, 1, 0.36, 1],
      }}
    >
      <Link href={`/dashboard/user/orders/${order.order_number}`}>
        <div className="group relative bg-white/60 backdrop-blur-md border border-gray-200 rounded-2xl hover:bg-white hover:border-yellow-200 transition-all duration-300 overflow-hidden shadow-sm">
          {/* Subtle status glow in background */}
          <div
            className="absolute -left-10 top-1/2 -translate-y-1/2 w-32 h-32 rounded-full blur-3xl opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"
            style={{ background: cfg.glowColor }}
          />

          <div className="relative flex flex-col sm:flex-row sm:items-center gap-4 px-5 py-5 sm:px-6">
            {/* Left: Icon & Core Info */}
            <div className="flex flex-1 items-center gap-4 min-w-0">
              <div
                className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 border border-gray-200 bg-white/50 backdrop-blur-sm transition-transform group-hover:scale-105 shadow-sm"
                style={{ boxShadow: `inset 0 0 12px ${cfg.glowColor}` }}
              >
                <Icon className={cn('w-5 h-5', cfg.iconColor)} />
              </div>

              <div className="min-w-0">
                <div className="flex flex-wrap items-center gap-2 mb-1.5">
                  <span className="text-sm font-black text-gray-900 tracking-wide uppercase">
                    {order.order_number}
                  </span>
                  <StatusBadge status={order.status} />
                </div>
                <p className="text-[11px] font-medium text-gray-500 tracking-wide">
                  {formatDate(order.created_at, {
                    day: 'numeric',
                    month: 'long',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                  })}
                </p>
              </div>
            </div>

            {/* ── Conditional Button: Bayar / Ulangi / Detail ── */}
            {canRetry && paymentStatus !== 'expired' ? (
              <div className="flex items-center justify-center gap-2 px-4 py-2.5 border border-[#FFD738]/50 bg-[#FFD738]/10 text-[#FFD738] rounded-xl font-bold text-xs uppercase tracking-wider transition-all shadow-sm group-hover:scale-105 group-hover:bg-[#FFD738]/20">
                <RefreshCw className="w-4 h-4" /> Coba Bayar Ulang
              </div>
            ) : isPending && paymentStatus !== 'expired' ? (
              <div className="flex items-center justify-center gap-2 px-4 py-2.5 bg-[#FFD738] text-[#1C1D1F] rounded-xl font-bold text-xs uppercase tracking-wider transition-all shadow-lg shadow-[#FFD738]/20 group-hover:scale-105 group-hover:bg-[#FFD738]/90">
                Bayar Sekarang <ChevronRight className="w-4 h-4" />
              </div>
            ) : (
              ''
            )}

            {/* Right: Amount + Action */}
            <div className="flex items-center justify-between sm:justify-end gap-4 shrink-0 pl-16 sm:pl-0 mt-2 sm:mt-0">
              <div className="text-left sm:text-right">
                <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-0.5">
                  Total Belanja
                </p>
                <span className="font-black text-[#FFD738] text-lg tracking-tight">
                  {formatIDR(
                    Number(order.total) +
                      Number(order.payment?.unique_code || 0)
                  )}
                </span>
              </div>
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────
export default function UserOrdersPage() {
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState('');

  const { data, isLoading } = useMyOrders({
    page,
    per_page: 8,
    status: statusFilter || undefined,
  });

  const orders = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div className="min-h-screen text-gray-900 relative overflow-hidden pb-12">
      <div className="relative z-10 max-w-5xl mx-auto space-y-8 pt-4">
        {/* ── Header ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 relative z-20"
        >
          <div className="absolute top-0 right-10 pointer-events-none opacity-20 hidden md:block z-0">
            <Image
              src="/mascots/capt-yodi-chill-pose.avif"
              alt="Captain Yodi Mascot"
              className="w-32 h-32 object-contain"
              width={500}
              height={500}
            />
          </div>
          <div className="relative z-10">
            <h2 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
              Riwayat <span className="text-[#FFD738]">Pesanan</span>
            </h2>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Pantau status pengiriman dan kelola pesanan Anda
            </p>
          </div>

          <StatusFilter
            value={statusFilter}
            onChange={(v) => {
              setStatusFilter(v);
              setPage(1);
            }}
          />
        </motion.div>

        {/* ── Stats strip ── */}
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.06 }}
          className="grid grid-cols-2 md:grid-cols-3 gap-4"
        >
          {[
            {
              label: 'Total Pesanan',
              value: meta?.total ?? '—',
              icon: ShoppingCart,
            },
            {
              label: 'Halaman',
              value: meta ? `${meta.current_page} / ${meta.last_page}` : '—',
              icon: Package,
            },
            {
              label: 'Ditampilkan',
              value: meta ? `${meta.from ?? 0}–${meta.to ?? 0}` : '—',
              icon: CheckCircle2,
            },
          ].map(({ label, value, icon: Icon }) => (
            <div
              key={label}
              className="border border-gray-200 bg-white/60 backdrop-blur-md rounded-2xl p-5 shadow-sm"
            >
              <div className="flex items-center gap-2 mb-2">
                <Icon className="w-4 h-4 text-yellow-600" />
                <span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
                  {label}
                </span>
              </div>
              <p className="text-2xl font-black text-gray-900 tracking-tight">
                {value}
              </p>
            </div>
          ))}
        </motion.div>

        {/* ── Order list container ── */}
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-white/60 backdrop-blur-xl border border-white/50 rounded-3xl overflow-hidden shadow-sm"
        >
          {/* Header List */}
          <div className="flex items-center justify-between px-6 py-5 bg-white/40 border-b border-gray-200/50">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
                <ShoppingCart className="w-4 h-4 text-yellow-600" />
              </div>
              <span className="text-sm font-bold text-gray-900 tracking-wide">
                Daftar Pesanan
              </span>
            </div>
            {meta && (
              <span className="text-[10px] font-bold text-gray-600 uppercase tracking-widest px-3 py-1 rounded-full bg-white shadow-sm border border-gray-200">
                {meta.total} Pesanan Ditemukan
              </span>
            )}
          </div>

          <div className="p-6">
            {/* Loading */}
            {isLoading && (
              <div className="space-y-4">
                {Array.from({ length: 4 }).map((_, i) => (
                  <div
                    key={i}
                    className="flex flex-col sm:flex-row items-start sm:items-center gap-4 p-5 rounded-2xl bg-gray-50 border border-gray-200 animate-pulse"
                  >
                    <div className="w-12 h-12 rounded-xl bg-gray-200 shrink-0" />
                    <div className="flex-1 space-y-2 w-full">
                      <div className="h-4 bg-gray-200 rounded w-1/3" />
                      <div className="h-3 bg-gray-200 rounded w-1/4" />
                    </div>
                    <div className="h-6 bg-gray-200 rounded-lg w-24 mt-4 sm:mt-0" />
                  </div>
                ))}
              </div>
            )}

            {/* Empty State */}
            {!isLoading && orders.length === 0 && (
              <div className="py-20 flex flex-col items-center text-center">
                <div className="w-20 h-20 rounded-full border-2 border-dashed border-gray-200 bg-white flex items-center justify-center mb-6 shadow-sm">
                  <ShoppingCart className="w-8 h-8 text-gray-400" />
                </div>
                <p className="font-black text-gray-900 text-xl tracking-tight mb-2">
                  {statusFilter ? 'Tidak Ada Pesanan' : 'Belum Ada Pesanan'}
                </p>
                <p className="text-sm font-medium text-gray-500 mb-8 max-w-sm">
                  {!statusFilter
                    ? 'Anda belum membuat pesanan. Mulai berbelanja untuk melihat riwayat Anda di sini.'
                    : 'Tidak ada pesanan yang sesuai dengan status filter saat ini.'}
                </p>
                {!statusFilter && (
                  <Link
                    href="/products"
                    className="inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-[#FFD738] text-[#1C1D1F] font-bold text-sm hover:bg-[#FFD738]/90 transition-all shadow-lg shadow-[#FFD738]/20"
                  >
                    <Package className="w-4 h-4" /> Mulai Belanja
                  </Link>
                )}
              </div>
            )}

            {/* Order Items */}
            {!isLoading && orders.length > 0 && (
              <div className="space-y-4">
                {orders.map((order, i) => (
                  <OrderCard key={order.id} order={order} index={i} />
                ))}
              </div>
            )}
          </div>

          {/* Pagination */}
          {meta && meta.last_page > 1 && (
            <div className="px-6 py-4 border-t border-gray-200 bg-white/40">
              <Pagination
                currentPage={meta.current_page}
                lastPage={meta.last_page}
                total={meta.total}
                perPage={meta.per_page}
                from={meta.from}
                to={meta.to}
                onPageChange={setPage}
              />
            </div>
          )}
        </motion.div>
      </div>
    </div>
  );
}
