'use client';

import { useState } from 'react';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ShoppingCart,
  PackageSearch,
  Search,
  X,
  SlidersHorizontal,
  ChevronDown,
  Package,
  RefreshCw,
} from 'lucide-react';
import {
  useAdminOrders,
  useExpireOverdueManualPayments,
  useSyncAllPayments,
} from '@/hooks/useAdmin';
import { Pagination } from '@/components/ui/pagination';
import { formatDate, formatIDR, cn } from '@/lib/utils';
import { Order } from '@/types';

import Image from 'next/image';
import { Button } from '@/components/ui';
// ── Helpers ────────────────────────────────────────────────────────────
const toNumber = (value: number | string | null | undefined): number =>
  Number(value ?? 0);

type OrderStatus = Order['status'];

const STATUS_CONFIG: Record<
  OrderStatus,
  {
    label: string;
    badgeBg: string;
    badgeText: string;
    badgeBorder: string;
    dot: string;
  }
> = {
  pending: {
    label: 'Menunggu',
    badgeBg: 'bg-amber-500/10',
    badgeText: 'text-amber-400',
    badgeBorder: 'border-amber-500/20',
    dot: 'bg-amber-400',
  },
  confirmed: {
    label: 'Dikonfirmasi',
    badgeBg: 'bg-cyan-500/10',
    badgeText: 'text-cyan-400',
    badgeBorder: 'border-cyan-500/20',
    dot: 'bg-cyan-400',
  },
  processing: {
    label: 'Diproses',
    badgeBg: 'bg-blue-500/10',
    badgeText: 'text-blue-400',
    badgeBorder: 'border-blue-500/20',
    dot: 'bg-blue-400',
  },
  shipped: {
    label: 'Dikirim',
    badgeBg: 'bg-violet-500/10',
    badgeText: 'text-violet-400',
    badgeBorder: 'border-violet-500/20',
    dot: 'bg-violet-400',
  },
  delivered: {
    label: 'Terkirim',
    badgeBg: 'bg-emerald-500/10',
    badgeText: 'text-emerald-400',
    badgeBorder: 'border-emerald-500/20',
    dot: 'bg-emerald-400',
  },
  completed: {
    label: 'Selesai',
    badgeBg: 'bg-emerald-500/10',
    badgeText: 'text-emerald-400',
    badgeBorder: 'border-emerald-500/20',
    dot: 'bg-emerald-400',
  },
  cancelled: {
    label: 'Dibatalkan',
    badgeBg: 'bg-rose-500/10',
    badgeText: 'text-rose-400',
    badgeBorder: 'border-rose-500/20',
    dot: 'bg-rose-400',
  },
  refunded: {
    label: 'Dikembalikan',
    badgeBg: 'bg-fuchsia-500/10',
    badgeText: 'text-fuchsia-400',
    badgeBorder: 'border-fuchsia-500/20',
    dot: 'bg-fuchsia-400',
  },
};

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' },
];

// ── Components ─────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: OrderStatus | string }) {
  const cfg = STATUS_CONFIG[status as OrderStatus] ?? {
    label: status,
    badgeBg: 'bg-gray-100',
    badgeText: 'text-gray-500',
    badgeBorder: 'border-gray-200',
    dot: 'bg-gray-400',
  };
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-bold uppercase tracking-widest border rounded-full',
        cfg.badgeBg,
        cfg.badgeText,
        cfg.badgeBorder
      )}
    >
      <span className={cn('w-1.5 h-1.5 rounded-full', cfg.dot)} />
      {cfg.label}
    </span>
  );
}

function SearchBar({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div className="relative flex-1 bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
      <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder="Cari no. pesanan atau pelanggan..."
        className="w-full pl-11 pr-10 py-3 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none tracking-wide"
      />
      {value && (
        <button
          onClick={() => onChange('')}
          className="absolute right-3 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-yellow-600 transition-colors rounded-full hover:bg-gray-100"
        >
          <X className="w-4 h-4" />
        </button>
      )}
    </div>
  );
}

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 rounded-xl hover:border-gray-300 hover:bg-gray-50 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>
  );
}

// ── Main Page ──────────────────────────────────────────────────────────

