"use client";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { AWS_CDN_URL } from "@/utils/staticValues";
import { useDispatch } from "react-redux";
import { setCartItemCount } from "../redux/cartSlice";

interface Product {
    id: string;
    size: string;
    main_item_image: {
      image_url: string;
    };
    design_house: {
      name: string;
    };
    product_name: string;
    price: number;
    item_order_type: string;
  }
  interface Order {
    order_id: string;
    created_at: string;
    total_price:string;
    shipping_price:string;
    coupon_discount_amount:any,
    coupon_stripe_id:string
    order_at:any
    
   
  }
  interface Coupon {
    coupons_code: string;
  }
  interface Customer {
    name: string;
    email: string;
  }
  interface ShippingAddress {
    name:string;
    address:{
        line1:string;
        city:string;
        line2:string;
        state:string;
        country:string;
        postal_code:string;

    }
  }
export default function OrderClient() {
  const router = useRouter();
  const dispatch = useDispatch();
  const searchParams = useSearchParams();
  const orderId = searchParams.get("order_id");
  const [invoicePdf, setInvoicePdf] = useState("");

  const [products, setProducts] = useState<Product[]>([]);
  const [shipping, setShipping] = useState<ShippingAddress | null>(null);
  const [customer, setCustomer] = useState<Customer | null>(null);
  const [order, setOrder] = useState<Order | null>(null);
  const [coupon, setCoupon] = useState<Coupon | null>(null);
  const [grandTotalAmount, setGrandTotalAmount] = useState('0');
  const [productionLeadTime, setProductionLeadTime] = useState('0');
  const [isLoading, setIsLoading] = useState(true);

  // Prevent body scroll when loader is active
  useEffect(() => {
    if (isLoading) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    
    // Cleanup function to restore scroll when component unmounts
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isLoading]);

  useEffect(() => {
    if (!orderId) return;
    (async () => {
      try {
        setIsLoading(true);
        const res = await fetch(
          `/api/order/detail?order_id=${orderId}`,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        if (!res.ok) throw new Error(`Error ${res.status}: ${res.statusText}`);
        const data = await res.json();   
        setProducts(data.data.order_item);  
        setOrder(data.data.order); 
        setInvoicePdf(data.data.invoice_pdf);  
        setShipping(data.data.shipping_options); 
        setCustomer(data.data.customer);  
        setGrandTotalAmount(data.data.grandTotal);
        setCoupon(data.data.coupon);
        setProductionLeadTime(data.data.estimated_lead_time);
          setIsLoading(false);
       
      } catch (err) {
        console.error("Error fetching invoice:", err);
      } finally {
        setIsLoading(false);
      }
    })();
  }, [orderId]);



  return (
    <div className="mob-noise relative min-h-lvh py-20">
      {isLoading ? (
        // Stripe Verification Loader
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-white/90 backdrop-blur-sm overflow-hidden">
          <div className="relative z-10 mx-auto flex w-full flex-col items-center justify-center md:w-[50%] overflow-hidden">
            <div className="wrapper">
              <div className="relative mx-auto flex w-full flex-col items-center justify-center py-5 align-middle md:w-[75%]">
                {/* Loading Animation */}
                <div className="mb-8">
                  <div className="relative h-20 w-20">
                    <div className="absolute inset-0 rounded-full border-4 border-gray-200"></div>
                    <div className="absolute inset-0 animate-spin rounded-full border-4 border-transparent border-t-gray-950"></div>
                  </div>
                </div>
                
                {/* Main Message */}
                <div className="font-hasiant text-[4rem]/[1.2] md:text-[6rem]/[1.2] font-light capitalize text-center mb-4">
                  Verifying
                </div>
                
                {/* Subtitle */}
                <div className="relative mx-auto flex flex-row justify-center border-t-1 border-b-1 border-dashed pt-6 pb-4 px-4">
                  <p className="font-macropolo text-base md:text-lg font-medium tracking-[0.15rem] md:tracking-[0.25rem] uppercase text-center">
                    We are verifying your details with Stripe
                  </p>
                </div>
                
                {/* Additional Info */}
                <div className="mt-6 text-center">
                  <p className="text-sm text-gray-600 max-w-md mx-auto">
                    Please wait while we confirm your payment and prepare your order details. This should only take a moment.
                  </p>
                </div>

                {/* Animated dots */}
                <div className="mt-4 flex space-x-1">
                  <div className="h-2 w-2 bg-gray-950 rounded-full animate-pulse"></div>
                  <div className="h-2 w-2 bg-gray-950 rounded-full animate-pulse" style={{animationDelay: '0.2s'}}></div>
                  <div className="h-2 w-2 bg-gray-950 rounded-full animate-pulse" style={{animationDelay: '0.4s'}}></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <>
      <div className="fixed top-10 right-0 z-10 h-[50%] w-[50%] overflow-hidden md:h-[40%] md:w-[40%]">
        <div className="absolute -top-[20%] -right-[40%] h-full w-full md:-top-[50%] md:-right-[40%] md:h-[80%] md:w-[80%]">
          <Image
            src="/images/chakra.png"
            alt="Chakra"
            width={600}
            height={600}
            className="img-responsive opacity-30"
          />
        </div>
      </div>
      <div className="absolute bottom-0 left-0 z-10 h-full w-[50%] overflow-hidden md:h-[80%] md:w-[20%]">
        <div className="absolute bottom-0 left-0 h-full w-full md:w-[80%]">
          <Image
            src="/images/motif-peacock.png"
            alt="peacock motif"
            width={600}
            height={600}
            className="img-responsive absolute bottom-0 left-0 opacity-60"
          />
        </div>
      </div>
      <div className="relative z-30 mx-auto flex w-full flex-col md:w-[50%]">
        <div className="wrapper">
          <div className="relative mx-auto flex w-full flex-col items-center justify-center py-5 align-middle md:w-[75%]">
            <span className="icon-thread-eye h-23 w-25 bg-gray-950"></span>
            <div className="font-hasiant text-[10rem]/24 font-light capitalize">
              Thank you!
            </div>
            <div className="relative mx-auto -mt-4 flex flex-row justify-end border-t-1 border-b-1 border-dashed pt-6 pb-1">
              <p className="font-macropolo text-lg font-medium tracking-[0.25rem] uppercase">
                so much for your shopping
              </p>
            </div>
          </div>
        </div>
        <div className="wrapper pt-5 pb-10">
          <div className="mx-auto flex w-full flex-col gap-10 md:w-[80%]">
            <div className="flex flex-col items-center justify-between gap-2">
              <h1 className="med tracking-widest">Hello, {customer?.name}</h1>
              <div className="flex flex-col items-center justify-center">
                <p className="text-xs font-medium uppercase">Your order id</p>
                <h4 className="med uppercase">{order?.order_id}</h4>
              </div>
            </div>
            <div className="grid grid-cols-1 items-start gap-5 align-top md:grid-cols-2">
              <div className="flex flex-col gap-1 col-span-1">
                <div className="text-sm font-medium capitalize">
                  Shipping Info
                </div>
                <div className="text-xs">
                  <p>{customer?.name}</p>
                  <p>{customer?.email}</p>
                  <address className="mt-2">
                    {shipping?.address?.line1} {" "}  {shipping?.address?.line2} {" "} {shipping?.address?.city } {" "} {shipping?.address?.state} {" "} {shipping?.address?.country} {" "} {shipping?.address?.postal_code}
                   
                  </address>
                </div>
              </div>
              <div className="flex flex-col gap-1">
                <div className="text-sm font-medium capitalize">
                  Order Placed
                </div>
                <div className="flex flex-col text-xs">
                {order?.order_at}
                </div>
              </div>
              <div className="flex flex-col gap-1 md:text-right">
                <div className="text-sm font-medium capitalize flex flex-col gap-1">
                  <span>Estimated Production Lead Time:</span>
                  <span className="text-xs font-normal">{productionLeadTime} Days</span>
                </div>
              </div>
            </div>
            <div className="flex flex-col gap-4">
              <div className="font-macropolo flex border-b-1 border-gray-950/25 pb-2 font-medium tracking-widest uppercase">
                Item (s)
              </div>
              <div className="flex flex-col gap-1">
              {products &&
                products.map((product: any,index) => (
                    <div className="grid grid-cols-3 gap-8 bg-white/50 p-5" key={index}>
                  <div className="col-span-2">
                    <div className="grid grid-cols-4 gap-5">
                      <div className="col-span-1">
                        <div className="border-1">
                          <Image
                            src={`${AWS_CDN_URL}/${product.product_image}`}
                            alt="peacock motif"
                            width={300}
                            height={500}
                            className="img-responsive"
                          />
                        </div>
                      </div>
                      <div className="col-span-3">
                        <div className="flex flex-col gap-2">
                          <div className="font-bogart flex flex-col capitalize">
                            <p>{product.product_name}</p>
                            <p>$ {product.product_price}</p>
                          </div>
                          {product.item_order_type!='CO_CREATION' && (
                          <div className="flex flex-row gap-8 text-sm">
                            <p>Qty: {product.quantity}</p>
                            <p>Size: {product.size}</p>
                          </div>
                        )}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="col-span-1 justify-end text-right">
                    <div className="font-bogart capitalize">$ {product.total_price}</div>
                  </div>
                </div>
                ))}

              
               
                <div className="mt-5 flex flex-col border-1 border-dashed border-gray-950/50 bg-white/50">
                  <div className="flex flex-row items-center justify-between border-b-1 border-dashed border-gray-950/25 px-5 py-2 align-middle">
                    <p className="label">Sub total</p>
                    <p>$ {order?.total_price}</p>
                  </div>

                  <div className="flex flex-row items-center justify-between border-b-1 border-dashed border-gray-950/25 px-5 py-2 align-middle">
                    <p className="label">Shipping Cost</p>
                    <p>{products.length > 0 && products[0].item_order_type=='STORE' ? `$ ${order?.shipping_price}` : 'Due on Shipping'}</p>
                  </div>
                  { order?.coupon_stripe_id ?<div className="flex flex-row items-center justify-between border-b-1 border-dashed border-gray-950/25 px-5 py-2 align-middle">
                    <p className="label">
                      Applied Coupon <br />
                      <span className="text-sm font-medium uppercase">
                       {coupon?.coupons_code}
                      </span>
                    </p>
                    <p>- $ {order.coupon_discount_amount}</p>
                  </div> :null}
                  {/*  */}
                  <div className="flex flex-row items-center justify-between px-5 py-4 align-middle">
                    <p className="label">Grand Total</p>
                   

                    <p className="font-medium">
                        $ {
                            grandTotalAmount
                        }.00
                        </p>

                  </div>
                </div>
                <div className="mt-5 flex flex-col items-center justify-center gap-5">
                 
                 <a href={invoicePdf} className="btn-outline" type="button" target="_blank">Invoice</a>
                  <Link href="/category" className="btn-link">
                    Continue more Shopping 
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
        </>
      )}
    </div>
  );
}
