"use client";

/**
 * OrderStatusCard Component
 *
 * A reusable component that displays dynamic order status information based on
 * the purchase order status history table.
 *
 * @example
 * ```tsx
 * // Basic usage
 * <OrderStatusCard
 *   purchaseOrderId={123}
 *   orderNumber="PO-202508-4295"
 * />
 *
 * // With custom styling
 * <OrderStatusCard
 *   purchaseOrderId={123}
 *   orderNumber="PO-202508-4295"
 *   className="custom-class"
 * />
 * ```
 *
 * @param purchaseOrderId - The ID of the purchase order
 * @param orderNumber - The order number to display in descriptions
 * @param className - Additional CSS classes to apply
 */

import React, { useEffect, useState } from "react";
import { FiCheck, FiClock } from "react-icons/fi";
import { purchaseOrderService } from "../../services/api";
import { formatDateTime } from "../../utils/dateUtils";
import { UserRole, getTimelineLabel } from "../../utils/roleStatusLabels";

interface StatusHistoryItem {
  id: number;
  purchaseOrderId: number;
  statusType: "submitted" | "picking" | "shipping" | "fulfillment";
  statusValue:
    | "Not Started"
    | "Submitted"
    | "Partially Picked"
    | "Picked"
    | "Partially Shipped"
    | "Shipped"
    | "Partially Fulfilled"
    | "Fulfilled";
  changedBy?: {
    id: number;
    firstname: string;
    lastname: string;
  };
  createdAt: string;
}

interface OrderStatusCardProps {
  purchaseOrderId: number;
  orderNumber: string;
  className?: string;
  role?: UserRole;
}

