"use client";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import OrderVisionBoardCapture from "../order/OrderVisionBoardCapture";
import { FormButton } from "@/app/components/form/forms";
import { getApiClient } from "@/utils/apiClient";
import DialogModal from "@/app/components/common/DialogModal";
import PageTransitionLoader from "@/app/components/PageTransitionLoader";
import { toast } from "react-toastify";
import CustomDropdown from "@/app/components/form/CustomDropdown";
import withAuth from "@/app/hook/withAuth";

type ModalKey = string | null;

function SummaryRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex w-full flex-row justify-between gap-2 border-b-1 border-dashed bg-gray-100/50 px-5 py-3 text-xs capitalize transition-all duration-300 last:border-0 last:bg-gray-950/25 hover:bg-gray-100 md:text-sm">
      <span className="">{label}</span>
      <span className="font-medium">${value}</span>
    </div>
  );
}

const STATUS_OPTIONS = [
  { label: "All", value: "all" },
  { label: "Draft", value: "DRAFT" },
  { label: "Awaiting Response", value: "AWAITING_RESPONSE" },
  { label: "Accepted", value: "ACCEPTED" },
  { label: "Declined", value: "DECLINED" },
  { label: "Order Initiated", value: "ORDERED" },
];

const STATUS_PILL: Record<string, { label: string; className: string }> = {
  DRAFT: { label: "Draft", className: "bg-gray-100 text-gray-600" },
  AWAITING_RESPONSE: {
    label: "Awaiting Response",
    className: "bg-amber-100 text-amber-700",
  },
  ACCEPTED: { label: "Accepted", className: "bg-green-100 text-green-700" },
  DECLINED: { label: "Declined", className: "bg-red-100 text-red-700" },
  ORDERED: { label: "Order Initiated", className: "bg-blue-100 text-blue-700" },
};

function getStatusDescription(product: any): string {
  switch (product.status) {
    case "DRAFT":
      return "Draft (incomplete vision)";
    case "AWAITING_RESPONSE":
      if (product.is_owner) {
        const name = product.shared_with_name || "";
        const email = product.shared_with_email
          ? `(${product.shared_with_email})`
          : "";
        return `Sent to ${name} ${email}`.trim();
      }
      return `Shared with you by ${product.sender_name || product.sender_email || ""}`.trim();
    case "ACCEPTED":
      if (product.is_owner) {
        const name = product.shared_with_name || "";
        const email = product.shared_with_email
          ? `(${product.shared_with_email})`
          : "";
        return `Accepted by ${name} ${email}`.trim();
      }
      return `Accepted — shared by ${product.sender_name || product.sender_email || ""}`.trim();
    case "DECLINED":
      if (product.is_owner || product.shared_with_name || product.shared_with_email) {
        const name = product.shared_with_name || "";
        const email = product.shared_with_email
          ? `(${product.shared_with_email})`
          : "";
        return `Declined by ${name} ${email}`.trim();
      }
      return `Declined — shared by ${product.sender_name || product.sender_email || ""}`.trim();
    case "ORDERED":
      if (product.is_owner || product.shared_with_name || product.shared_with_email) {
        const name = product.shared_with_name || "";
        const email = product.shared_with_email
          ? `(${product.shared_with_email})`
          : "";
        return `Order Initiated by ${name} ${email}`.trim();
      }
      return "Order Initiated";
    default:
      return product.status || "";
  }
}

