"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Image from "next/image";
import {AWS_CDN_URL, CDN_URL } from "@/utils/staticValues";
import Cookies from "js-cookie";
import { TextLink } from "@/app/components/button";

interface Order {
  order_id: string;
  no_of_item: string;
  item_order: string;
  coupon_discount_amount: string;
  shipping_price: string;
  grand_total: string;
  payment_status: string;
  status: string;
  order_at: number;
  estimated_lead_time: any;
  product_image: string;
  item_order_type: string;
  shipping_url: string;
}

export default function OrderDetails() {
  const params = useParams();
  const [product, setProduct] = useState<Order[] | null>(null);
  const [order, setOrder] = useState<Order | null>(null);
  const [grandTotal, setGrandTotal] = useState<string>("0");
  const [coupon, setCoupon] = useState<number | null>(null);
  const [estimatedLeadTime, setEstimatedLeadTime] = useState<string>("0");

  useEffect(() => {
    async function fetchOrder() {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_APP_URL}/dashboard/order/detail?order_id=${params.orderId}`,
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${Cookies.get("token")}`,
            },
          },
        );

        if (!response.ok) {
          throw new Error(`Error: ${response.status} - ${response.statusText}`);
        }

        const data = await response.json();
        const allOrders: Order[] = data.data.order;

        console.log("Fetched Orders:", data.data);
        setProduct(data.data.order_item || null);
        setOrder(data.data.order || null);
        setGrandTotal(data.data.grandTotal || "0");
        setCoupon(data.data.order.coupon);
        setEstimatedLeadTime(data.data.estimated_lead_time || "0");
      } catch (error) {
        console.error("Error fetching orders:", error);
      }
    }

    fetchOrder();
  }, [params.orderId]);

  if (!product) {
    return <div className="p-5 text-gray-500">Loading order details...</div>;
  }
  console.log("Product Details:", grandTotal);
  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col">
        <div className="flex w-full flex-col gap-1">
          <button
            type="button"
            className="btn-link"
            onClick={() => window.history.back()}
          >
            My orders
          </button>
        </div>
        <div className="flex flex-col items-start justify-center gap-4 align-bottom md:flex-row md:items-end">
          <div className="mt-4 flex w-full flex-col gap-1">
            <h1 className="med">Order Details </h1>
            <p className="font-bogart text-lg">
              {order?.order_id} | {product.length} items
            </p>
          </div>
          <div>
            <div className="flex flex-row items-center gap-2 rounded-full bg-teal-100 p-1 align-middle">
              <div className="flex h-8 w-8 items-center justify-center overflow-hidden rounded-full bg-teal-600 align-middle text-white">
                <span
                  className="icon-[material-symbols-light--delivery-truck-speed]"
                  style={{ width: 16, height: 20 }}
                ></span>
              </div>
              <div className="flex flex-col pr-4">
                <span className="text-xs/4 font-medium text-teal-600 capitalize">
                  {order?.status}
                </span>
                <span className="text-xs">{order?.order_at}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="flex flex-col gap-5">
        <div className="md:-4 grid grid-cols-1 gap-2 md:grid-cols-2">
          {product &&
            product.map((item: any, index: number) =>
              item.item_order_type === "CO_CREATION" ? (
                (console.log("Co-Creation Item:", item),
                (
                  <div
                    key={index}
                    className="grid grid-cols-3 gap-4 bg-white p-5"
                  >
                    <div className="col-span-1">
                      <div>
                        {Array.isArray(item.order_summary.category) ? (
                          item.order_summary.category
                            .slice(1)
                            .map((cat: any, idx: number) => (
                              <Image
                                key={idx}
                                src={`${AWS_CDN_URL}/${cat.image || cat.silhouette.silhouette_image}`}
                                width={120}
                                height={160}
                                alt={item.product_name}
                                className="img-responsive"
                              />
                            ))
                        ) : (
                          <Image
                            src={`${AWS_CDN_URL}/${item.product_image}`}
                            alt={item.product_name}
                            width={200}
                            height={200}
                            className="img-responsive"
                          />
                        )}
                      </div>
                    </div>

                    <div className="col-span-2 flex flex-col gap-2">
                      <div className="grid grid-cols-1 gap-2 md:gap-4">
                        <div>
                          <div className="font-bogart">{item.product_name}</div>
                          <div className="font-bogart">
                            ${item.product_price}
                          </div>
                        </div>
                        
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Quantity:</span>{" "}
                          {item.quantity}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Vibe:</span>{" "}
                          {item.order_summary.vibe}
                        </p>
                        {item.order_summary.category.length > 0 && (
                          <p className="text-xs text-gray-950">
                            <span className="font-medium">Category:</span>{" "}
                            {item.order_summary.category[0].name}
                          </p>
                        )}
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Silhouette:</span>
                          {item.order_summary.silhouette.map(
                            (silhouette_data: any, index: number) => (
                              <p key={index} className="text-xs text-gray-950">
                                {silhouette_data.piece_name}-{" "}
                                {silhouette_data.silhouette.silhouette_name}
                              </p>
                            ),
                          )}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Fabric:</span>{" "}
                          {item.order_summary.fabric}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Color:</span>{" "}
                          {item.order_summary.color}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">ArtWork:</span>{" "}
                          {item.order_summary.art_data}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Technique Family:</span>{" "}
                          {item.order_summary.technique_family}
                        </p>
                        <p className="text-xs text-gray-950">
                          <span className="font-medium">Prominence:</span>{" "}
                          {item.order_summary.prominence}
                        </p>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div
                  key={index}
                  className="grid grid-cols-3 gap-4 bg-white p-5"
                >
                  <div className="col-span-1">
                    <div>
                      <Image
                        src={`${AWS_CDN_URL}/${item.product_image}`}
                        alt=""
                        width={200}
                        height={200}
                        className="img-responsive"
                      />
                    </div>
                  </div>
                  <div className="col-span-2 flex flex-col gap-2">
                    <div>
                      <div className="font-bogart">{item.product_name}</div>
                      <div className="font-bogart">${item.product_price}</div>
                    </div>
                    <div className="flex flex-col text-xs">
                      <span>Qunatity</span>
                      <span>{item.quantity}</span>
                    </div>
                    <div className="flex flex-col text-xs">
                      <span>Size</span>
                      <span className="uppercase">{item.size}</span>
                    </div>
                  </div>
                </div>
              ),
            )}

          {/* end loop items here */}
        </div>
        <div className="flex flex-col border-t-1 border-b-1 border-dashed py-4">
          <div className="grid grid-cols-1 gap-2 md:grid-cols-4 md:gap-5">
            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Total Amount</span>
              <span className="font-bogart text-[16px]">
                ${parseInt(grandTotal)}
              </span>
            </div>
            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Shipping Charge</span>
              <span className="font-bogart text-[16px]">
                $ {parseInt(order?.shipping_price || "0")}
              </span>
            </div>
            {coupon !== null && coupon > 0 && (
              <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
                <span>Coupons Discount</span>
                <span className="font-bogart text-[16px]">
                  ${parseInt(coupon.toString())}
                </span>
              </div>
            )}

            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Grand Total</span>
              <span className="font-bogart text-[16px]">
                ${parseInt(grandTotal)}
              </span>
            </div>
          </div>
        </div>
        <div className="flex flex-col border-b-1 border-dashed pt-1 pb-4">
          <div className="grid grid-cols-1 gap-2 md:grid-cols-4">
            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Order At</span>
              <span className="font-bogart text-[16px]">{order?.order_at}</span>
            </div>
            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Payment Status</span>
              <span className="font-bogart text-[16px]">
                {order?.payment_status}
              </span>
            </div>

            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <span>Estimated Production Time</span>
              <span className="font-bogart text-[16px]">
                {estimatedLeadTime} Days
              </span>
            </div>
            <div className="flex flex-row items-center justify-between align-middle text-xs md:flex-col md:items-start">
              <TextLink
                id="link_shipping_tracking_code"
                href={order?.shipping_url || "#"}
                label="Shipping Tracking code"
                color="gray"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