const OrderStatusCard: React.FC<OrderStatusCardProps> = ({
  purchaseOrderId,
  orderNumber,
  className = "",
  role,
}) => {
  const [statusHistory, setStatusHistory] = useState<StatusHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchStatusHistory = async () => {
      try {
        setLoading(true);
        const response =
          await purchaseOrderService.getPurchaseOrderStatusHistory(
            purchaseOrderId
          );
        setStatusHistory(response.data || []);
        setError(null);
      } catch (err) {
        console.error("Failed to fetch status history:", err);
        setError("Failed to load status history");
        setStatusHistory([]);
      } finally {
        setLoading(false);
      }
    };

    if (purchaseOrderId) {
      fetchStatusHistory();
    }
  }, [purchaseOrderId]);

  // Determine if a status is completed
  const isStatusCompleted = (statusValue: string) => {
    const completedStatuses = ["Submitted", "Picked", "Shipped", "Fulfilled"];
    return completedStatuses.includes(statusValue);
  };

  // Get status color based on completion and status value
  const getStatusColor = (statusValue: string, isCompleted: boolean) => {
    if (isCompleted) {
      return {
        icon: "bg-[#20C997]",
        text: "text-[#20C997]",
      };
    }

    // Different colors for different status types
    switch (statusValue) {
      case "Partially Picked":
      case "Partially Shipped":
      case "Partially Fulfilled":
        return {
          icon: "bg-orange-400",
          text: "text-orange-400",
        };
      case "Not Started":
        return {
          icon: "bg-gray-400",
          text: "text-gray-400",
        };
      default:
        return {
          icon: "bg-orange-400",
          text: "text-orange-400",
        };
    }
  };

  // Get display label based on status type and value
  const getDisplayLabel = (statusType: string, statusValue: string) => {
    if (role) {
      return getTimelineLabel(statusType, statusValue, role);
    }
    // Fallback: original behavior
    const typeLabels = {
      submitted: "Order",
      picking: "Order Picking",
      shipping: "Order Shipping",
      fulfillment: "Order Fulfillment",
    };
    const baseLabel = typeLabels[statusType as keyof typeof typeLabels] || "Order";
    switch (statusValue) {
      case "Not Started":
        return `${baseLabel} Created`;
      case "Submitted":
        return "Order Submitted";
      case "Partially Picked":
        return "Order Partially Picked";
      case "Picked":
        return "Order Picked";
      case "Partially Shipped":
        return "Order Partially Shipped";
      case "Shipped":
        return "Order Shipped";
      case "Partially Fulfilled":
        return "Order Partially Fulfilled";
      case "Fulfilled":
        return "Order Fulfilled";
      default:
        return `${baseLabel} - ${statusValue}`;
    }
  };

  // Get description based on status type
  const getDescription = (statusType: string, statusValue: string) => {
    if (statusValue === "Not Started") {
      return `(Order ID #${orderNumber})`;
    }

    const typeDescriptions = {
      submitted: `(Order ID #${orderNumber})`,
      picking: `(Order ID #${orderNumber})`,
      shipping: `(Order ID #${orderNumber})`,
      fulfillment: `(Order ID #${orderNumber})`,
    };

    return (
      typeDescriptions[statusType as keyof typeof typeDescriptions] ||
      `(Order ID #${orderNumber})`
    );
  };

  if (loading) {
    return (
      <div className={`p-4 ${className}`}>
        <h2 className="text-lg font-semibold text-black mb-4">Order Status</h2>
        <div className="space-y-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="flex items-center animate-pulse">
              <div className="w-4 h-4 bg-gray-200 rounded-full mr-3"></div>
              <div className="flex-grow">
                <div className="h-4 bg-gray-200 rounded w-24 mb-1"></div>
                <div className="h-3 bg-gray-200 rounded w-32"></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`p-4 ${className}`}>
        <h2 className="text-lg font-semibold text-black mb-4">Order Status</h2>
        <div className="text-red-500 text-sm">{error}</div>
      </div>
    );
  }

  // If no status history exists, show a default "Order Created" status
  if (statusHistory.length === 0) {
    return (
      <div className={`p-4 ${className}`}>
        <h2 className="text-lg font-semibold text-black mb-4">Order Status</h2>
        <div className="space-y-4">
          <div className="flex items-center">
            <div className="w-4 h-4 rounded-full flex items-center justify-center mr-3 bg-[#20C997]">
              <FiCheck size={10} className="text-white" />
            </div>
            <div className="flex-grow">
              <p className="text-sm font-medium text-[#20C997]">
                Order Created
              </p>
              <p className="text-xs text-gray-500">(Order ID #{orderNumber})</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Sort status history by creation date (newest first - reverse chronological order)
  const sortedStatusHistory = [...statusHistory].sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  );

  return (
    <div className={`p-4 ${className}`}>
      <h2 className="text-lg font-semibold text-black mb-4 sticky top-0 bg-white z-10 pb-2">
        Order Status
      </h2>

      <div className="space-y-4 h-full overflow-y-auto no-scrollbar hidden lg:block pb-4">
        {sortedStatusHistory.map((statusItem, index) => {
          const isCompleted = isStatusCompleted(statusItem.statusValue);
          const colors = getStatusColor(statusItem.statusValue, isCompleted);
          const displayLabel = getDisplayLabel(
            statusItem.statusType,
            statusItem.statusValue
          );
          const description = getDescription(
            statusItem.statusType,
            statusItem.statusValue
          );

          return (
            <div key={statusItem.id} className="flex items-center">
              <div
                className={`w-4 h-4 rounded-full flex items-center justify-center mr-3 ${colors.icon}`}
              >
                {isCompleted ? (
                  <FiCheck size={10} className="text-white" />
                ) : (
                  <FiClock size={10} className="text-white" />
                )}
              </div>
              <div className="flex-grow">
                <p className={`text-sm font-medium ${colors.text}`}>
                  {displayLabel}
                </p>
                <p className="text-xs text-gray-500">{description}</p>
                <p className="text-xs text-gray-400 mt-1">
                  {formatDateTime(statusItem.createdAt)}
                </p>
                {statusItem.changedBy && (
                  <p className="text-xs text-gray-400">
                    by {statusItem.changedBy.firstname}{" "}
                    {statusItem.changedBy.lastname}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Mobile version without scroll */}
      <div className="space-y-4 lg:hidden">
        {sortedStatusHistory.map((statusItem, index) => {
          const isCompleted = isStatusCompleted(statusItem.statusValue);
          const colors = getStatusColor(statusItem.statusValue, isCompleted);
          const displayLabel = getDisplayLabel(
            statusItem.statusType,
            statusItem.statusValue
          );
          const description = getDescription(
            statusItem.statusType,
            statusItem.statusValue
          );

          return (
            <div key={statusItem.id} className="flex items-center">
              <div
                className={`w-4 h-4 rounded-full flex items-center justify-center mr-3 ${colors.icon}`}
              >
                {isCompleted ? (
                  <FiCheck size={10} className="text-white" />
                ) : (
                  <FiClock size={10} className="text-white" />
                )}
              </div>
              <div className="flex-grow">
                <p className={`text-sm font-medium ${colors.text}`}>
                  {displayLabel}
                </p>
                <p className="text-xs text-gray-500">{description}</p>
                <p className="text-xs text-gray-400 mt-1">
                  {formatDateTime(statusItem.createdAt)}
                </p>
                {statusItem.changedBy && (
                  <p className="text-xs text-gray-400">
                    by {statusItem.changedBy.firstname}{" "}
                    {statusItem.changedBy.lastname}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>
      <style jsx>{`
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none; /* IE and Edge */
          scrollbar-width: none; /* Firefox */
        }
      `}</style>
    </div>
  );
};

export default OrderStatusCard;
