"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { usePublicSession } from "@/components/shop/public-session-context";
import { useAuthModal } from "@/components/shop/auth-modal-context";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { resolvePublicMediaUrl } from "@/lib/public-product";
import { formatShippingLines } from "@/lib/shipping-countries";
import { toast } from "sonner";

type OrderDetail = {
  _id: string;
  orderNumber: string;
  status: string;
  paymentMethod?: string;
  paymentStatus?: string;
  paymentReference?: string;
  paymentProofUrl?: string;
  trackingNumber?: string;
  trackingNote?: string;
  subtotal: number;
  shippingTotal: number;
  discountTotal?: number;
  specialDiscount?: number;
  additionalCost?: number;
  adjustmentNote?: string;
  grandTotal: number;
  couponCode?: string;
  shippingFullName?: string;
  shippingPhone?: string;
  shippingEmail?: string;
  shippingAddress?: string;
  shippingCity?: string;
  shippingZip?: string;
  shippingCountry?: string;
  shippingCountryCode?: string;
  createdAt?: string;
  items?: {
    title: string;
    image?: string;
    variantLabel?: string;
    quantity: number;
    unitPrice: number;
    lineSubtotal: number;
    lineShipping?: number;
  }[];
};

const STATUS_STEPS = ["pending", "processing", "shipped", "delivered"] as const;