function OrderClients() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [openModal, setOpenModal] = useState<ModalKey>(null);
  const [orders, setOrders] = useState<any[]>([]);
  const [selectedStatus, setSelectedStatus] = useState<string>("all");
  const [isLoading, setIsLoading] = useState(true);
  const [inviteEmail, setInviteEmail] = useState("");
  const [customer_name, setCustomerName] = useState("");
  const [isInviting, setIsInviting] = useState(false);
  const [declineOrderId, setDeclineOrderId] = useState<string | null>(null);
  const [declineReason, setDeclineReason] = useState("");
  const [isDeclining, setIsDeclining] = useState(false);
  const [highlightedId, setHighlightedId] = useState<string | null>(null);
  const [justAccepted, setJustAccepted] = useState<Set<string>>(new Set());

  const cardRefs = useRef<Record<string, HTMLDivElement | null>>({});

  useEffect(() => {
    const inviteId = searchParams.get("invite");
    if (inviteId) setHighlightedId(inviteId);
    getUserOrderList();
  }, []);

  useEffect(() => {
    if (highlightedId && orders.length > 0) {
      const el = cardRefs.current[highlightedId];
      if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [orders, highlightedId]);

  async function getUserOrderList() {
    try {
      setIsLoading(true);
      const response = await fetch("/api/vision/list", {
        method: "GET",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
      });
      if (!response.ok)
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      const data = await response.json();
      setOrders(data.data.my_vision);
    } catch {
      // silently fail
    } finally {
      setIsLoading(false);
    }
  }

  const filteredOrders = orders.filter((order) => {
    if (selectedStatus === "all") return true;
    return order.status === selectedStatus;
  });

  const closeAllModals = () => setOpenModal(null);

  const openSpecificModal = (modalKey: ModalKey) => {
    closeAllModals();
    setTimeout(() => setOpenModal(modalKey), 50);
  };

  const handleAccept = async (orderId: string) => {
    if (!window.confirm("Are you sure you want to accept this vision board invitation?"))
      return;
    try {
      const response = await fetch("/api/vision/invite-action", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ order_id: orderId, action: "accept" }),
      });
      if (!response.ok)
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      setOrders((prev) =>
        prev.map((o) =>
          o.order_id === orderId
            ? { ...o, status: "ACCEPTED", is_add_to_bag_allow: true }
            : o,
        ),
      );
      setJustAccepted((prev) => new Set(prev).add(orderId));
      toast.success("Invite accepted successfully!");
    } catch {
      toast.error("Failed to accept invite. Please try again.");
    }
  };

  const handleDeclineSubmit = async () => {
    if (!declineOrderId) return;
    setIsDeclining(true);
    try {
      const response = await fetch("/api/vision/invite-action", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          order_id: declineOrderId,
          action: "reject",
          reason: declineReason,
        }),
      });
      if (!response.ok)
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      setOrders((prev) =>
        prev.map((o) =>
          o.order_id === declineOrderId ? { ...o, status: "DECLINED", decline_reason: declineReason } : o,
        ),
      );
      toast.success("Invite declined.");
      setDeclineOrderId(null);
      setDeclineReason("");
    } catch {
      toast.error("Failed to decline invite. Please try again.");
    } finally {
      setIsDeclining(false);
    }
  };

  const handleDelete = async (co_creation_invoice_id: string) => {
    if (
      !window.confirm(
        "Are you sure you want to delete this vision board invitation?",
      )
    )
      return;
    try {
      await getApiClient(`co-creation/del/${co_creation_invoice_id}`);
      toast.success("Vision board deleted successfully!");
      getUserOrderList();
    } catch {
      toast.error("Failed to delete vision board. Please try again.");
    }
  };

  const handleInviteSubmit = async (sessionId: string) => {
    if (!inviteEmail || !inviteEmail.includes("@")) {
      alert("Please enter a valid email address");
      return;
    }
    try {
      setIsInviting(true);
      const response = await fetch("/api/vision/invite-submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          email: inviteEmail,
          session_id: sessionId,
          customer_name,
        }),
      });
      if (!response.ok)
        throw new Error(`Error: ${response.status} - ${response.statusText}`);
      // Update card status inline — no full list refresh
      setOrders((prev) =>
        prev.map((o) =>
          o.session_id === sessionId
            ? {
                ...o,
                status: "AWAITING_RESPONSE",
                vision_share_allow: false,
                shared_with_name: customer_name,
                shared_with_email: inviteEmail,
              }
            : o,
        ),
      );
      setInviteEmail("");
      setCustomerName("");
      closeAllModals();
      toast.success("Vision board shared successfully!");
    } catch {
      toast.error("Failed to send invitation. Please try again.");
    } finally {
      setIsInviting(false);
    }
  };

  return (
    <div className="flex w-full flex-1 flex-col gap-4">
      <PageTransitionLoader isLoading={isLoading} />

      {/* Decline modal */}
      <DialogModal
        name="decline-reason"
        isOpen={declineOrderId !== null}
        onClose={() => {
          setDeclineOrderId(null);
          setDeclineReason("");
        }}
        size="md"
        title="Decline Vision"
        subtitle=""
        showFooter={false}
      >
        <div className="flex flex-col gap-4 p-4">
          <p className="text-sm text-gray-600">
            Let the sender know why you&apos;re declining (optional).
          </p>
          <textarea
            rows={4}
            placeholder="Reason for declining..."
            value={declineReason}
            onChange={(e) => setDeclineReason(e.target.value)}
            className="w-full border border-gray-300 p-3 text-sm"
          />
          <div className="flex gap-3">
            <button
              type="button"
              className="btn-outline flex-1"
              onClick={handleDeclineSubmit}
              disabled={isDeclining}
            >
              {isDeclining ? "Declining..." : "Confirm Decline"}
            </button>
            <button
              type="button"
              className="btn-link"
              onClick={() => {
                setDeclineOrderId(null);
                setDeclineReason("");
              }}
            >
              Cancel
            </button>
          </div>
        </div>
      </DialogModal>

      <div className="flex w-full flex-col">
        <div className="flex flex-col">
          <div className="flex w-full flex-col gap-1">
            <h1 className="med">Vision Board</h1>
            <p className="text-xs">
              Manage your vision boards: track progress, review updates, accept
              or decline invitations, share with collaborators, and move designs
              to production when ready.
            </p>
          </div>

          <div className="mt-5 flex w-full flex-col justify-between gap-5 align-top">
            <div className="flex w-full flex-col justify-between align-top">
              <div className="relative z-20 flex w-full md:w-[30%]">
                <CustomDropdown
                  key={selectedStatus}
                  label="Filter by Status"
                  placeholder="Filter by Status"
                  options={STATUS_OPTIONS}
                  defaultValue={selectedStatus}
                  onSelect={(value) => setSelectedStatus(value as string)}
                />
              </div>

              <div className="relative flex w-full flex-col">
                <div className="relative z-10 grid grid-cols-1 gap-4 pt-4">
                  {filteredOrders && filteredOrders.length > 0 ? (
                    filteredOrders.map((product: any) => {
                      const isRecipient =
                        product.item_order_type === "INVITE_VISION" &&
                        !product.is_owner;
                      const isHighlighted =
                        highlightedId === product.order_id;
                      const isJustAccepted = justAccepted.has(product.order_id);
                      const pill = STATUS_PILL[product.status];
                      const canActOnInvite =
                        isRecipient &&
                        product.status === "AWAITING_RESPONSE";

                      return (
                        <div
                          key={product.order_id}
                          ref={(el) => {
                            cardRefs.current[product.order_id] = el;
                          }}
                        >
                          <div
                            className={`flex w-full flex-col border-1 border-dashed bg-white py-5 duration-300 ${
                              isHighlighted
                                ? "border-gray-950 ring-2 ring-gray-950/20"
                                : "border-transparent hover:border-gray-950"
                            }`}
                          >
                            {/* Accepted confirmation banner */}
                            {isJustAccepted && (
                              <div className="mb-3 flex items-center gap-2 bg-green-50 px-5 py-3 text-sm text-green-700">
                                <span className="font-medium">
                                  Vision accepted!
                                </span>{" "}
                                You can now add it to your bag below.
                              </div>
                            )}

                            <div className="flex flex-col justify-between border-b-1 border-gray-950/25 px-5 pb-2 align-middle md:flex-row">
                              <div className="flex w-full items-center justify-between gap-4">
                                <div className="flex flex-col">
                                  <div className="flex flex-col text-lg">
                                    <div className="flex items-center gap-3">
                                      <span className="font-bogart">
                                        {product.product_name}
                                      </span>
                                      {pill && (
                                        <span
                                          className={`rounded px-2 py-0.5 text-xs font-medium ${pill.className}`}
                                        >
                                          {pill.label}
                                        </span>
                                      )}
                                      {canActOnInvite && (
                                        <span className="rounded bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-700">
                                          Action Required
                                        </span>
                                      )}
                                    </div>
                                    <div className="mt-0.5 text-xs text-gray-500">
                                      {getStatusDescription(product)}
                                    </div>
                                    {product.status === "DECLINED" && product.decline_reason && (
                                      <div className="mt-1 text-xs text-red-600">
                                        Reason: {product.decline_reason}
                                      </div>
                                    )}
                                  </div>

                                  <div className="mt-2 flex flex-wrap items-center gap-4 text-xs">
                                    <div className="flex items-center gap-2">
                                      Created:
                                      <span className="font-medium">
                                        {product.created_at}
                                      </span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                      Last updated:
                                      <span className="font-medium">
                                        {product.updated_at}
                                      </span>
                                    </div>
                                  </div>
                                </div>
                              </div>

                              <div className="flex w-1/2 flex-row items-center justify-end gap-4">
                                {product.is_edit_allow === true && (
                                  <Link
                                    href={`/morni-guidance?group=base_canvas&step=define_vibe&external=${product.order_id}&vbshow=true`}
                                    className="btn-outline"
                                  >
                                    Edit this
                                  </Link>
                                )}
                                {product.is_delete_allow === true && (
                                  <button
                                    type="button"
                                    className="btn-link"
                                    onClick={() =>
                                      handleDelete(product.order_id)
                                    }
                                  >
                                    Delete
                                  </button>
                                )}

                                {/* Accept / Decline for recipients */}
                                {canActOnInvite && (
                                  <div className="flex gap-4">
                                    <button
                                      type="button"
                                      className="btn-outline"
                                      onClick={() =>
                                        handleAccept(product.order_id)
                                      }
                                    >
                                      Accept
                                    </button>
                                    <button
                                      type="button"
                                      className="btn-link"
                                      onClick={() =>
                                        setDeclineOrderId(product.order_id)
                                      }
                                    >
                                      Decline
                                    </button>
                                  </div>
                                )}

                                {product.is_re_creation_allow === true && (
                                  <div className="font-medium">
                                    <button
                                      className="btn-link"
                                      onClick={async () => {
                                        if (
                                          !window.confirm(
                                            "Are you sure you want to re-create this item?",
                                          )
                                        )
                                          return;
                                        try {
                                          const response = await fetch(
                                            `/api/vision/replicate/${product.order_id}`,
                                            {
                                              method: "POST",
                                              headers: {
                                                "Content-Type":
                                                  "application/json",
                                              },
                                              credentials: "include",
                                            },
                                          );
                                          if (!response.ok)
                                            throw new Error(
                                              "Failed to re-create the item.",
                                            );
                                          const data = await response.json();
                                          toast.success(
                                            "Item re-created successfully!",
                                          );
                                          window.location.href = data.data.url;
                                        } catch {
                                          alert(
                                            "Failed to re-create the item. Please try again.",
                                          );
                                        }
                                      }}
                                    >
                                      Re-Create
                                    </button>
                                  </div>
                                )}
                              </div>
                            </div>

                            <div className="grid grid-cols-1 items-start gap-8 p-2 align-top md:grid-cols-7 md:p-8">
                              <div className="col-span-1 md:col-span-4">
                                {product.vision_board_summary != null ? (
                                  <OrderVisionBoardCapture
                                    vision_board_summary={
                                      product.vision_board_summary
                                    }
                                    order_id={product.order_id}
                                  />
                                ) : null}
                              </div>

                              <div className="col-span-1 md:col-span-3">
                                <div className="flex w-full flex-col justify-between gap-2">
                                  <div className="mx-auto flex w-full flex-col items-center justify-between gap-4 text-xs font-light">
                                    <p className="font-light">
                                      Please proceed to pay an initiation fee of{" "}
                                      <span className="font-medium text-blue-600">
                                        $
                                        {
                                          product?.payment_calculation
                                            ?.initiation_price
                                        }
                                      </span>{" "}
                                      to begin the co-creation process. This fee
                                      will be used to procure raw materials and
                                      finalize your design.
                                    </p>
                                    <p className="font-light">
                                      We will contact you shortly after the
                                      payment is processed
                                    </p>
                                  </div>

                                  <div>
                                    <div className="mt-8 flex w-full flex-col">
                                      <div className="flex flex-col gap-2 text-xs">
                                        <div className="mx-auto flex w-full flex-col border-1 border-dashed border-gray-950/50">
                                          {product?.payment_calculation
                                            ?.type === "suits" ? (
                                            <>
                                              <SummaryRow
                                                label="base cost: Suit Jackets"
                                                value={`${product?.payment_calculation?.pricing_calculation?.silhouette_outerwear || 0}`}
                                              />
                                              <SummaryRow
                                                label="base cost: Bottom"
                                                value={`${product?.payment_calculation?.pricing_calculation?.silhouette_bottom || 0}`}
                                              />
                                              {product?.payment_calculation
                                                ?.pricing_calculation
                                                .silhouette_vest > 0 && (
                                                <SummaryRow
                                                  label="base cost: Vest"
                                                  value={`${product?.payment_calculation?.pricing_calculation?.silhouette_vest || 0}`}
                                                />
                                              )}
                                            </>
                                          ) : product?.payment_calculation
                                              ?.type === "CoordSet" ? (
                                            <>
                                              <SummaryRow
                                                label={`base cost : ${product?.payment_calculation?.pricing_calculation?.outer_wear_category?.name || 0}`}
                                                value={`${product?.payment_calculation?.pricing_calculation?.silhouette_outerwear || 0}`}
                                              />
                                              <SummaryRow
                                                label={`base cost : ${product?.payment_calculation?.pricing_calculation?.bottom_category?.name || 0}`}
                                                value={`${product?.payment_calculation?.pricing_calculation?.silhouette_bottom || 0}`}
                                              />
                                            </>
                                          ) : (
                                            <SummaryRow
                                              label={`base cost: ${product?.payment_calculation?.pricing_calculation?.category_name?.name || ""}`}
                                              value={`${product?.payment_calculation?.pricing_calculation?.silhouette || 0}`}
                                            />
                                          )}

                                          <SummaryRow
                                            label="fabric (+)"
                                            value={`${product?.payment_calculation?.pricing_calculation?.fabric || 0}`}
                                          />
                                          <SummaryRow
                                            label="Craft (+)"
                                            value={`${product?.payment_calculation?.pricing_calculation?.technique || 0}`}
                                          />
                                          <SummaryRow
                                            label="Prominence (+)"
                                            value={`${product?.payment_calculation?.pricing_calculation?.prominence || 0}`}
                                          />
                                          <SummaryRow
                                            label="Total Estimated cost"
                                            value={`${product?.payment_calculation?.pricing_calculation?.total || 0}`}
                                          />
                                        </div>
                                        <div className="mx-auto flex flex-col py-4">
                                          <p className="text-xs font-light">
                                            *** Your final cost may vary slightly{" "}
                                            <span className="font-medium text-blue-600">
                                              (±20%)
                                            </span>{" "}
                                            depending on design and materials.
                                          </p>
                                        </div>
                                      </div>
                                    </div>

                                    {product.is_add_to_bag_allow === true && (
                                      <div className="mt-8 flex w-full flex-col">
                                        <FormButton
                                          id="btn_cc_proceed_pay"
                                          label="Add to Bag"
                                          type="button"
                                          color="gray"
                                          hairline="blue"
                                          onClick={async () => {
                                            try {
                                              await getApiClient(
                                                `cart/co-creation/save?session_id=${product.session_id}`,
                                                { method: "POST" },
                                              );
                                              router.push("/bag");
                                            } catch {
                                              // silently fail
                                            }
                                          }}
                                        />
                                      </div>
                                    )}

                                    {product.vision_share_allow === true && (
                                      <div className="mt-8 flex w-full flex-col">
                                        <button
                                          type="button"
                                          onClick={() =>
                                            openSpecificModal(
                                              `visionBoard_share_${product.session_id}`,
                                            )
                                          }
                                          className="btn-outline relative top-2 flex w-full items-center justify-center text-center"
                                        >
                                          <span className="md:hidden">
                                            Share
                                          </span>
                                          <span className="hidden md:inline">
                                            Share Vision
                                          </span>
                                        </button>
                                      </div>
                                    )}

                                    <DialogModal
                                      name={`visionBoard_share_${product.session_id}`}
                                      isOpen={
                                        openModal ===
                                        `visionBoard_share_${product.session_id}`
                                      }
                                      onClose={closeAllModals}
                                      size="md"
                                      title=""
                                      subtitle=""
                                      showFooter={false}
                                    >
                                      <form className="flex flex-col gap-4 p-4">
                                        <div className="border px-6 py-4">
                                          <input
                                            id="invite-customer-name"
                                            type="text"
                                            required
                                            placeholder="Enter Customer Name"
                                            value={customer_name}
                                            onChange={(e) =>
                                              setCustomerName(e.target.value)
                                            }
                                            className="flex w-full"
                                          />
                                        </div>
                                        <div className="border px-6 py-4">
                                          <input
                                            id="invite-email"
                                            type="email"
                                            required
                                            placeholder="Enter email"
                                            value={inviteEmail}
                                            onChange={(e) =>
                                              setInviteEmail(e.target.value)
                                            }
                                            className="flex w-full"
                                          />
                                        </div>
                                        <button
                                          type="submit"
                                          className="btn-outline"
                                          aria-label="Share vision board"
                                          onClick={(e) => {
                                            e.preventDefault();
                                            void handleInviteSubmit(
                                              product.session_id,
                                            );
                                          }}
                                          disabled={isInviting}
                                        >
                                          {isInviting
                                            ? "Sharing..."
                                            : "Share Vision"}
                                        </button>
                                      </form>
                                    </DialogModal>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      );
                    })
                  ) : (
                    <div className="col-span-full mx-auto flex w-full flex-col items-center justify-center py-16 md:w-1/2">
                      <div className="text-center">
                        <h3 className="mb-2 text-lg font-medium text-gray-900">
                          No Vision Boards
                        </h3>
                        <p className="mb-6 text-gray-500">
                          {selectedStatus === "all"
                            ? "You haven't created any vision boards yet."
                            : `No vision boards with status "${STATUS_PILL[selectedStatus]?.label ?? selectedStatus}".`}
                        </p>
                        {selectedStatus === "all" && (
                          <Link
                            href="/morni-guidance?group=base_canvas&step=define_vibe"
                            className="btn-outline"
                          >
                            Create Vision Board
                          </Link>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default withAuth(OrderClients);