export default function AdminOrdersPage() {
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  const { data, isLoading } = useAdminOrders({
    page,
    per_page: 10,
    search: search || undefined,
    status: statusFilter || undefined,
  });

  const syncPayments = useSyncAllPayments();
  const expireMutation = useExpireOverdueManualPayments();

  const handleSearchChange = (val: string) => {
    setSearch(val);
    setPage(1);
  };
  const handleStatusFilter = (val: string) => {
    setStatusFilter(val);
    setPage(1);
  };

  return (
    <div className="min-h-screen bg-transparent text-gray-900 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={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 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">
              Manajemen <span className="text-yellow-600">Pesanan</span>
            </h1>
            <p className="text-sm font-medium text-gray-500 tracking-wide">
              Pantau dan kelola seluruh transaksi pelanggan dalam satu tempat.
            </p>
          </div>

          {/* Mascot decoration */}
          <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"
              className="w-full h-auto object-contain"
              width={500}
              height={500}
            />
          </div>

          {/* ── TOMBOL SYNC PAYMENTS ── */}
          <Button
            variant="primary"
            onClick={() => {
              syncPayments.mutate();
              expireMutation.mutate();
            }}
            disabled={syncPayments.isPending || expireMutation.isPending}
            leftIcon={<RefreshCw className="w-4 h-4" />}
          >
            {syncPayments.isPending
              ? 'Menyinkronkan...'
              : 'Sync Status Pembayaran'}
          </Button>
        </motion.div>

        {/* ── Filters ── */}
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.05 }}
          className="flex flex-col sm:flex-row gap-3"
        >
          <SearchBar value={search} onChange={handleSearchChange} />
          <StatusFilter value={statusFilter} onChange={handleStatusFilter} />
        </motion.div>

        {/* ── Table Card ── */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="relative bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm"
        >
          {/* Summary Bar */}
          <div className="flex items-center justify-between px-6 py-5 border-b border-gray-200 bg-white/40">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-yellow-50 border border-yellow-200 rounded-xl shadow-sm">
                <ShoppingCart className="w-4 h-4 text-yellow-600" />
              </div>
              <span className="text-xs font-bold text-gray-500 tracking-wide">
                {isLoading || syncPayments.isPending
                  ? 'Memuat data...'
                  : `${data?.meta?.total ?? 0} Pesanan Ditemukan`}
              </span>
            </div>
            {data?.meta && (
              <span className="text-[10px] font-bold text-gray-600 uppercase tracking-widest px-3 py-1 rounded-full bg-white border border-gray-200 shadow-sm">
                Halaman {data.meta.current_page} / {data.meta.last_page}
              </span>
            )}
          </div>

          {isLoading || syncPayments.isPending ? (
            <div className="divide-y divide-gray-100">
              {Array.from({ length: 5 }).map((_, i) => (
                <div
                  key={i}
                  className="flex items-center gap-4 px-6 py-5 animate-pulse"
                >
                  <div className="h-10 w-24 bg-gray-200 rounded-lg" />
                  <div className="flex-1 space-y-2">
                    <div className="h-3 bg-gray-200 rounded w-1/3" />
                    <div className="h-2 bg-gray-200 rounded w-1/4" />
                  </div>
                  <div className="h-6 w-20 bg-gray-200 rounded-full" />
                  <div className="h-5 w-24 bg-gray-200 rounded" />
                </div>
              ))}
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 bg-gray-50/50">
                    {[
                      'No. Pesanan',
                      'Ringkasan',
                      'Status',
                      'Total',
                      'Tanggal',
                      'Aksi',
                    ].map((h) => (
                      <th
                        key={h}
                        className="text-left px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap"
                      >
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {(data?.data ?? []).map((order) => (
                    <tr
                      key={order.id}
                      className="hover:bg-gray-50/50 transition-colors group"
                    >
                      <td className="px-6 py-5">
                        <div className="space-y-1">
                          <span className="block text-sm font-mono font-bold text-yellow-600">
                            {order.order_number}
                          </span>
                          <span className="text-[11px] font-medium text-gray-500">
                            {order.items?.length ?? 0} item
                          </span>
                        </div>
                      </td>

                      <td className="px-6 py-5">
                        <div className="space-y-1">
                          <p className="text-[11px] font-medium text-gray-500 line-clamp-1 max-w-[200px]">
                            {order.items?.[0]?.product_name ??
                              order.items?.[0]?.variant?.product?.name ??
                              'Produk tidak tersedia'}
                          </p>
                          {order.shipping_courier && order.shipping_service && (
                            <div className="inline-flex items-center gap-1.5 px-2 py-0.5 bg-gray-100 border border-gray-200 rounded text-[10px] text-gray-500 mt-1">
                              <Package className="w-3 h-3" />
                              <span className="font-bold uppercase tracking-wider">
                                {order.shipping_courier}
                              </span>{' '}
                              - {order.shipping_service}
                            </div>
                          )}
                        </div>
                      </td>

                      <td className="px-6 py-5">
                        <div className="space-y-1.5">
                          <StatusBadge status={order.status} />
                          {order.status_label && (
                            <p className="text-[10px] font-medium text-gray-500 tracking-wide">
                              {order.status_label}
                            </p>
                          )}
                        </div>
                      </td>

                      <td className="px-6 py-5">
                        <div className="space-y-1">
                          <span className="block text-sm font-black text-gray-900 tracking-tight">
                            {formatIDR(
                              toNumber(order.total) +
                                toNumber(order.payment?.unique_code || 0)
                            )}
                          </span>
                          <span className="text-[10px] font-medium text-gray-500">
                            Ongkir {formatIDR(toNumber(order.shipping_fee))}
                          </span>
                        </div>
                      </td>

                      <td className="px-6 py-5 whitespace-nowrap">
                        <span className="text-xs font-medium text-gray-400 tracking-wide">
                          {formatDate(order.created_at, {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric',
                          })}
                        </span>
                      </td>

                      <td className="px-6 py-5">
                        <Link
                          href={`/dashboard/admin/orders/${order.order_number}`}
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white border border-gray-200 text-xs font-bold text-gray-600 hover:bg-yellow-400 hover:border-yellow-400 hover:text-yellow-900 transition-all shadow-sm"
                        >
                          <PackageSearch className="w-3.5 h-3.5" /> Kelola
                        </Link>
                      </td>
                    </tr>
                  ))}

                  {!isLoading && (data?.data ?? []).length === 0 && (
                    <tr>
                      <td colSpan={6} className="py-24 text-center">
                        <div className="w-16 h-16 bg-white border border-gray-200 rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm">
                          <ShoppingCart className="w-8 h-8 text-gray-400" />
                        </div>
                        <p className="font-bold text-gray-900 text-lg tracking-wide mb-1">
                          {search
                            ? 'Pencarian tidak menemukan hasil'
                            : 'Belum Ada Pesanan'}
                        </p>
                        <p className="text-sm font-medium text-gray-500">
                          {search
                            ? 'Coba gunakan kata kunci atau filter lain.'
                            : 'Pesanan pelanggan akan muncul di sini.'}
                        </p>
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

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