export default function AccountOrderDetailPage() {
  const params = useParams();
  const orderId = params.id as string;
  const { isAuthenticated, loading } = usePublicSession();
  const { openAuthModal } = useAuthModal();
  const [order, setOrder] = useState<OrderDetail | null>(null);
  const [busy, setBusy] = useState(false);
  const [actionBusy, setActionBusy] = useState(false);
  const [paymentReference, setPaymentReference] = useState("");
  const [proofFile, setProofFile] = useState<File | null>(null);

  const load = useCallback(async () => {
    if (!isAuthenticated || !orderId) return;
    setBusy(true);
    try {
      const res = await DataService.get(`/user/shop/orders/${orderId}`);
      setOrder(res.data?.data || null);
    } catch {
      setOrder(null);
    } finally {
      setBusy(false);
    }
  }, [isAuthenticated, orderId]);

  useEffect(() => {
    if (!loading && isAuthenticated) load();
  }, [loading, isAuthenticated, load]);

  const cancelOrder = async () => {
    if (!order || !confirm("Cancel this order?")) return;
    setActionBusy(true);
    try {
      await DataService.post(`/user/shop/orders/${order._id}/cancel`);
      toast.success("Order cancelled");
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not cancel"));
    } finally {
      setActionBusy(false);
    }
  };

  const submitProof = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!order) return;
    if (!paymentReference.trim() && !proofFile) {
      toast.error("Add a reference and/or proof image");
      return;
    }
    setActionBusy(true);
    try {
      const fd = new FormData();
      if (paymentReference.trim()) fd.append("paymentReference", paymentReference.trim());
      if (proofFile) fd.append("proof", proofFile);
      await DataService.post(`/user/shop/orders/${order._id}/payment-proof`, fd);
      toast.success("Payment info submitted");
      setProofFile(null);
      load();
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not submit"));
    } finally {
      setActionBusy(false);
    }
  };

  if (loading || busy) return <p className="text-gray-500">Loading…</p>;

  if (!isAuthenticated) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Order</h1>
        <p className="mt-4 text-gray-600">Sign in to view this order.</p>
        <Button className="mt-4" type="button" onClick={() => openAuthModal("login")}>
          Log in
        </Button>
      </div>
    );
  }

  if (!order) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Order not found</h1>
        <Button asChild className="mt-4" variant="outline">
          <Link href="/account/orders">Back to orders</Link>
        </Button>
      </div>
    );
  }

  const canCancel =
    ["pending", "processing"].includes(order.status) && order.paymentStatus !== "paid";
  const showBankForm =
    order.paymentMethod === "bank_transfer" &&
    !["paid", "refunded"].includes(order.paymentStatus || "") &&
    order.status !== "cancelled";

  const stepIndex =
    order.status === "cancelled"
      ? -1
      : Math.max(0, STATUS_STEPS.indexOf(order.status as (typeof STATUS_STEPS)[number]));

  return (
    <div>
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <p className="text-sm text-gray-500">
            <Link href="/account/orders" className="hover:text-primary">
              Orders
            </Link>{" "}
            / {order.orderNumber}
          </p>
          <h1 className="mt-1 text-2xl font-bold text-slate-900">{order.orderNumber}</h1>
          <p className="text-sm text-gray-600">
            {order.createdAt ? new Date(order.createdAt).toLocaleString() : ""}
          </p>
        </div>
        {canCancel ? (
          <Button type="button" variant="outline" disabled={actionBusy} onClick={cancelOrder}>
            Cancel order
          </Button>
        ) : null}
      </div>

      <div className="mt-6 rounded-lg border bg-white p-4">
        <p className="text-sm font-semibold text-slate-900">Status</p>
        {order.status === "cancelled" ? (
          <p className="mt-2 capitalize text-red-600">Cancelled</p>
        ) : (
          <ol className="mt-3 flex flex-wrap gap-2">
            {STATUS_STEPS.map((s, i) => (
              <li
                key={s}
                className={`rounded-full px-3 py-1 text-xs font-medium capitalize ${
                  i <= stepIndex ? "bg-primary text-primary-foreground" : "bg-gray-100 text-gray-500"
                }`}
              >
                {s}
              </li>
            ))}
          </ol>
        )}
        {(order.trackingNumber || order.trackingNote) && (
          <div className="mt-3 text-sm text-gray-700">
            {order.trackingNumber ? <p>Tracking: {order.trackingNumber}</p> : null}
            {order.trackingNote ? <p>{order.trackingNote}</p> : null}
          </div>
        )}
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <div className="rounded-lg border bg-white p-4">
          <p className="font-semibold text-slate-900">Items</p>
          <ul className="mt-3 space-y-3">
            {(order.items || []).map((it, i) => {
              const img = resolvePublicMediaUrl(it.image || "");
              return (
                <li key={i} className="flex gap-3 text-sm">
                  <div className="h-12 w-12 shrink-0 overflow-hidden rounded bg-gray-100">
                    {img ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={img} alt="" className="h-full w-full object-cover" />
                    ) : null}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="font-medium text-slate-900">{it.title}</p>
                    {it.variantLabel ? <p className="text-xs text-gray-500">{it.variantLabel}</p> : null}
                    <p className="text-xs text-gray-600">Qty {it.quantity}</p>
                  </div>
                  <p className="font-medium">{Number(it.lineSubtotal).toFixed(2)}</p>
                </li>
              );
            })}
          </ul>
          <div className="mt-4 space-y-1 border-t pt-3 text-sm">
            <div className="flex justify-between">
              <span>Subtotal</span>
              <span>{Number(order.subtotal).toFixed(2)}</span>
            </div>
            {(order.discountTotal || 0) > 0 ? (
              <div className="flex justify-between text-green-700">
                <span>Discount{order.couponCode ? ` (${order.couponCode})` : ""}</span>
                <span>-{Number(order.discountTotal).toFixed(2)}</span>
              </div>
            ) : null}
            {(order.specialDiscount || 0) > 0 ? (
              <div className="flex justify-between text-green-700">
                <span>Special discount</span>
                <span>-{Number(order.specialDiscount).toFixed(2)}</span>
              </div>
            ) : null}
            <div className="flex justify-between">
              <span>Shipping</span>
              <span>{Number(order.shippingTotal).toFixed(2)}</span>
            </div>
            {(order.additionalCost || 0) > 0 ? (
              <div className="flex justify-between">
                <span>Additional cost</span>
                <span>{Number(order.additionalCost).toFixed(2)}</span>
              </div>
            ) : null}
            <div className="flex justify-between font-bold">
              <span>Total</span>
              <span>{Number(order.grandTotal).toFixed(2)}</span>
            </div>
            {order.adjustmentNote ? (
              <p className="pt-1 text-xs text-gray-500">{order.adjustmentNote}</p>
            ) : null}
          </div>
        </div>

        <div className="space-y-4">
          <div className="rounded-lg border bg-white p-4 text-sm">
            <p className="font-semibold text-slate-900">Shipping</p>
            <p className="mt-2">{order.shippingFullName}</p>
            <p>{order.shippingPhone}</p>
            <p>{order.shippingEmail}</p>
            <p className="mt-1 whitespace-pre-wrap">
              {formatShippingLines({
                address: order.shippingAddress,
                city: order.shippingCity,
                zip: order.shippingZip,
                country: order.shippingCountry,
                countryCode: order.shippingCountryCode,
              })}
            </p>
          </div>

          <div className="rounded-lg border bg-white p-4 text-sm">
            <p className="font-semibold text-slate-900">Payment</p>
            <p className="mt-2 capitalize">
              {order.paymentMethod === "bank_transfer" ? "Bank transfer" : "Cash on delivery"} ·{" "}
              {(order.paymentStatus || "unpaid").replace(/_/g, " ")}
            </p>
            {order.paymentReference ? <p className="mt-1">Reference: {order.paymentReference}</p> : null}
            {order.paymentProofUrl ? (
              <a
                href={resolvePublicMediaUrl(order.paymentProofUrl) || order.paymentProofUrl}
                target="_blank"
                rel="noreferrer"
                className="mt-2 inline-block text-primary hover:underline"
              >
                View payment proof
              </a>
            ) : null}
          </div>

          {showBankForm ? (
            <form onSubmit={submitProof} className="space-y-3 rounded-lg border bg-white p-4">
              <p className="font-semibold text-slate-900">Submit bank payment info</p>
              <div className="grid gap-2">
                <Label htmlFor="ref">Transfer reference</Label>
                <Input
                  id="ref"
                  value={paymentReference}
                  onChange={(e) => setPaymentReference(e.target.value)}
                  placeholder={order.paymentReference || "Transaction ID"}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="proof">Proof image</Label>
                <Input
                  id="proof"
                  type="file"
                  accept="image/*"
                  onChange={(e) => setProofFile(e.target.files?.[0] || null)}
                />
              </div>
              <Button type="submit" disabled={actionBusy}>
                {actionBusy ? "Submitting…" : "Submit for confirmation"}
              </Button>
            </form>
          ) : null}

          {order.status === "delivered" ? (
            <Button asChild variant="outline">
              <Link href={`/account/returns?orderId=${order._id}`}>Request return / refund</Link>
            </Button>
          ) : null}
        </div>
      </div>
    </div>
  );
}
