"use client";
import { useState, useMemo, useEffect } from "react";
import { useAppSelector } from "@/store/hooks";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence, useMotionValue, useSpring, animate } from "framer-motion";
import {
  TrendingUp,
  Clock,
  CheckCircle,
  RotateCcw,
  Package,
  ArrowUpRight,
  Download,
  Filter,
  Check,
  X,
  type LucideProps,
} from "lucide-react";
import { usePayment } from "@/lib/PaymentContext";
import { SELLER_STATS } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { StatusBadge } from "./StatusBadge";

// ─── Animated counter ─────────────────────────────────────────────────────────
function AnimatedNumber({ value, prefix = "" }: { value: number; prefix?: string }) {
  const [display, setDisplay] = useState(0);

  useEffect(() => {
    const controls = animate(0, value, {
      duration: 1.4,
      ease: [0.16, 1, 0.3, 1],
      onUpdate: (v) => setDisplay(Math.round(v)),
    });
    return controls.stop;
  }, [value]);

  return (
    <span>
      {prefix}
      {display.toLocaleString("en-IN")}
    </span>
  );
}

// ─── Mini bar chart ───────────────────────────────────────────────────────────
function EarningsChart({ data }: { data: { month: string; amount: number }[] }) {
  const max = Math.max(...data.map((d) => d.amount));

  return (
    <div className="flex items-end gap-2 h-24">
      {data.map((d, i) => {
        const pct = (d.amount / max) * 100;
        return (
          <div key={d.month} className="flex flex-col items-center gap-1 flex-1 min-w-0">
            <div className="w-full relative flex items-end justify-center" style={{ height: "80px" }}>
              <motion.div
                initial={{ height: 0 }}
                animate={{ height: `${pct}%` }}
                transition={{ duration: 0.8, delay: i * 0.08, ease: [0.16, 1, 0.3, 1] }}
                className="w-full rounded-t-lg"
                style={{
                  background:
                    i === data.length - 1
                      ? "var(--accent)"
                      : "rgba(252,0,0,0.25)",
                  minHeight: 4,
                }}
              />
            </div>
            <span className="text-[9px] text-[var(--text-muted)] font-medium">{d.month}</span>
          </div>
        );
      })}
    </div>
  );
}

// ─── Stat card ────────────────────────────────────────────────────────────────
function StatCard({
  label,
  value,
  icon: Icon,
  color,
  delay = 0,
  prefix = "",
}: {
  label: string;
  value: number;
  icon: React.ForwardRefExoticComponent<Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>>;
  color: string;
  delay?: number;
  prefix?: string;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, ease: [0.16, 1, 0.3, 1] }}
      className="rounded-2xl p-4 border border-[var(--border)]"
      style={{ background: "var(--card)" }}
    >
      <div className="flex items-start justify-between mb-3">
        <div
          className="w-9 h-9 rounded-xl flex items-center justify-center"
          style={{ background: `${color}18` }}
        >
          <Icon size={17} color={color} className="opacity-90" />
        </div>
        <ArrowUpRight size={13} className="text-[var(--text-muted)] opacity-50" />
      </div>
      <p className="text-xl font-black text-[var(--text-primary)]">
        <AnimatedNumber value={value} prefix={prefix} />
      </p>
      <p className="text-[11px] text-[var(--text-muted)] mt-0.5">{label}</p>
    </motion.div>
  );
}

// ─── COD confirm modal ─────────────────────────────────────────────────────────
function CODModal({
  orderId,
  orderTitle,
  onConfirm,
  onReject,
  onClose,
}: {
  orderId: string;
  orderTitle: string;
  onConfirm: () => void;
  onReject: () => void;
  onClose: () => void;
}) {
  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.7)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.9, y: 20 }}
        animate={{ scale: 1, y: 0 }}
        exit={{ scale: 0.9, y: 20 }}
        className="rounded-2xl overflow-hidden max-w-xs w-full"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="px-5 py-4 border-b border-[var(--border)]">
          <h3 className="font-bold text-[var(--text-primary)]">Confirm COD Payment</h3>
          <p className="text-xs text-[var(--text-muted)] mt-1 line-clamp-1">{orderTitle}</p>
        </div>
        <div className="p-5 space-y-3">
          <p className="text-sm text-[var(--text-muted)]">
            Did you receive cash payment from the buyer? This will mark the order as completed.
          </p>
          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={onConfirm}
            className="w-full py-3 rounded-xl text-white font-bold text-sm flex items-center justify-center gap-2"
            style={{ background: "#22c55e" }}
          >
            <Check size={15} />
            Mark as Paid
          </motion.button>
          <button
            onClick={onReject}
            className="w-full py-3 rounded-xl text-sm font-semibold flex items-center justify-center gap-2 text-red-400 border border-red-500/30"
          >
            <X size={14} />
            Reject Payment
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}

