'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowLeft,
  User as UserIcon,
  Mail,
  Phone,
  Calendar,
  MapPin,
  Building,
  ShieldCheck,
  ShieldOff,
  ShoppingBag,
  CreditCard,
  CheckCircle2,
  XCircle,
  Hash,
  Briefcase,
} from 'lucide-react';
import {
  useAdminUser,
  useSuspendUser,
  useActivateUser,
} from '@/hooks/useAdmin';
import { cn, formatIDR, formatDate, getInitials } from '@/lib/utils';
import { UserWithProfile, UserStatus, Order } from '@/types';
import { SuspendDialog } from '../components/SuspendDialog'; // Sesuaikan path

import Image from 'next/image';
// ── Extended Type untuk data aggregate dari backend ────────────────────
interface AdminUserDetail extends UserWithProfile {
  orders_count?: number;
  orders_sum_total?: number;
  successful_orders_count?: number;
  successful_orders_total?: number;
  orders?: Order[];
}

// ── Reusable Info Row ──────────────────────────────────────────────────
function InfoRow({
  icon: Icon,
  label,
  value,
  fallback = '—',
  highlight = false,
}: {
  icon: React.ElementType;
  label: string;
  value?: string | number | null;
  fallback?: string;
  highlight?: boolean;
}) {
  return (
    <div className="flex items-start gap-4 py-3 border-b border-gray-100 last:border-0">
      <div className="p-2 rounded-lg bg-gray-50 border border-gray-200 shrink-0 mt-0.5 shadow-sm">
        <Icon className="w-4 h-4 text-gray-500" />
      </div>
      <div>
        <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1">
          {label}
        </p>
        <p
          className={cn(
            'text-sm font-medium tracking-wide',
            value
              ? highlight
                ? 'text-yellow-600 font-bold'
                : 'text-gray-900'
              : 'text-gray-400 '
          )}
        >
          {value || fallback}
        </p>
      </div>
    </div>
  );
}

