import { useMemo, useState } from "react";
import { useParams, useNavigate, Link } from "@tanstack/react-router";
import dayjs from "dayjs";
import { trpc } from "../trpc/client";
import { Button } from "@/components/ui/button";

const getStatusBadge = (status?: string) => {
  if (status === "delivered") {
    return "bg-emerald-50 text-emerald-700 border-emerald-200";
  }
  if (status === "cancelled") {
    return "bg-red-50 text-red-700 border-red-200";
  }
  return "bg-amber-50 text-amber-700 border-amber-200";
};

export function OrderDetailsRoute() {
  const { id } = useParams({ from: "/manage-orders/order-details/$id" });
  const navigate = useNavigate();
  const [incidentComment, setIncidentComment] = useState("");
  const [negativityScore, setNegativityScore] = useState("");

  const orderId = Number(id);
  const {
    data: orderData,
    isLoading,
    error,
  } = trpc.admin.order.getOrderDetails.useQuery(
    { orderId: Number.isFinite(orderId) ? orderId : 0 },
    { enabled: Number.isFinite(orderId) }
  );

  const order = orderData as any;

  const { data: incidentsData, refetch: refetchIncidents } =
    trpc.admin.user.getUserIncidents.useQuery(
      { userId: order?.userId ?? 0 },
      { enabled: Boolean(order?.userId) }
    );

  const addIncidentMutation = trpc.admin.user.addUserIncident.useMutation({
    onSuccess: () => {
      setIncidentComment("");
      setNegativityScore("");
      refetchIncidents();
    },
  });

  const subtotal = useMemo(() => {
    if (!order?.items?.length) return 0;
    return order.items.reduce((sum: number, item: any) => sum + item.amount, 0);
  }, [order]);

  if (isLoading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="rounded-2xl border border-slate-200 bg-white px-6 py-8 text-sm text-slate-600 shadow-sm">
          Loading order details...
        </div>
      </div>
    );
  }

  if (error || !order) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="rounded-2xl border border-red-200 bg-red-50 px-6 py-8 text-sm text-red-700 shadow-sm">
          {error?.message || "Failed to load order details"}
        </div>
      </div>
    );
  }

  const statusBadge = getStatusBadge(order.status);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-xs font-medium text-slate-500">Order Details</p>
          <h1 className="text-2xl font-semibold text-slate-900">#{order.readableId}</h1>
        </div>
        <Button
          variant="outline"
          onClick={() => navigate({ to: "/vendor-order-list" })}
        >
          Back to Orders
        </Button>
      </div>

      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-sm text-slate-500">Status</p>
            <div className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold uppercase ${statusBadge}`}>
              {order.status}
            </div>
          </div>
          <div className="text-sm text-slate-600">
            <p className="font-medium text-slate-700">Placed on</p>
            <p>{dayjs(order.createdAt).format("MMM DD, YYYY • h:mm A")}</p>
          </div>
          <div className="text-sm text-slate-600">
            <p className="font-medium text-slate-700">Delivery</p>
            <p>
              {order.isFlashDelivery
                ? dayjs(order.createdAt).add(30, "minutes").format("MMM DD, YYYY • h:mm A")
                : order.slotInfo?.time
                  ? dayjs(order.slotInfo.time).format("MMM DD, YYYY • h:mm A")
                  : "Not scheduled"}
            </p>
          </div>
        </div>
      </div>

      {order.status === "cancelled" && order.cancelReason && (
        <div className="rounded-2xl border border-red-200 bg-red-50 p-5 text-sm text-red-700">
          <p className="font-semibold">Cancellation Reason</p>
          <p className="mt-1 text-red-800">{order.cancelReason}</p>
        </div>
      )}

      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="text-lg font-semibold text-slate-900 mb-4">Customer Details</h2>
        <div className="grid gap-2 text-sm text-slate-600">
          {order.userId ? (
            <Link
              to="/user-management/$id"
              params={{ id: String(order.userId) }}
              className="font-semibold text-blue-700 hover:text-blue-800"
            >
              {order.customerName || "Unknown User"}
            </Link>
          ) : (
            <p className="font-medium text-slate-900">{order.customerName || "Unknown User"}</p>
          )}
          <p>{order.customerMobile}</p>
          {order.customerEmail && <p>{order.customerEmail}</p>}
          <p className="whitespace-pre-line">
            {order.address?.name} {order.address?.line1}
            {order.address?.line2 ? `, ${order.address.line2}` : ""}
            {`\n${order.address?.city}, ${order.address?.state} - ${order.address?.pincode}`}
          </p>
        </div>
      </div>

      {order.userId && (
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-6 shadow-sm">
          <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
            <h2 className="text-lg font-semibold text-amber-900">User Incidents</h2>
          </div>

          {incidentsData?.incidents?.length ? (
            <div className="space-y-3">
              {incidentsData.incidents.map((incident: any) => (
                <div key={incident.id} className="rounded-xl border border-amber-200 bg-white p-4">
                  <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
                    <span>{dayjs(incident.dateAdded).format("MMM DD, YYYY • h:mm A")}</span>
                    {incident.negativityScore ? (
                      <span className="rounded-md bg-red-100 px-2 py-1 text-red-700 font-semibold">
                        Score: {incident.negativityScore}
                      </span>
                    ) : null}
                  </div>
                  {incident.adminComment && (
                    <p className="mt-2 text-sm text-slate-800">{incident.adminComment}</p>
                  )}
                  <div className="mt-3 border-t border-slate-100 pt-2 text-xs text-slate-500">
                    Added by {incident.addedBy}
                    {incident.orderId ? ` • Order #${incident.orderId}` : ""}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="rounded-xl border border-amber-100 bg-white p-4 text-sm text-amber-800">
              No incidents recorded for this user
            </div>
          )}

          <div className="mt-6 rounded-xl border border-amber-100 bg-white p-4">
            <p className="text-sm font-semibold text-slate-900">Add Incident</p>
            <p className="text-xs text-slate-500 mt-1">
              Record an incident for this user. Higher negativity scores indicate more serious incidents.
            </p>
            <div className="mt-3 grid gap-3">
              <textarea
                value={incidentComment}
                onChange={(event) => setIncidentComment(event.target.value)}
                placeholder="Enter details about the incident..."
                className="min-h-[96px] w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-blue-400 focus:outline-none"
              />
              <input
                type="number"
                value={negativityScore}
                onChange={(event) => setNegativityScore(event.target.value)}
                placeholder="Negativity score (optional)"
                className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-blue-400 focus:outline-none"
              />
              <div className="flex justify-end">
                <Button
                  onClick={() => {
                    addIncidentMutation.mutate({
                      userId: order.userId,
                      orderId: order.id,
                      adminComment: incidentComment || undefined,
                      negativityScore: negativityScore ? Number(negativityScore) : undefined,
                    });
                  }}
                  disabled={addIncidentMutation.isPending}
                >
                  {addIncidentMutation.isPending ? "Adding..." : "Add Incident"}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h2 className="text-lg font-semibold text-slate-900 mb-4">Items Ordered</h2>
        <div className="space-y-3">
          {order.items?.map((item: any, index: number) => (
            <div
              key={`${item.id}-${index}`}
              className="flex items-center justify-between border-b border-slate-100 pb-3"
            >
              <div>
                <p className="text-sm font-semibold text-slate-900">{item.name}</p>
                <p className="text-xs text-slate-500">
                  {Number(item.quantity) * item.productSize} {item.unit} × ₹{item.price}
                </p>
              </div>
              <div className="text-sm font-semibold text-slate-900">₹{item.amount}</div>
            </div>
          ))}
        </div>

        <div className="mt-6 border-t border-slate-100 pt-4 text-sm text-slate-600">
          <div className="flex items-center justify-between">
            <span>Subtotal</span>
            <span className="font-semibold text-slate-900">₹{subtotal}</span>
          </div>
          {order.discountAmount > 0 && (
            <div className="flex items-center justify-between mt-2 text-emerald-600">
              <span>Discount</span>
              <span className="font-semibold">-₹{order.discountAmount}</span>
            </div>
          )}
          {order.deliveryCharge > 0 && (
            <div className="flex items-center justify-between mt-2">
              <span>Delivery Charge</span>
              <span className="font-semibold text-slate-900">₹{order.deliveryCharge}</span>
            </div>
          )}
          <div className="flex items-center justify-between mt-4 text-base font-semibold text-slate-900">
            <span>Total Amount</span>
            <span>₹{order.totalAmount}</span>
          </div>
        </div>
      </div>

      {order.adminNotes && (
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900">
          <p className="font-semibold">Admin Notes</p>
          <p className="mt-1">{order.adminNotes}</p>
        </div>
      )}

      {order.couponCode && (
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-5">
          <p className="text-sm font-semibold text-emerald-800">Coupon Applied</p>
          <p className="mt-1 text-sm text-emerald-700">{order.couponCode}</p>
          {order.couponDescription && (
            <p className="mt-1 text-xs text-emerald-600">{order.couponDescription}</p>
          )}
          <p className="mt-2 text-sm font-semibold text-emerald-800">-₹{order.discountAmount}</p>
        </div>
      )}
    </div>
  );
}