// ─── Main SellerEarnings ──────────────────────────────────────────────────────
export function SellerEarnings() {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const { orders, confirmCOD, rejectCOD } = usePayment();
  const [codModalId, setCodModalId] = useState<string | null>(null);
  const currencyCode = useAppSelector((s) => s.generalSetting.currencyCode);

  const mySellerOrders = useMemo(
    () =>
      orders
        .filter((o) => o.sellerId === "me")
        .sort(
          (a, b) =>
            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        ),
    [orders]
  );

  const stats = SELLER_STATS;
  const pendingCOD = mySellerOrders.filter(
    (o) => o.paymentMethod === "cod" && o.paymentStatus === "pending"
  );

  const codOrder = mySellerOrders.find((o) => o.id === codModalId);

  return (
    <div className="min-h-full pb-20" style={{ background: "var(--bg)" }}>
      <div className="max-w-6xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-xl font-black text-[var(--text-primary)]">Seller Earnings</h1>
            <p className="text-xs text-[var(--text-muted)] mt-0.5">Your complete financial overview</p>
          </div>
          <button
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border border-[var(--border)] text-[var(--text-muted)]"
            style={{ background: "var(--card)" }}
          >
            <Download size={13} />
            Export
          </button>
        </div>

        {/* Pending COD alert */}
        <AnimatePresence>
          {pendingCOD.length > 0 && (
            <motion.div
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className="flex items-center gap-3 p-4 rounded-xl mb-6"
              style={{ background: "rgba(251,146,60,0.1)", border: "1px solid rgba(251,146,60,0.25)" }}
            >
              <Clock size={16} className="text-orange-400 shrink-0" />
              <div className="flex-1">
                <p className="text-xs font-semibold text-orange-400">
                  {pendingCOD.length} COD order{pendingCOD.length > 1 ? "s" : ""} awaiting your confirmation
                </p>
                <p className="text-[10px] text-[var(--text-muted)]">
                  Mark as paid after receiving cash from the buyer.
                </p>
              </div>
              <button
                onClick={() => setCodModalId(pendingCOD[0].id)}
                className="shrink-0 px-3 py-1.5 rounded-lg text-xs font-semibold text-white"
                style={{ background: "#f97316" }}
              >
                Confirm
              </button>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Stat cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
          <StatCard
            label="Total Earnings"
            value={stats.totalEarnings}
            icon={TrendingUp}
            color="#22c55e"
            delay={0}
            prefix={currencyCode}
          />
          <StatCard
            label="Pending"
            value={stats.pendingAmount}
            icon={Clock}
            color="#f0c040"
            delay={0.1}
            prefix={currencyCode}
          />
          <StatCard
            label="Completed"
            value={stats.completedAmount}
            icon={CheckCircle}
            color="#60a5fa"
            delay={0.2}
            prefix={currencyCode}
          />
          <StatCard
            label="Refunded"
            value={stats.refundedAmount}
            icon={RotateCcw}
            color="#f87171"
            delay={0.3}
            prefix={currencyCode}
          />
        </div>

        {/* Chart + AOV */}
        <div className="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-4 mb-6">
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="rounded-2xl p-5 border border-[var(--border)]"
            style={{ background: "var(--card)" }}
          >
            <div className="flex items-center justify-between mb-4">
              <div>
                <p className="text-sm font-bold text-[var(--text-primary)]">Monthly Earnings</p>
                <p className="text-[11px] text-[var(--text-muted)]">Jan – Jun 2026</p>
              </div>
              <div className="text-right">
                <p className="text-sm font-black text-[var(--accent)]">
                  <AnimatedNumber value={stats.monthlyData[5].amount} prefix={currencyCode} />
                </p>
                <p className="text-[10px] text-green-400">This month</p>
              </div>
            </div>
            <EarningsChart data={stats.monthlyData} />
          </motion.div>

          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="rounded-2xl p-5 border border-[var(--border)] flex flex-col justify-center gap-4 min-w-[140px]"
            style={{ background: "var(--card)" }}
          >
            <div>
              <p className="text-[10px] text-[var(--text-muted)] mb-0.5">Avg. Order Value</p>
              <p className="text-lg font-black text-[var(--text-primary)]">
                <AnimatedNumber value={stats.averageOrderValue} prefix={currencyCode} />
              </p>
            </div>
            <div>
              <p className="text-[10px] text-[var(--text-muted)] mb-0.5">Total Orders</p>
              <p className="text-2xl font-black text-[var(--text-primary)]">{stats.totalOrders}</p>
            </div>
            <div>
              <p className="text-[10px] text-[var(--text-muted)] mb-0.5">Conversion</p>
              <p className="text-lg font-black text-green-400">68%</p>
            </div>
          </motion.div>
        </div>

        {/* Transactions table */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
          className="rounded-2xl overflow-hidden border border-[var(--border)]"
          style={{ background: "var(--card)" }}
        >
          <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
            <h2 className="text-sm font-bold text-[var(--text-primary)]">Transactions</h2>
            <span className="text-xs text-[var(--text-muted)]">{mySellerOrders.length} orders</span>
          </div>

          {mySellerOrders.length === 0 ? (
            <div className="flex flex-col items-center py-14 gap-3">
              <Package size={36} className="text-[var(--text-muted)] opacity-40" />
              <p className="font-semibold text-[var(--text-primary)]">No sales yet</p>
              <p className="text-sm text-[var(--text-muted)]">Your earnings will appear here once you make a sale.</p>
              <button
                onClick={() => router.push("/marketplace/create")}
                className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white mt-2"
                style={{ background: "var(--accent)" }}
              >
                Create a Listing
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left min-w-[600px]">
                <thead>
                  <tr style={{ background: "rgba(255,255,255,0.03)" }}>
                    {["Product", "Buyer", "Amount", "Method", "Status", "Date", ""].map((h) => (
                      <th key={h} className="px-5 py-3 text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)]">
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {mySellerOrders.map((order, i) => (
                    <motion.tr
                      key={order.id}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ delay: 0.7 + i * 0.05 }}
                      className="border-t border-[var(--border)] hover:bg-[var(--bg)] transition-colors"
                    >
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <img
                            src={order.listingImage}
                            alt=""
                            className="w-10 h-10 rounded-xl object-cover shrink-0"
                          />
                          <p className="text-xs font-medium text-[var(--text-primary)] line-clamp-1 max-w-[140px]">
                            {order.listingTitle}
                          </p>
                        </div>
                      </td>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-2">
                          <p className="text-xs text-[var(--text-primary)]">{order.buyerInfo.name}</p>
                        </div>
                      </td>
                      <td className="px-5 py-4">
                        <span className="text-sm font-bold text-[var(--accent)]">
                          {formatPrice(order.totalAmount)}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        <span className="text-xs text-[var(--text-muted)]">
                          {order.paymentMethod === "paypal" ? "PayPal" : "COD"}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        <StatusBadge status={order.paymentStatus} size="sm" pulse={order.paymentStatus === "pending"} />
                      </td>
                      <td className="px-5 py-4">
                        <span className="text-[10px] text-[var(--text-muted)]">
                          {new Date(order.createdAt).toLocaleDateString("en-IN", {
                            day: "numeric",
                            month: "short",
                          })}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        {order.paymentMethod === "cod" && order.paymentStatus === "pending" ? (
                          <button
                            onClick={() => setCodModalId(order.id)}
                            className="text-xs px-3 py-1.5 rounded-lg font-semibold text-white whitespace-nowrap"
                            style={{ background: "#f97316" }}
                          >
                            Confirm COD
                          </button>
                        ) : (
                          <button
                            onClick={() => router.push(`/payment/receipt/${order.id}`)}
                            className="text-xs px-3 py-1.5 rounded-lg font-medium border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors whitespace-nowrap"
                          >
                            Details
                          </button>
                        )}
                      </td>
                    </motion.tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </motion.div>
      </div>

      {/* COD Modal */}
      <AnimatePresence>
        {codModalId && codOrder && (
          <CODModal
            orderId={codModalId}
            orderTitle={codOrder.listingTitle}
            onConfirm={() => {
              confirmCOD(codModalId);
              setCodModalId(null);
            }}
            onReject={() => {
              rejectCOD(codModalId);
              setCodModalId(null);
            }}
            onClose={() => setCodModalId(null)}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