// ── Status Badge ───────────────────────────────────────────────────────
function StatusBadge({ status }: { status: UserStatus }) {
  if (status === 'active') {
    return (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-md bg-emerald-50 border border-emerald-200 text-emerald-700 text-[10px] font-bold uppercase tracking-widest shadow-sm">
        <ShieldCheck className="w-3.5 h-3.5" /> Aktif
      </span>
    );
  }
  if (status === 'suspended') {
    return (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-md bg-rose-50 border border-rose-200 text-rose-700 text-[10px] font-bold uppercase tracking-widest shadow-sm">
        <ShieldOff className="w-3.5 h-3.5" /> Suspended
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-md bg-gray-50 border border-gray-200 text-gray-600 text-[10px] font-bold uppercase tracking-widest shadow-sm">
      <XCircle className="w-3.5 h-3.5" /> Inaktif
    </span>
  );
}

// ── Main Page ──────────────────────────────────────────────────────────
export default function AdminUserDetailPage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;

  const { data, isLoading, isError } = useAdminUser(id);
  const user = data as AdminUserDetail | undefined;

  const suspendMutation = useSuspendUser();
  const activateMutation = useActivateUser();

  const [showSuspendModal, setShowSuspendModal] = useState(false);

  const handleActivate = () => activateMutation.mutate(id);
  const handleSuspendConfirm = (reason: string) => {
    suspendMutation.mutate(
      { id, reason },
      { onSuccess: () => setShowSuspendModal(false) }
    );
  };

  const isUpdating = suspendMutation.isPending || activateMutation.isPending;

  if (isLoading) {
    return (
      <div className="max-w-6xl mx-auto space-y-6 animate-pulse pt-6">
        <div className="h-10 bg-white/5 rounded-xl w-1/4 mb-8" />
        <div className="grid lg:grid-cols-3 gap-6">
          <div className="h-[400px] bg-white/5 rounded-3xl" />
          <div className="lg:col-span-2 space-y-6">
            <div className="h-64 bg-white/5 rounded-3xl" />
            <div className="h-64 bg-white/5 rounded-3xl" />
          </div>
        </div>
      </div>
    );
  }

  if (isError || !user) {
    return (
      <div className="max-w-6xl mx-auto py-32 text-center relative z-10">
        <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <UserIcon className="w-10 h-10 text-gray-500" />
        </div>
        <h2 className="font-black text-gray-900 text-2xl tracking-tight mb-2">
          Pengguna Tidak Ditemukan
        </h2>
        <p className="text-gray-500 text-sm mb-6">
          Data pengguna yang Anda cari tidak ada atau telah dihapus.
        </p>
        <Link
          href="/dashboard/admin/users"
          className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-yellow-400 text-gray-900 font-bold text-sm transition-all hover:bg-yellow-500 shadow-md shadow-yellow-400/20"
        >
          <ArrowLeft className="w-4 h-4" /> Kembali ke Daftar
        </Link>
      </div>
    );
  }

  const profile = user.profile;

  return (
    <div className="min-h-screen bg-transparent text-gray-900 relative overflow-hidden pb-24">
      {/* Background Glow */}
      <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none" />
      <div className="absolute bottom-0 left-0 w-[400px] h-[400px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none" />

      <div className="relative z-10 max-w-6xl mx-auto px-4 sm:px-6 pt-6 sm:pt-10 space-y-8">
        {/* ── Header ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col sm:flex-row sm:items-center justify-between gap-6"
        >
          <div className="flex items-start gap-4">
            <button
              onClick={() => router.back()}
              className="p-3 rounded-xl bg-white/60 backdrop-blur-sm border border-gray-200 text-gray-500 hover:text-gray-900 hover:bg-gray-50 transition-all mt-1 shrink-0 shadow-sm"
            >
              <ArrowLeft className="w-5 h-5" />
            </button>
            <div>
              <div className="flex items-center gap-3 mb-2 flex-wrap">
                <h1 className="text-3xl font-black text-gray-900 tracking-tight leading-none">
                  Detail <span className="text-yellow-600">Pengguna</span>
                </h1>
                <StatusBadge status={user.status as UserStatus} />
              </div>
              <div className="flex gap-2 flex-wrap">
                {user.roles.map((role) => (
                  <span
                    key={role}
                    className="text-[10px] font-bold text-gray-600 border border-gray-200 bg-gray-50 px-2.5 py-1 rounded-md uppercase tracking-widest"
                  >
                    {role}
                  </span>
                ))}
                <span className="text-[10px] font-bold text-gray-500 border border-transparent px-2.5 py-1 uppercase tracking-widest flex items-center gap-1">
                  <Calendar className="w-3 h-3" /> Bergabung:{' '}
                  {formatDate(user.created_at, {
                    month: 'short',
                    year: 'numeric',
                  })}
                </span>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-3">
            {user.status !== 'active' && (
              <button
                onClick={handleActivate}
                disabled={isUpdating}
                className="px-6 py-3 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 hover:bg-emerald-100 text-sm font-bold tracking-wide transition-all disabled:opacity-50 flex items-center gap-2 shadow-sm"
              >
                <ShieldCheck className="w-4 h-4" /> Aktifkan
              </button>
            )}
            {user.status !== 'suspended' && (
              <button
                onClick={() => setShowSuspendModal(true)}
                disabled={isUpdating}
                className="px-6 py-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 hover:bg-rose-100 text-sm font-bold tracking-wide transition-all disabled:opacity-50 flex items-center gap-2 shadow-sm"
              >
                <ShieldOff className="w-4 h-4" /> Suspend
              </button>
            )}
          </div>
        </motion.div>

        <div className="grid lg:grid-cols-3 gap-6">
          {/* ── LEFT: Profile Card & Stats ── */}
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="space-y-6"
          >
            <div className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm p-6 sm:p-8 flex flex-col items-center text-center">
              <div className="relative mb-6">
                {user.avatar_url ? (
                  <Image
                    src={user.avatar_url}
                    alt={user.name}
                    className="w-32 h-32 rounded-full object-cover border-4 border-white shadow-md"
                    width={500}
                    height={500}
                  />
                ) : (
                  <div className="w-32 h-32 rounded-full bg-yellow-100 border-4 border-white shadow-md flex items-center justify-center">
                    <span className="text-4xl font-black text-yellow-600">
                      {getInitials(user.name)}
                    </span>
                  </div>
                )}
                {user.is_email_verified && (
                  <div
                    className="absolute bottom-2 right-2 bg-emerald-500 rounded-full p-1 border-2 border-white"
                    title="Email Terverifikasi"
                  >
                    <CheckCircle2 className="w-4 h-4 text-white" />
                  </div>
                )}
              </div>
              <h2 className="text-xl font-black text-gray-900 tracking-wide mb-1">
                {user.name}
              </h2>
              <p className="text-sm font-medium text-gray-500 mb-6">
                {user.email}
              </p>

              <div className="w-full flex flex-col gap-3 pt-6 border-t border-gray-100">
                {/* Total Pesanan */}
                <div className="bg-gray-50 rounded-2xl p-4 border border-gray-200 flex items-center justify-between gap-4 transition-colors hover:border-gray-300">
                  <div className="flex items-center gap-3 shrink-0">
                    <div className="p-2 bg-white rounded-xl border border-gray-200 shadow-sm">
                      <ShoppingBag className="w-4 h-4 text-gray-500" />
                    </div>
                    <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest text-left">
                      Total Pesanan
                    </p>
                  </div>
                  <p className="text-sm font-black text-gray-900 truncate text-right">
                    {user.orders_count ?? 0}
                  </p>
                </div>

                {/* Total Belanja */}
                <div className="bg-gray-50 rounded-2xl p-4 border border-gray-200 flex items-center justify-between gap-4 transition-colors hover:border-gray-300">
                  <div className="flex items-center gap-3 shrink-0">
                    <div className="p-2 bg-white rounded-xl border border-gray-200 shadow-sm">
                      <CreditCard className="w-4 h-4 text-gray-500" />
                    </div>
                    <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest text-left">
                      Total Belanja
                    </p>
                  </div>
                  <p className="text-sm font-black text-gray-900 truncate text-right">
                    {formatIDR(user.orders_sum_total ?? 0)}
                  </p>
                </div>

                {/* Pesanan Sukses */}
                <div className="bg-emerald-50 rounded-2xl p-4 border border-emerald-200 flex items-center justify-between gap-4 transition-colors hover:border-emerald-300">
                  <div className="flex items-center gap-3 shrink-0">
                    <div className="p-2 bg-white rounded-xl border border-emerald-200 shadow-sm">
                      <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                    </div>
                    <p className="text-[10px] font-bold text-emerald-700 uppercase tracking-widest text-left">
                      Pesanan Sukses
                    </p>
                  </div>
                  <p className="text-sm font-black text-emerald-700 truncate text-right">
                    {user.successful_orders_count ?? 0}
                  </p>
                </div>

                {/* Total Sukses */}
                <div className="bg-yellow-50 rounded-2xl p-4 border border-yellow-200 flex items-center justify-between gap-4 transition-colors hover:border-yellow-300">
                  <div className="flex items-center gap-3 shrink-0">
                    <div className="p-2 bg-white rounded-xl border border-yellow-200 shadow-sm">
                      <CreditCard className="w-4 h-4 text-yellow-600" />
                    </div>
                    <p className="text-[10px] font-bold text-yellow-700 uppercase tracking-widest text-left">
                      Total Sukses
                    </p>
                  </div>
                  <p className="text-sm font-black text-yellow-700 truncate text-right">
                    {formatIDR(user.successful_orders_total ?? 0)}
                  </p>
                </div>
              </div>
            </div>
          </motion.div>

          {/* ── RIGHT: Details ── */}
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="lg:col-span-2 space-y-6"
          >
            {/* Personal Info */}
            <div className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm">
              <div className="flex items-center gap-3 px-6 sm:px-8 py-5 border-b border-gray-200 bg-white/40">
                <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
                  <UserIcon className="w-4 h-4 text-yellow-600" />
                </div>
                <span className="text-sm font-bold text-gray-900 tracking-wide">
                  Informasi Kontak & Personal
                </span>
              </div>
              <div className="p-6 sm:p-8 grid sm:grid-cols-2 gap-x-8 gap-y-2">
                <InfoRow icon={Mail} label="Email" value={user.email} />
                <InfoRow
                  icon={Phone}
                  label="Nomor Telepon"
                  value={user.phone}
                />
                <InfoRow
                  icon={UserIcon}
                  label="Jenis Kelamin"
                  value={
                    profile?.gender === 'male'
                      ? 'Laki-laki'
                      : profile?.gender === 'female'
                        ? 'Perempuan'
                        : null
                  }
                />
                <InfoRow
                  icon={Calendar}
                  label="Tanggal Lahir"
                  value={
                    profile?.date_of_birth
                      ? formatDate(profile.date_of_birth)
                      : null
                  }
                />
              </div>
            </div>

            {/* Address Info */}
            <div className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm">
              <div className="flex items-center gap-3 px-6 sm:px-8 py-5 border-b border-gray-200 bg-white/40">
                <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
                  <MapPin className="w-4 h-4 text-yellow-600" />
                </div>
                <span className="text-sm font-bold text-gray-900 tracking-wide">
                  Alamat Lengkap
                </span>
              </div>
              <div className="p-6 sm:p-8 grid sm:grid-cols-2 gap-x-8 gap-y-2">
                <div className="sm:col-span-2">
                  <InfoRow
                    icon={MapPin}
                    label="Alamat Spesifik"
                    value={profile?.address}
                  />
                </div>
                <InfoRow
                  icon={Building}
                  label="Kota/Kabupaten"
                  value={profile?.city}
                />
                <InfoRow
                  icon={MapPin}
                  label="Provinsi"
                  value={profile?.province}
                />
                <InfoRow
                  icon={Hash}
                  label="Kode Pos"
                  value={profile?.postal_code}
                />
              </div>
            </div>

            {/* Business Info (Visible if roles include umkm/distributor or if fields exist) */}
            {(profile?.company_name ||
              profile?.distributor_code ||
              profile?.umkm_registration_no) && (
              <div className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm">
                <div className="flex items-center gap-3 px-6 sm:px-8 py-5 border-b border-gray-200 bg-white/40">
                  <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
                    <Briefcase className="w-4 h-4 text-yellow-600" />
                  </div>
                  <span className="text-sm font-bold text-gray-900 tracking-wide">
                    Informasi Bisnis
                  </span>
                </div>
                <div className="p-6 sm:p-8 grid sm:grid-cols-2 gap-x-8 gap-y-2">
                  <div className="sm:col-span-2">
                    <InfoRow
                      icon={Building}
                      label="Nama Perusahaan / Toko"
                      value={profile?.company_name}
                      highlight
                    />
                  </div>
                  <InfoRow
                    icon={Hash}
                    label="Kode Distributor"
                    value={profile?.distributor_code}
                  />
                  <InfoRow
                    icon={Hash}
                    label="NIB / Registrasi UMKM"
                    value={profile?.umkm_registration_no}
                  />
                </div>
              </div>
            )}
          </motion.div>
        </div>

        {/* Orders History */}
        {user.orders && user.orders.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm"
          >
            <div className="flex items-center gap-3 px-6 sm:px-8 py-5 border-b border-gray-200 bg-white/40">
              <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
                <ShoppingBag className="w-4 h-4 text-yellow-600" />
              </div>
              <span className="text-sm font-bold text-gray-900 tracking-wide">
                Riwayat Pesanan
              </span>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-gray-200 bg-white/20">
                    <th className="py-4 px-6 sm:px-8 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                      Order ID
                    </th>
                    <th className="py-4 px-6 sm:px-8 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                      Tanggal
                    </th>
                    <th className="py-4 px-6 sm:px-8 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap">
                      Status
                    </th>
                    <th className="py-4 px-6 sm:px-8 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap text-right">
                      Total
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {user.orders.map((order) => (
                    <tr
                      key={order.id}
                      className="hover:bg-gray-50 transition-colors group"
                    >
                      <td className="py-4 px-6 sm:px-8">
                        <Link
                          href={`/dashboard/admin/orders/${order.order_number}`}
                          className="text-sm font-bold text-gray-900 group-hover:text-yellow-600 transition-colors block"
                        >
                          {order.order_number}
                        </Link>
                      </td>
                      <td className="py-4 px-6 sm:px-8 text-sm text-gray-500 whitespace-nowrap">
                        {formatDate(order.created_at, {
                          month: 'short',
                          year: 'numeric',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </td>
                      <td className="py-4 px-6 sm:px-8 whitespace-nowrap">
                        <span
                          className={cn(
                            'text-[10px] font-bold uppercase tracking-widest px-2.5 py-1 rounded-md border inline-flex items-center',
                            order.status === 'delivered' ||
                              order.status === 'completed'
                              ? 'bg-emerald-50 border-emerald-200 text-emerald-700 shadow-sm'
                              : order.status === 'cancelled' ||
                                  order.status === 'refunded'
                                ? 'bg-rose-50 border-rose-200 text-rose-700 shadow-sm'
                                : order.status === 'pending'
                                  ? 'bg-yellow-50 border-yellow-200 text-yellow-700 shadow-sm'
                                  : 'bg-blue-50 border-blue-200 text-blue-700 shadow-sm'
                          )}
                        >
                          {order.status_label || order.status}
                        </span>
                      </td>
                      <td className="py-4 px-6 sm:px-8 text-sm font-black text-gray-900 text-right whitespace-nowrap">
                        {formatIDR(
                          Number(order.total) +
                            Number(order.payment?.unique_code || 0)
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </motion.div>
        )}
      </div>

      {/* Suspend Modal */}
      <AnimatePresence>
        {showSuspendModal && (
          <SuspendDialog
            user={user}
            onConfirm={handleSuspendConfirm}
            onCancel={() => setShowSuspendModal(false)}
            isPending={suspendMutation.isPending}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
