"use client";

import { Fragment, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../store";
import { formatDate } from "../../../common/DateFormant";
import { trackOrder, updateOrderStatus } from "../../../api/api";
import { useDispatch } from "react-redux";
import { useParams } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Menu, Transition } from "@headlessui/react";
import { truncateDescription } from "../../../utils/commonFunction";

function PurchaseStatus() {
  const params = useParams();
  const productId = params?.id as string;
  const { orderData } = useSelector(
    (state: RootState) => state.OrderTrackReducer
  );
  const [selectedStatus, setSelectedStatus] = useState("");
  const [currentStatus, setCurrentStatus] = useState("");

  const ordersDetail = orderData?.data?.orders;

  const dispatch = useDispatch<any>();

  const steps = [
    { label: "Bidding Process", status: "completed" },
    { label: "Accepted", status: "pending" },
    { label: "In Progress", status: "pending" },
    { label: "In Transit", status: "pending" },
    { label: "Completed", status: "pending" },
  ];

  useEffect(() => {
    if (productId) {
      dispatch(trackOrder(productId));
    }
    if (ordersDetail?.order_status) {
      setSelectedStatus(ordersDetail.order_status);
      setCurrentStatus(ordersDetail.order_status);
    }
  }, [dispatch, productId, ordersDetail?.order_status]);

  const handleStatusChange = async (status: string) => {
    // Only proceed if the status is actually changing
    if (status === currentStatus) {
      return;
    }

    try {
      await dispatch(updateOrderStatus({ id: Number(productId), status }));
      setSelectedStatus(status);
      setCurrentStatus(status); // Update the current status after successful API call
    } catch {
      // Revert to previous status if API call fails
      setSelectedStatus(currentStatus);
      return null;
    }
  };

  const updateStepStatus = (orderStatus: string) => {
    let isCompleted = true;

    return steps.map((step) => {
      if (isCompleted) {
        step.status = "completed";
      }

      if (step.label === orderStatus) {
        step.status = "current";
        isCompleted = false;
      }

      return step;
    });
  };

  const orderStatusData = selectedStatus || ordersDetail?.order_status;
  const updatedSteps = updateStepStatus(orderStatusData);

  return (
    <div className="max-w-7xl w-full m-auto min-h-screen bg-gray-50 pt-4 flex flex-col items-center">
      <div className="bg-white w-full rounded-lg">
        {/* Header Section */}
        <div className="mb-4 flex justify-between xs:p-3">
          <h1 className="xs:text-sm font-semibold text-black lg:text-4xl flex items-center gap-4 cursor-pointer">
            <Link href="/profile/orders">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth="1.5"
                stroke="currentColor"
                className="lg:size-9 xs:size-5"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18"
                />
              </svg>
            </Link>
            Purchase Details
          </h1>
        </div>
        <hr />

        {/* Product Info Section */}
        <section className="relative md:px-0 xs:p-3">
          <div className="flex w-full md:max-w-full md:flex lg:max-w-full lg:flex md:mb-4 lmd:mt-3 rounded-lg bg-white sm:m-auto sm:mb-4 sm:max-w-[28rem] lg:p-3 lg:gap-3 md:gap-5 cursor-pointer justify-between">
            <div className="bg-white lg:w-8/12 rounded-b lg:rounded-b-none lg:rounded-r p-1 flex justify-between leading-normal">
              <div>
                <div className="xs:text-lg text-gray-900 font-bold lg:text-3xl mb-1 text-start lg:pt-1 capitalize">
                  {ordersDetail?.listing?.product_name}
                </div>

                <div className="mb-3 lg:mb-1 text-gray-600 lg:pt-1">
                  <p className="flex items-center gap-1 xs:text-sm lg:text-2xl font-medium">
                    <span>{formatDate(ordersDetail?.created_at)}</span> |
                    <span>{ordersDetail?.listing?.location}</span>
                  </p>
                </div>
                <p className="hidden text-black-700 text-start lg:text-lg font-bold text-[#373737] lg:block lg:pt-1">
                  {truncateDescription(ordersDetail?.listing?.description)}
                </p>
                <p className="text-green-500 md:text-2xl font-semibold text-start xs:text-lg mt-2 flex flex-col">
                  <span>
                    {ordersDetail?.currency === "USD" ? "US$" : "C$"}{" "}
                    {ordersDetail?.amount}
                  </span>
                  {ordersDetail?.listing?.currency !=
                    ordersDetail?.currency && (
                    <span className="text-gray-500 font-semibold text-base">
                      {ordersDetail?.listing?.currency === "USD" ? "US$" : "C$"}{" "}
                      {ordersDetail?.bid_amount}
                    </span>
                  )}
                </p>
              </div>
            </div>

            <div className="relative lg:w-4/12 lg:h-[212px] xs:h-[114px] xs:w-[122px] lg:p-0 p-2 rounded-lg overflow-hidden">
              <Image
                unoptimized
                src={ordersDetail?.listing?.images[0]}
                alt={ordersDetail?.listing?.product_name || "Listing image"}
                fill
                className="object-cover rounded-lg"
                sizes="(max-width: 768px) 122px, 248px"
              />
            </div>
          </div>
        </section>
        <hr />

        {/* Desktop Order Tracking with Status Dropdown */}
        <div className="px-4 sm:px-6 py-6 mb-6">
          <div className="flex  sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
            <h3 className="text-xl md:text-3xl text-black font-semibold">
              Order Tracking
            </h3>

            <Menu as="div" className="relative z-[9999]">
              <div>
                <Menu.Button className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg shadow-md hover:bg-gray-300 capitalize font-semibold text-sm z-[9999]">
                  {selectedStatus || ordersDetail?.order_status || "Status"}
                </Menu.Button>
              </div>

              <Transition
                as={Fragment}
                enter="transition ease-out duration-100"
                enterFrom="transform opacity-0 scale-95"
                enterTo="transform opacity-100 scale-100"
                leave="transition ease-in duration-75"
                leaveFrom="transform opacity-100 scale-100"
                leaveTo="transform opacity-0 scale-95"
              >
                <Menu.Items className="absolute right-0 mt-2 w-44 sm:w-48 origin-top-right bg-white rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden z-50 border-b border-gray-200">
                  <div>
                    {["Accepted", "In Progress", "In Transit", "Completed"].map(
                      (status, idx, arr) => (
                        <Menu.Item key={status}>
                          {({ active }) => (
                            <div
                              onClick={() => handleStatusChange(status)}
                              className={`w-full text-left px-4 py-3 text-sm font-medium text-black cursor-pointer border-b border-gray-200 ${
                                active
                                  ? "bg-navy text-white dark:bg-gray-600"
                                  : "text-gray-900 dark:text-white"
                              } ${
                                idx !== arr.length - 1
                                  ? "border-b border-gray-100"
                                  : ""
                              }`}
                            >
                              {status}
                            </div>
                          )}
                        </Menu.Item>
                      )
                    )}
                  </div>
                </Menu.Items>
              </Transition>
            </Menu>
          </div>

          <div className="relative">
            <div className="flex justify-between items-start relative ">
              {/* Horizontal progress line - positioned between first and last circle */}
              <div className="absolute top-6 left-5 right-5 h-0.5 bg-green-500 z-10"></div>
              {updatedSteps.map((step, index) => (
                <div
                  key={index}
                  className={`flex flex-col items-center relative ${
                    step.status === "current"
                      ? "bg-[#ecf5ec] p-2 rounded-lg"
                      : ""
                  }`}
                >
                  {/* Step circle */}
                  <div
                    className={`flex items-center justify-center w-10 h-10 rounded-full z-20 shadow-sm ${
                      step.status === "completed" || step.status === "current"
                        ? "bg-[#0B7D0C]"
                        : "bg-gray-300"
                    }`}
                  >
                    {(step.status === "completed" ||
                      step.status === "current") && (
                      <svg
                        className="h-5 w-5 text-white"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        viewBox="0 0 24 24"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          d="M5 13l4 4L19 7"
                        ></path>
                      </svg>
                    )}
                  </div>

                  {/* Step label */}
                  <p
                    className={`mt-2 text-center text-xs font-medium max-w-20 ${
                      step.status === "completed"
                        ? "text-[#0B7D0C]"
                        : step.status === "current"
                        ? "text-black font-bold"
                        : "text-gray-500"
                    }`}
                  >
                    {step.label}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </div>

        <hr />

        {/* Buyer Details Section */}
        <div className="py-3 px-4">
          <h3 className="xs:text-lg font-medium mb-4 lg:text-2xl text-[#A2A2A1] text-start">
            Buyer Details
          </h3>

          <div className="flex justify-between items-center">
            <div>
              <p className="text-[#373737] xs:text-lg lg:text-xl text-start font-semibold">
                Name:
                <span className="text-[#373737] text-base capitalize">
                  {" "}
                  {ordersDetail?.buyer?.name}{" "}
                </span>
              </p>
              <p className="text-[#2E2E2E] text-start lg:text-xl font-semibold">
                Email:{" "}
                <span className="text-[#373737] text-base">
                  {" "}
                  {ordersDetail?.buyer?.email}{" "}
                </span>
              </p>
              <p className="text-[#2E2E2E] text-start lg:text-xl font-semibold capitalize">
                Phone No:{" "}
                <span className="text-[#373737] text-base capitalize">
                  {" "}
                  {ordersDetail?.buyer?.phone}{" "}
                </span>
              </p>
              <p className="text-[#2E2E2E] text-start lg:text-xl font-semibold capitalize">
                Location:{" "}
                <span className="text-[#373737] text-base capitalize">
                  {[
                    ordersDetail?.buyer?.default_address?.house_number,
                    ordersDetail?.buyer?.default_address?.city,
                    ordersDetail?.buyer?.default_address?.postal_code,
                    ordersDetail?.buyer?.default_address?.country === "USA"
                      ? ordersDetail?.buyer?.default_address?.state
                      : ordersDetail?.buyer?.default_address?.province,
                    ordersDetail?.buyer?.default_address?.country,
                  ]
                    .filter((val) => val && val.trim() !== "")
                    .join(", ")}
                </span>
              </p>

              <div className="mt-4 text-start text-[#373737] text-lg">
                <p className="font-semibold text-[#A2A2A1] text-xl">
                  Next Steps for Transfer
                </p>
                <ul className="list-decimal list-inside space-y-4 mt-2">
                  <li>
                    <span className="font-semibold text-[#373737] text-lg">
                      Confirm Details and Coordinate Payment
                    </span>
                    <p className="text-[#373737] text-base mt-1">
                      Connect with the buyer to confirm all purchase details and
                      agree on a secure payment method.
                    </p>
                    <ul className="list-disc list-inside ml-6 mt-1 space-y-1">
                      <li className="text-[#373737] text-base">
                        Before making any payment, verify the buyer's identity
                        and ensure the item matches the description provided.
                      </li>
                      <li className="text-[#373737] text-base">
                        Consider exchanging user IDs or contact details to
                        ensure trust and transparency.
                      </li>
                      <li className="text-[#373737] text-base">
                        Use trusted payment platforms that offer buyer
                        protection whenever possible.
                      </li>
                    </ul>
                  </li>

                  <li>
                    <span className="font-semibold text-[#373737] text-lg">
                      Arrange Pickup or Delivery
                    </span>
                    <p className="text-[#373737] text-base mt-1">
                      Coordinate the pickup or delivery of the purchased item.
                      Our support team is available if you need assistance.
                    </p>
                  </li>

                  <li>
                    <span className="font-semibold text-[#373737] text-lg">
                      Complete Documentation
                    </span>
                    <p className="text-[#373737] text-base mt-1">
                      Fill out any required paperwork to finalize the transfer.
                      For further help, you can always submit a support ticket.
                    </p>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <hr />

        {/* Shipping Details Section */}
        <div className="mb-6 mt-7 xs:p-3">
          <h3 className="xs:text-lg font-medium mb-4 lg:text-2xl text-[#A2A2A1] text-start">
            Shipping Details
          </h3>
          <div className="flex justify-between items-center">
            <p>
              <br />
              <p className="text-[#2E2E2E] text-start lg:text-2xl font-medium capitalize">
                {" "}
                #{ordersDetail?.address?.house_number}{" "}
                {ordersDetail?.address?.locality}{" "}
              </p>
            </p>
          </div>
        </div>

        {/* Order Total Section */}
        <div className="mb-4 xs:p-3">
          <div className="flex justify-between font-medium">
            <p className="text-[#373737] lg:text-2xl font-medium">
              Order Total
            </p>
            <p className="text-[#373737] lg:text-2xl font-medium flex flex-col">
              <span>
                {ordersDetail?.currency === "USD" ? "US$" : "C$"}{" "}
                {ordersDetail?.converted_price}
              </span>
              {ordersDetail?.listing?.currency != ordersDetail?.currency && (
                <span className="text-gray-500 font-semibold text-base">
                  {ordersDetail?.listing?.currency === "USD" ? "US$" : "C$"}{" "}
                  {ordersDetail?.bid_amount}
                </span>
              )}
            </p>
          </div>
        </div>
        <hr />
      </div>
    </div>
  );
}

export default PurchaseStatus;
