"use client";

import React, { useEffect, useRef, useState } from "react";
import { fetchShippingHistory, getShippingCards } from "@/app/lib/api/profile";

type ShipmentStatus = string; // API returns e.g. "Rejected", you can narrow later

interface Shipment {
  id: number; // from 'order'
  status: ShipmentStatus;
  tracking?: string; // from 'tracking'
  totalCards: number; // from 'cards'
  date: string; // from 'date'
  address: string; // from 'address'
  order: number;
}

const pageSize = 5;

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import CardPackUI from "./OrderModel";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}

const Shipping: React.FC = () => {
  const [page, setPage] = useState(1);
  const [shipments, setShipments] = useState<Shipment[]>([]);
  const [shipped, setShipped] = useState<number>(0);
  const [shipment, setShipment] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedOrder, setSelectedOrder] = useState<number | null>(null);
  const [orderCards, setOrderCards] = useState<{ id: number; image: string }[]>(
    [],
  );
  const [copiedOrderId, setCopiedOrderId] = useState<number | null>(null);

  const [selectedShipment, setSelectedShipment] = useState<Shipment | null>(
    null,
  );
  const [cardsLoading, setCardsLoading] = useState(false);

  const user = useSelector((state: { auth: AuthState }) => state.auth.user);

  const hasFetched = useRef(false); // prevent double-call in React StrictMode

  const handleCopy = (value: string, orderId: number) => {
    navigator.clipboard.writeText(value);
    setCopiedOrderId(orderId);

    setTimeout(() => {
      setCopiedOrderId(null);
    }, 1500);
  };

  const totalPages = Math.ceil(shipments.length / pageSize) || 1;

  const paginatedData = shipments.slice((page - 1) * pageSize, page * pageSize);

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  const openModal = async (orderId: number) => {
    setOpen(true);
    setSelectedOrder(orderId);

    // shipment info (date/status/address) ke liye:
    const shipment = shipments.find((s) => s.id === orderId) || null;
    setSelectedShipment(shipment);

    try {
      setCardsLoading(true);
      const resp = await getShippingCards(user.userId, user.token, orderId);

      if (resp.resp !== "success") throw new Error("Failed to load cards");
      setOrderCards(resp.cards || []);
    } finally {
      setCardsLoading(false);
    }
  };
  const statusClasses = (status: ShipmentStatus) => {
    const upper = status.toUpperCase();

    if (upper === "DELIVERED") {
      return "bg-[#15C57C] text-[#031012]";
    }
    if (upper === "PROCESSING") {
      return "!bg-[#2B5AFF26] text-[var(--color-blue)]";
    }
    if (upper === "REJECTED") {
      return "bg-red-500/80 text-white";
    }

    // default style
    return "!bg-[#2B5AFF26] text-[var(--color-blue)]";
  };

  useEffect(() => {
    const loadShipping = async () => {
      if (hasFetched.current) return;
      hasFetched.current = true;

      try {
        setLoading(true);
        setError(null);

        const json = await fetchShippingHistory(user.userId, user.token, 0);

        if (json.resp !== "success") {
          throw new Error("Backend responded with error");
        }

        const data = json.data;

        setShipped(data.shipped);
        setShipment(data.shipment);
        setTotal(data.total);

        const mapped: Shipment[] = (data.history || []).map((h: any) => ({
          id: h.order,
          status: h.status,
          tracking: h.tracking,
          totalCards: h.cards,
          date: h.date,
          address: h.address,
        }));

        setShipments(mapped);
        setPage(1);
      } catch (err: any) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    };

    loadShipping();
  }, []);

  return (
    <div className="px-8 border border-[var(--color-gray)] text-white font-onest">
      {loading && (
        <div className="flex w-full h-[160px] items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      )}

      {error && (
        <div className="py-6 text-center text-sm text-red-400">{error}</div>
      )}

      {!loading && !error && shipments.length === 0 && (
        <div className="py-6 text-center text-sm text-gray-300">
          No shipping history yet.
        </div>
      )}

      {!loading && !error && shipments.length > 0 && (
        <>
          {/* Rows */}
          <div>
            {paginatedData.map((item) => (
              <div
                key={item.id}
                className="py-4 md:py-6 border-b border-[var(--color-gray)] flex flex-col md:flex-row md:items-center md:justify-between gap-4"
              >
                {/* Left: Order ID + status / tracking */}
                <div className="flex-1 font-onest space-y-2">
                  <p className="text-sm md:text-base 2xl:text-xl font-normal tracking-wide">
                    ORDER ID{" "}
                    <span className="font-semibold text-white">#{item.id}</span>
                  </p>

                  <div className="flex flex-wrap items-center gap-3">
                    {/* Status pill */}
                    <span
                      className={
                        "px-3 py-1 text-sm font-sofia md:text-base font-extrabold italic uppercase tracking-wide rounded-[2px]" +
                        " " +
                        statusClasses(item.status)
                      }
                    >
                      {item.status}
                    </span>

                    {/* Tracking pill (optional) */}
                    {item.tracking && (
                      <div className="relative flex items-center gap-2 px-3 py-1 rounded-[2px] bg-[#2B5AFF26] font-sofia font-extrabold italic text-xs md:text-sm">
                        <span className="tracking-wide">{item.tracking}</span>
                        {item.status !== "pending" && (
                          <button
                            onClick={() => handleCopy(item.tracking!, item.id)}
                            className="w-4 h-4 rounded-[2px] flex items-center justify-center text-[10px] hover:scale-110 transition"
                          >
                            <img src="/images/profile/copy.svg" alt="copy" />
                          </button>
                        )}
                        {copiedOrderId === item.id && (
                          <span className="absolute -bottom-5 left-0 text-[10px] text-green-400">
                            Copied!
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                </div>

                {/* Middle: total cards box */}
                <div className="flex-1">
                  <div
                    className="w-fit cursor-pointer"
                    onClick={() => openModal(item.id)}
                  >
                    <div className="bg-[var(--color-naviBlue)] p-3 py-2 text-center">
                      <div className="text-[10px] font-sofia md:text-base uppercase tracking-wide ">
                        Total Cards
                      </div>
                      <div className="text-lg md:text-xl font-sofia italic -mt-1 font-extrabold">
                        {item.totalCards}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Right: date + address */}
                <div className="flex-1 md:max-w-sm text-xs md:text-sm 2xl:text-base space-y-1">
                  <p className="uppercase font-medium tracking-wide">
                    {item.date}
                  </p>
                  <p className="font-normal">{item.address}</p>
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          <div className="flex font-onest justify-center items-center gap-3 m-6">
            <button
              onClick={() => goToPage(page - 1)}
              disabled={page === 1}
              className="rounded-full w-[34px] h-[34px] flex justify-center items-center bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
            >
              <img src="/images/profile/left.svg" alt="Previous" />
            </button>

            {/* Page numbers */}
            <div className="flex gap-2 text-sm">
              {[...Array(totalPages)].map((_, i) => {
                const pg = i + 1;

                if (pg === 1 || pg === totalPages || Math.abs(pg - page) <= 1) {
                  return (
                    <button
                      key={pg}
                      onClick={() => goToPage(pg)}
                      className={`px-3 py-1 rounded transition-transform ${
                        pg === page
                          ? "scale-115 text-white"
                          : "text-[var(--color-naturalGray)]"
                      }`}
                    >
                      {pg}
                    </button>
                  );
                }

                if (pg === page - 2 || pg === page + 2) {
                  return (
                    <span key={`ellipsis-${pg}`} className="px-2 text-gray-400">
                      ...
                    </span>
                  );
                }

                return null;
              })}
            </div>

            <button
              onClick={() => goToPage(page + 1)}
              disabled={page === totalPages}
              className="flex justify-center items-center w-[34px] h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
            >
              <img src="/images/profile/right.svg" alt="Next" />
            </button>
          </div>
        </>
      )}
      <CardPackUI
        open={open}
        setOpen={setOpen}
        orderId={selectedOrder}
        shipment={selectedShipment}
        cards={orderCards}
        loading={cardsLoading}
      />
    </div>
  );
};

export default Shipping;
