"use client";
import { useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Clock,
  Download,
  ExternalLink,
  RefreshCw,
  Filter,
  Search,
  X,
  ChevronDown,
  RotateCcw,
  Package,
  ShoppingBag,
} from "lucide-react";
import { usePayment } from "@/lib/PaymentContext";
import { StatusBadge } from "./StatusBadge";
import { formatDate } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import type { PaymentStatus } from "./types";

const STATUS_FILTERS: { key: string; label: string }[] = [
  { key: "all", label: "All" },
  { key: "paid", label: "Paid" },
  { key: "pending", label: "Pending" },
  { key: "refunded", label: "Refunded" },
  { key: "failed", label: "Failed" },
  { key: "cancelled", label: "Cancelled" },
];

function RefundModal({
  orderId,
  onClose,
}: {
  orderId: string;
  onClose: () => void;
}) {
  const { requestRefund } = usePayment();
  const [reason, setReason] = useState("");
  const [done, setDone] = useState(false);

  const REASONS = [
    "Item not as described",
    "Did not receive item",
    "Item damaged/defective",
    "Changed my mind",
  ];

  const submit = () => {
    if (!reason) return;
    requestRefund(orderId, reason);
    setDone(true);
    setTimeout(onClose, 1500);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4"
      style={{ background: "rgba(0,0,0,0.7)" }}
      onClick={onClose}
    >
      <motion.div
        initial={{ y: "100%" }}
        animate={{ y: 0 }}
        exit={{ y: "100%" }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        className="w-full sm:max-w-sm rounded-t-3xl sm:rounded-2xl overflow-hidden"
        style={{ background: "var(--card)" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 pt-5 pb-3 border-b border-[var(--border)]">
          <h3 className="font-bold text-[var(--text-primary)] flex items-center gap-2">
            <RotateCcw size={15} className="text-blue-400" /> Request Refund
          </h3>
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-[var(--bg)]"
          >
            <X size={15} className="text-[var(--text-muted)]" />
          </button>
        </div>

        {done ? (
          <div className="flex flex-col items-center py-10 gap-2">
            <span className="text-4xl">✅</span>
            <p className="font-semibold text-[var(--text-primary)]">
              Refund Requested
            </p>
            <p className="text-xs text-[var(--text-muted)]">
              We'll process it within 3-5 business days.
            </p>
          </div>
        ) : (
          <div className="p-4 space-y-3">
            <p className="text-xs text-[var(--text-muted)]">Select a reason:</p>
            {REASONS.map((r) => (
              <button
                key={r}
                onClick={() => setReason(r)}
                className="w-full text-left px-4 py-2.5 rounded-xl text-sm transition-colors border"
                style={{
                  background:
                    reason === r ? "rgba(96,165,250,0.1)" : "var(--bg)",
                  borderColor: reason === r ? "#60a5fa" : "var(--border)",
                  color: reason === r ? "#60a5fa" : "var(--text-primary)",
                }}
              >
                {r}
              </button>
            ))}
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={submit}
              disabled={!reason}
              className="w-full py-3 rounded-xl text-sm font-bold text-white disabled:opacity-40 mt-2"
              style={{ background: "#3b82f6" }}
            >
              Submit Refund Request
            </motion.button>
          </div>
        )}
      </motion.div>
    </motion.div>
  );
}

export function BuyerHistory() {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const { orders } = usePayment();
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [refundOrderId, setRefundOrderId] = useState<string | null>(null);

  const myOrders = useMemo(
    () =>
      orders
        .filter((o) => o.buyerId === "me")
        .filter((o) => (filter === "all" ? true : o.paymentStatus === filter))
        .filter((o) =>
          search
            ? o.listingTitle.toLowerCase().includes(search.toLowerCase()) ||
              o.id.toLowerCase().includes(search.toLowerCase())
            : true,
        )
        .sort(
          (a, b) =>
            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
        ),
    [orders, filter, search],
  );

  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-5">
          <div>
            <h1 className="text-lg font-black text-[var(--text-primary)]">
              Payment History
            </h1>
            <p className="text-xs text-[var(--text-muted)]">
              {myOrders.length} transactions
            </p>
          </div>
          <button
            onClick={() => router.push("/seller/earnings")}
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold"
            style={{
              background: "rgba(240,192,64,0.1)",
              color: "#f0c040",
              border: "1px solid rgba(240,192,64,0.3)",
            }}
          >
            My Earnings →
          </button>
        </div>

        {/* Search */}
        <div
          className="flex items-center gap-2 rounded-xl px-4 py-2.5 mb-4"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
          }}
        >
          <Search size={14} className="text-[var(--text-muted)]" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by product or order ID…"
            className="flex-1 bg-transparent outline-none text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
          />
          {search && (
            <button onClick={() => setSearch("")}>
              <X size={13} className="text-[var(--text-muted)]" />
            </button>
          )}
        </div>

        {/* Filter tabs */}
        <div className="flex gap-1.5 overflow-x-auto no-scrollbar mb-5 pb-1">
          {STATUS_FILTERS.map((f) => (
            <button
              key={f.key}
              onClick={() => setFilter(f.key)}
              className="shrink-0 px-3 py-1.5 rounded-full text-xs font-semibold transition-colors"
              style={{
                background: filter === f.key ? "var(--accent)" : "var(--card)",
                color: filter === f.key ? "#fff" : "var(--text-muted)",
                border: `1px solid ${filter === f.key ? "var(--accent)" : "var(--border)"}`,
              }}
            >
              {f.label}
            </button>
          ))}
        </div>

        {/* Order list */}
        <AnimatePresence mode="popLayout">
          {myOrders.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="flex flex-col items-center justify-center py-20 gap-4"
            >
              <div
                className="w-16 h-16 rounded-2xl flex items-center justify-center"
                style={{ background: "var(--card)" }}
              >
                <ShoppingBag size={28} className="text-[var(--text-muted)]" />
              </div>
              <p className="font-semibold text-[var(--text-primary)]">
                No payments found
              </p>
              <p className="text-sm text-[var(--text-muted)] text-center">
                {search
                  ? "Try a different search term."
                  : "You haven't made any purchases yet."}
              </p>
              <button
                onClick={() => router.push("/marketplace")}
                className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white"
                style={{ background: "var(--accent)" }}
              >
                Browse Marketplace
              </button>
            </motion.div>
          ) : (
            <div className="space-y-3">
              {myOrders.map((order, i) => (
                <motion.div
                  key={order.id}
                  layout
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  transition={{ delay: i * 0.05 }}
                  className="rounded-2xl overflow-hidden border border-[var(--border)]"
                  style={{ background: "var(--card)" }}
                >
                  {/* Top: product info */}
                  <div className="flex gap-3 p-4 border-b border-[var(--border)]">
                    <img
                      src={order.listingImage}
                      alt={order.listingTitle}
                      className="w-16 h-16 rounded-xl object-cover shrink-0"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-[var(--text-primary)] line-clamp-1 mb-1">
                        {order.listingTitle}
                      </p>
                      <div className="flex items-center gap-2 mb-2">
                        <img
                          src={order.sellerAvatar}
                          alt=""
                          className="w-4 h-4 rounded-full object-cover"
                        />
                        <span className="text-xs text-[var(--text-muted)]">
                          {order.sellerName}
                        </span>
                      </div>
                      <StatusBadge
                        status={order.paymentStatus}
                        size="sm"
                        pulse={order.paymentStatus === "pending"}
                      />
                    </div>
                    <div className="text-right shrink-0">
                      <p className="text-base font-black text-[var(--accent)]">
                        {formatPrice(order.totalAmount)}
                      </p>
                      <p className="text-[10px] text-[var(--text-muted)] mt-1">
                        {order.paymentMethod === "paypal" ? "PayPal" : "COD"}
                      </p>
                    </div>
                  </div>

                  {/* Details row */}
                  <div className="flex items-center gap-4 px-4 py-2.5 border-b border-[var(--border)]">
                    <div className="flex-1">
                      <p className="text-[10px] text-[var(--text-muted)]">
                        Order ID
                      </p>
                      <p className="text-xs font-mono text-[var(--text-primary)]">
                        {order.id.toUpperCase()}
                      </p>
                    </div>
                    {order.transactionId && (
                      <div className="flex-1">
                        <p className="text-[10px] text-[var(--text-muted)]">
                          Transaction
                        </p>
                        <p className="text-xs font-mono text-[var(--text-primary)] truncate">
                          {order.transactionId}
                        </p>
                      </div>
                    )}
                    <div>
                      <p className="text-[10px] text-[var(--text-muted)]">
                        Date
                      </p>
                      <p className="text-[10px] text-[var(--text-muted)]">
                        {new Date(order.createdAt).toLocaleDateString("en-IN", {
                          day: "numeric",
                          month: "short",
                          year: "numeric",
                        })}
                      </p>
                    </div>
                  </div>

                  {/* Refund badge */}
                  {order.refundStatus && (
                    <div
                      className="flex items-center gap-2 px-4 py-2 border-b border-[var(--border)]"
                      style={{ background: "rgba(96,165,250,0.06)" }}
                    >
                      <RotateCcw size={11} className="text-blue-400" />
                      <span className="text-[10px] text-blue-400 font-medium">
                        Refund {order.refundStatus} · {order.refundReason}
                      </span>
                    </div>
                  )}

                  {/* Actions */}
                  <div className="flex items-center gap-2 px-4 py-3">
                    <button
                      onClick={() =>
                        router.push(`/payment/receipt/${order.id}`)
                      }
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
                      style={{ background: "var(--bg)" }}
                    >
                      <Download size={11} />
                      Receipt
                    </button>
                    <button
                      onClick={() =>
                        router.push(`/marketplace/listing/${order.listingSlug}`)
                      }
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
                      style={{ background: "var(--bg)" }}
                    >
                      <ExternalLink size={11} />
                      View Order
                    </button>
                    {order.paymentStatus === "paid" && !order.refundStatus && (
                      <button
                        onClick={() => setRefundOrderId(order.id)}
                        className="ml-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-blue-400 border border-blue-500/30 hover:bg-blue-500/10 transition-colors"
                      >
                        <RotateCcw size={11} />
                        Refund
                      </button>
                    )}
                    {order.paymentStatus === "failed" && (
                      <button
                        onClick={() => router.push("/checkout")}
                        className="ml-auto flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-[var(--accent)] border border-[var(--accent)]/30 hover:bg-[var(--accent)]/10 transition-colors"
                      >
                        <RefreshCw size={11} />
                        Retry
                      </button>
                    )}
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </AnimatePresence>
      </div>

      <AnimatePresence>
        {refundOrderId && (
          <RefundModal
            orderId={refundOrderId}
            onClose={() => setRefundOrderId(null)}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
