"use client";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  Download,
  CheckCircle,
  XCircle,
  Clock,
  Shield,
  ArrowLeft,
  Copy,
  Check,
} from "lucide-react";
import { useState } from "react";
import { usePayment } from "@/lib/PaymentContext";
import { StatusBadge } from "./StatusBadge";
import { formatDate } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";

function Row({ label, value, accent }: { label: string; value: string; accent?: boolean }) {
  return (
    <div className="flex items-start justify-between py-3 border-b border-[var(--border)] last:border-0 gap-4">
      <span className="text-xs text-[var(--text-muted)] shrink-0">{label}</span>
      <span className={`text-xs font-medium text-right ${accent ? "text-[var(--accent)] font-bold text-sm" : "text-[var(--text-primary)]"}`}>
        {value}
      </span>
    </div>
  );
}

export function ReceiptPage() {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const params = useParams<{ id: string }>();
  const { orders } = usePayment();
  const [copied, setCopied] = useState(false);

  const order = orders.find((o) => o.id === params.id);

  const copyTxId = () => {
    if (order?.transactionId) {
      navigator.clipboard.writeText(order.transactionId).catch(() => {});
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  if (!order) {
    return (
      <div className="min-h-full flex flex-col items-center justify-center gap-4 px-4 py-12" style={{ background: "var(--bg)" }}>
        <XCircle size={48} className="text-red-400 opacity-60" />
        <h2 className="text-lg font-bold text-[var(--text-primary)]">Receipt Not Found</h2>
        <p className="text-sm text-[var(--text-muted)]">The order ID you provided doesn't match any records.</p>
        <button
          onClick={() => router.push("/profile/payments")}
          className="px-5 py-2.5 rounded-xl text-sm font-semibold text-white"
          style={{ background: "var(--accent)" }}
        >
          Payment History
        </button>
      </div>
    );
  }

  const isPaid = order.paymentStatus === "paid";
  const isRefunded = order.paymentStatus === "refunded";

  return (
    <div className="min-h-full pb-20" style={{ background: "var(--bg)" }}>
      <div className="max-w-6xl mx-auto px-4 py-6">
        {/* Back */}
        <button
          onClick={() => router.back()}
          className="flex items-center gap-2 text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)] mb-5 transition-colors"
        >
          <ArrowLeft size={15} />
          Back
        </button>

        {/* Receipt card */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="rounded-3xl overflow-hidden border border-[var(--border)]"
          style={{ background: "var(--card)" }}
        >
          {/* Header band */}
          <div
            className="px-6 py-6 text-center"
            style={{
              background: isPaid
                ? "linear-gradient(135deg, rgba(34,197,94,0.15) 0%, rgba(34,197,94,0.05) 100%)"
                : isRefunded
                ? "linear-gradient(135deg, rgba(96,165,250,0.15) 0%, rgba(96,165,250,0.05) 100%)"
                : "linear-gradient(135deg, rgba(248,113,113,0.15) 0%, rgba(248,113,113,0.05) 100%)",
            }}
          >
            {/* Logo area */}
            <div className="flex items-center justify-center gap-2 mb-4">
              <div
                className="w-8 h-8 rounded-xl flex items-center justify-center font-black text-white text-xs"
                style={{ background: "var(--accent)" }}
              >
                D
              </div>
              <span className="font-black text-[var(--text-primary)]">Doliplay</span>
            </div>

            <div className="flex justify-center mb-3">
              {isPaid ? (
                <CheckCircle size={40} className="text-green-400" />
              ) : isRefunded ? (
                <Clock size={40} className="text-blue-400" />
              ) : (
                <XCircle size={40} className="text-red-400" />
              )}
            </div>

            <p className="text-lg font-black text-[var(--text-primary)] mb-1">
              {isPaid ? "Payment Receipt" : isRefunded ? "Refund Receipt" : "Payment Failed"}
            </p>
            <p className="text-3xl font-black" style={{ color: "var(--accent)" }}>
              {formatPrice(order.totalAmount)}
            </p>
            <div className="mt-2">
              <StatusBadge status={order.paymentStatus} />
            </div>
          </div>

          {/* Dashed separator (receipt style) */}
          <div className="relative py-2 px-4">
            <div className="border-t-2 border-dashed border-[var(--border)]" />
            <div
              className="absolute -left-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full"
              style={{ background: "var(--bg)" }}
            />
            <div
              className="absolute -right-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full"
              style={{ background: "var(--bg)" }}
            />
          </div>

          {/* Order details */}
          <div className="px-6 pb-2">
            <p className="text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)] mb-1">Order Details</p>
          </div>
          <div className="px-6">
            {/* Product */}
            <div className="flex items-center gap-3 py-3 border-b border-[var(--border)]">
              <img
                src={order.listingImage}
                alt={order.listingTitle}
                className="w-12 h-12 rounded-xl object-cover shrink-0"
              />
              <div className="flex-1 min-w-0">
                <p className="text-xs font-semibold text-[var(--text-primary)] line-clamp-2">{order.listingTitle}</p>
                <p className="text-[10px] text-[var(--text-muted)] mt-0.5">Qty: {order.quantity} · {order.listingCondition}</p>
              </div>
            </div>

            <Row label="Order ID" value={order.id.toUpperCase()} />
            {order.transactionId && (
              <div className="flex items-center justify-between py-3 border-b border-[var(--border)]">
                <span className="text-xs text-[var(--text-muted)]">Transaction ID</span>
                <div className="flex items-center gap-2">
                  <span className="text-xs font-mono text-[var(--text-primary)]">{order.transactionId}</span>
                  <button onClick={copyTxId}>
                    {copied ? <Check size={11} className="text-green-400" /> : <Copy size={11} className="text-[var(--text-muted)]" />}
                  </button>
                </div>
              </div>
            )}
            <Row label="Payment Method" value={order.paymentMethod === "paypal" ? "PayPal" : "Cash on Delivery"} />
            <Row label="Date" value={formatDate(order.createdAt)} />
          </div>

          {/* Dashed separator */}
          <div className="relative py-2 px-4">
            <div className="border-t-2 border-dashed border-[var(--border)]" />
            <div className="absolute -left-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full" style={{ background: "var(--bg)" }} />
            <div className="absolute -right-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full" style={{ background: "var(--bg)" }} />
          </div>

          {/* Price breakdown */}
          <div className="px-6 pb-2">
            <p className="text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)] mb-1">Price Breakdown</p>
          </div>
          <div className="px-6 pb-4">
            <Row label="Item Price" value={formatPrice(order.listingPrice)} />
            <Row label="Service Fee" value={formatPrice(order.serviceFee)} />
            <Row label="Tax (GST)" value={formatPrice(order.tax)} />
            {order.deliveryFee > 0 && <Row label="Delivery" value={formatPrice(order.deliveryFee)} />}
            {order.discount > 0 && <Row label="Discount" value={`-${formatPrice(order.discount)}`} />}
            <Row label="Total Paid" value={formatPrice(order.totalAmount)} accent />
          </div>

          {/* Parties */}
          <div className="relative py-2 px-4">
            <div className="border-t-2 border-dashed border-[var(--border)]" />
            <div className="absolute -left-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full" style={{ background: "var(--bg)" }} />
            <div className="absolute -right-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full" style={{ background: "var(--bg)" }} />
          </div>
          <div className="px-6 pb-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)] mb-2">Buyer</p>
                <p className="text-xs font-semibold text-[var(--text-primary)]">{order.buyerInfo.name}</p>
                <p className="text-[10px] text-[var(--text-muted)]">{order.buyerInfo.email}</p>
                <p className="text-[10px] text-[var(--text-muted)]">{order.buyerInfo.city}</p>
              </div>
              <div>
                <p className="text-[10px] uppercase tracking-wider font-semibold text-[var(--text-muted)] mb-2">Seller</p>
                <p className="text-xs font-semibold text-[var(--text-primary)]">{order.sellerName}</p>
                <p className="text-[10px] text-[var(--text-muted)]">Doliplay Verified</p>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div
            className="px-6 py-4 text-center"
            style={{ background: "rgba(255,255,255,0.02)", borderTop: "1px solid var(--border)" }}
          >
            <div className="flex items-center justify-center gap-2 mb-1">
              <Shield size={12} className="text-green-400" />
              <span className="text-[10px] text-green-400 font-medium">Protected by Doliplay Buyer Guarantee</span>
            </div>
            <p className="text-[9px] text-[var(--text-muted)]">
              For disputes, contact support within 14 days of purchase.
            </p>
          </div>
        </motion.div>

        {/* Actions */}
        <div className="mt-5 space-y-3">
          <button
            className="w-full py-3.5 rounded-xl text-white font-semibold text-sm flex items-center justify-center gap-2"
            style={{ background: "var(--accent)" }}
          >
            <Download size={15} />
            Download PDF Receipt
          </button>
          <button
            onClick={() => router.push("/profile/payments")}
            className="w-full py-3 rounded-xl text-sm font-medium flex items-center justify-center gap-2 border border-[var(--border)] text-[var(--text-muted)]"
            style={{ background: "var(--card)" }}
          >
            View All Payments
          </button>
        </div>
      </div>
    </div>
  );
}
