"use client";

import { useGlobalContext } from "@/context/Provider";
import apis from "@/utils/apis";
import { Bike, FileCheck, Pizza, Store } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";

export default function OrderProgressTracker({ orderStatus, deliverType, orderPlacedAt, createdAt }: any) {

  const searchParams = useSearchParams();
  const router = useRouter();
  const orderId = searchParams.get("id");

  const { Toast } = useGlobalContext();

  const calculateRemainingTime = () => {
    if (!orderId) return 0;

    const timeRef = orderPlacedAt || createdAt;
    if (!timeRef) return 0;

    try {
      const startTime = new Date(timeRef).getTime();
      if (isNaN(startTime)) return 0;

      const currentTime = new Date().getTime();
      const elapsedSeconds = Math.floor((currentTime - startTime) / 1000);
      const remaining = Math.min(Math.max(30 - elapsedSeconds, 0), 30);

      return remaining;
    } catch (error) {
      console.error("Error calculating remaining time:", error);
      return 0;
    }
  };

  const [remainingTime, setRemainingTime] = useState(0);
  const [progress, setProgress] = useState(0);

  const steps = [
    { id: 1, title: "Confirmed By Vendor/Store", time: "02:50 Pm", icon: Store },
    { id: 2, title: "Order Prepared", time: "03:00 Pm", icon: FileCheck },
    { id: 3, title: "On the way", time: "", icon: Bike },
    { id: 4, title: "Order Delivered", time: "", icon: Pizza },
  ];

  const statusStepMap: any = {
    order_confirmed: 1,
    ready_for_pickup: 2,
    picked_up: 3,
    out_for_delivery: 3,
    delivered: 4,
  };

  const currentStep = statusStepMap[orderStatus] || 0;

  const filteredSteps = deliverType === "takeaway"
    ? steps.filter(step => step.title !== "On the way")
    : steps;

  const handleCancelOrder = async () => {
    if (!orderId) {
      Toast.error("Invalid order ID");
      return;
    }

    try {
      await apis.Orders.CancelOrder(orderId);
      Toast.success("Order Cancelled Successfully");
      router.push(`/summary?id=${orderId}`);
    } catch (error: any) {
      Toast.error(error);
    }
  };

  useEffect(() => {
    const initialRemaining = calculateRemainingTime();
    setRemainingTime(initialRemaining);
    setProgress((initialRemaining / 30) * 100);

    if (initialRemaining <= 0) return;

    const intervalId = setInterval(() => {
      setRemainingTime((prev) => {
        const newTime = prev - 1;
        setProgress((newTime / 30) * 100);
        if (newTime <= 0) {
          clearInterval(intervalId);
        }
        return newTime;
      });
    }, 1000);

    return () => clearInterval(intervalId);
  }, [orderId, orderPlacedAt, createdAt]);

  useEffect(() => {
    const nonCancellableStatuses = ["ready_for_pickup", "preparing", "picked_up", "out_for_delivery", "delivered", "cancelled"];
    if (orderStatus && nonCancellableStatuses.includes(orderStatus) && orderId) {
      const storageKey = `order_timer_${orderId}`;
      localStorage.removeItem(storageKey);
    }
  }, [orderStatus, orderId]);

  return (
    <div className="w-full max-w-md mx-auto">
      <h3 className="font-medium text-gray-800 mb-4">Progress of your order</h3>

      <div className="border rounded-lg p-4 bg-white">
        <div className="flex flex-col">
          {filteredSteps?.map((step, index) => (
            <div key={step.id} className="flex">
              <div className="flex flex-col items-center mr-4">
                <div
                  className={`w-8 h-8 rounded-full flex items-center justify-center
                      ${step.id <= currentStep
                      ? "bg-brand-100 text-primary"
                      : "bg-gray-100 text-gray-400"
                    }`}
                >
                  {React.createElement(step.icon, { size: 16 })}
                </div>
                {index < filteredSteps.length - 1 && (
                  <div
                    className={`w-[2px] h-12 
                        ${step.id < currentStep ? "bg-primary" : "bg-gray-200"
                      }`}
                  />
                )}
              </div>

              <div className="flex-1 pb-8">
                <p
                  className={`font-medium ${step.id <= currentStep ? "text-gray-800" : "text-gray-400"
                    }`}
                >
                  {step.title}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>
      {remainingTime > 0 && ["order_placed", "order_confirmed", "pending", "upcomming"].includes(orderStatus) && (
        <div className="relative mt-5">
          <button
            className="relative bg-red-500 text-white px-4 py-2 rounded w-full overflow-hidden hover:bg-red-600"
            onClick={handleCancelOrder}
          >
            <div
              className="absolute left-0 top-0 h-full bg-red-700/40 transition-all duration-1000 ease-linear"
              style={{ width: `${progress}%` }}
            ></div>

            <span className="relative z-10 font-medium">
              Cancel Order ({remainingTime}s)
            </span>
          </button>
        </div>
      )}
    </div>
  );
}