"use client";

import { Loader2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

import Image from "next/image";
import PriceDisplay from "@/components/ui/formattedPrice";

const Page = ({ params }: { params: { uuid: string } }) => {
  const { uuid } = params;
  const [order, setOrder] = useState<OrdersType | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [updating, setUpdating] = useState<boolean>(false);
  const [name, setName] = useState("");

  const [orderStatus, setOrderStatus] = useState("");

  const handleUpdateOrder = async () => {


    const response = await fetch(`/api/admin/orders/${uuid}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name,
        orderStatus,
      }),
    })

    if (response.status === 200) {
      const data = await response.json();
      setLoading(true)
      // setOrder(data.order)
      setLoading(false)
      setUpdating(false)
      setName(data.order.shipment_details.name)
      setOrderStatus(data.order.order_status)
    } else {
      console.error("Failed to update order");
      setUpdating(false);
    }

  }

  const fetchOrderDetails = useCallback(async () => {
    const response = await fetch(`/api/admin/orders/${uuid}`);
    if (response.status === 200) {
      const data = await response.json();
      setOrder(data.order);
      setName(data.order.shipment_details.name);
      setOrderStatus(data.order.order_status);
    }
    setLoading(false);
  }, [uuid])

  useEffect(() => {
    fetchOrderDetails();
  }, [fetchOrderDetails]);

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen bg-gray-100">
        <Loader2 className="animate-spin h-10 w-10 text-indigo-600" />
      </div>
    );
  }

  else {
    return (
      <div className="w-full max-w-8xl mx-auto px-6 py-12 space-y-10 bg-gray-50 min-h-screen">
        <h1 className="text-4xl font-extrabold text-gray-900 tracking-tight">
          🧾 Order Summary
        </h1>



        {/* Update Order Dialog */}
        <Dialog>
          <DialogTrigger asChild>
            <button
              className={`mt-5 px-6 py-2 rounded-xl text-white transition font-semibold shadow-lg backdrop-blur border border-indigo-400 
      ${updating
                  ? "bg-indigo-300 cursor-not-allowed"
                  : "bg-gradient-to-r from-indigo-600 to-purple-600 hover:scale-105 hover:shadow-xl"
                }`}
            >
              {updating ? "Updating..." : "✨ Update Order"}
            </button>
          </DialogTrigger>

          <DialogContent className="sm:max-w-[500px] bg-white backdrop-blur-md shadow-2xl border border-indigo-100 rounded-2xl">
            <form onSubmit={handleUpdateOrder}>
              <DialogHeader className="text-center">
                <DialogTitle className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 text-transparent bg-clip-text">
                  ✏️ Edit Order
                </DialogTitle>
                <DialogDescription className="text-gray-700">
                  Update shipping info and order status.
                </DialogDescription>
              </DialogHeader>

              <div className="grid gap-6 py-6 px-1">
                <div className="grid gap-2">
                  <Label htmlFor="name" className="text-sm font-medium text-gray-800">Customer&apos;s Name</Label>
                  <Input
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="rounded-lg border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition hover:scale-[1.01]"
                  />
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="orderStatus" className="text-sm font-medium text-gray-800">Order Status</Label>

                  <select name="" id="orderStatus"
                    value={orderStatus}
                    onChange={(e) => setOrderStatus(e.target.value)}
                    className="rounded-lg border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition hover:scale-[1.01] px-3 py-2">

                    <option value="PROCESSING">PROCESSING</option>
                    <option value="DISPATCHED">DISPATCHED</option>
                    <option value="DELIVERED">DELIVERED</option>
                    <option value="CANCELLED">CANCELLED</option>
                  </select>

                </div>
              </div>

              <DialogFooter className="mt-4">
                <DialogClose asChild>
                  <Button
                    type="button"
                    variant="outline"
                    className="rounded-md border-gray-300 hover:bg-gray-100 transition"
                  >
                    Cancel
                  </Button>
                </DialogClose>
                <Button
                  type="submit"
                  disabled={updating}
                  className="bg-indigo-600 hover:bg-indigo-700 text-white rounded-md px-6 py-2 transition shadow-md hover:shadow-lg"
                >
                  {updating ? "Saving..." : "Save changes"}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>




        {/* Card */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {/* Shipping Details */}
          <div className="bg-white rounded-2xl shadow p-6 space-y-3 border">
            <h2 className="text-2xl font-semibold text-indigo-600 mb-2">📦 Shipping Info</h2>
            <p><span className="text-gray-600 font-medium">Name:</span> <span className="font-semibold">{order?.shipment_details?.name}</span></p>
            <p><span className="text-gray-600 font-medium">Phone:</span> <span className="font-semibold">{order?.shipment_details?.phone}</span></p>
            <p><span className="text-gray-600 font-medium">Email:</span> <span className="font-semibold">{order?.shipment_details?.email}</span></p>
            {order?.shipment_details.is_delivered ? (
              <>
                <p><span className="text-gray-600 font-medium">Delivered:</span> ✅ Yes</p>
                <p><span className="text-gray-600 font-medium">Delivery Date:</span> {order?.shipment_details?.delivery_date}</p>
              </>
            ) : (
              <p className="text-red-500 font-semibold">🚫 Not Delivered Yet</p>
            )}
          </div>

          {/* Delivery Address */}
          <div className="bg-white rounded-2xl shadow p-6 space-y-3 border">
            <h2 className="text-2xl font-semibold text-indigo-600 mb-2">🏠 Delivery Address</h2>
            <p><span className="text-gray-600 font-medium">Street:</span> <span className="font-semibold">{order?.address.address_line}</span></p>
            <p><span className="text-gray-600 font-medium">City:</span> <span className="font-semibold">{order?.address.city}</span></p>
            <p><span className="text-gray-600 font-medium">District:</span> <span className="font-semibold">{order?.address.district}</span></p>
            <p><span className="text-gray-600 font-medium">Division:</span> <span className="font-semibold">{order?.address.division}</span></p>
            <p><span className="text-gray-600 font-medium">Postal Code:</span> <span className="font-semibold">{order?.address.post_code}</span></p>
            <p><span className="text-gray-600 font-medium">Delivery Cost:</span> <span className="font-semibold">{order?.delivery_cost} Tk</span></p>
          </div>
        </div>

        {/* Payment Info */}
        <div className="bg-white rounded-2xl shadow p-6 border">
          <h2 className="text-2xl font-semibold text-indigo-600 mb-4">💳 Payment Info</h2>
          <p className="text-gray-600 font-medium">
            Payment Status:{" "}
            <span className={`ml-2 px-3 py-1 rounded-full text-sm font-semibold ${order?.payment.payment_status === "PAID"
              ? "bg-green-100 text-green-700"
              : "bg-yellow-100 text-yellow-700"
              }`}>
              {order?.payment.payment_status}
            </span>
          </p>
        </div>

        {/* Order Items */}
        <div className="bg-white rounded-2xl shadow p-6 border">
          <h2 className="text-2xl font-semibold text-indigo-600 mb-4">🛒 Ordered Items</h2>
          <div className="space-y-5">
            {order?.order_items.map((item, index) => (
              <div key={index} className="flex items-center gap-5 border-b pb-4 last:border-b-0">
                <Image
                  src={item.variant?.variant_images[0]?.file_url}
                  alt="Product"
                  width={70}
                  height={70}
                  className="rounded-lg object-cover border"
                />
                <div>
                  <p className="font-medium text-gray-800">{item.variant?.name}</p>
                  <p className="text-sm mt-1 font-semibold">
                    Qty: <span className="font-semibold">{item.quantity}</span> ×
                    <span className="font-semibold"> <PriceDisplay price={item.price}/></span>
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Order Summary */}
        <div className="bg-white rounded-2xl shadow p-6 border">
          <h2 className="text-2xl font-semibold text-indigo-600 mb-4">Final Summary</h2>

          <div className="grid sm:grid-cols-2 gap-y-3">
            <p><span className="text-gray-600 font-medium ">Order Total:</span>
              {order?.applied_discount && order.applied_discount > 0 ? (
                <span className="font-semibold"><PriceDisplay price={(order?.order_total_amount ?? 0) - (order?.applied_coupon?.value || 0)} /></span>
              ) : (<span className="font-semibold"><PriceDisplay price={(order?.order_total_amount ?? 0)} /></span>)}
            </p>

            <p className="flex items-center gap-2">
              <span className="text-gray-600 font-medium">Order Status:</span>
              <span className={`px-3 py-1 rounded-full text-sm font-semibold ${order?.order_status === "Delivered"
                ? "bg-green-100 text-green-700"
                : "bg-blue-100 text-blue-700"
                }`}>
                {order?.order_status}
              </span>
            </p>
          </div>

          {order?.applied_discount && order.applied_discount > 0 && (
            <div className="grid sm:grid-cols-2 gap-y-3">
              <p><span className="text-gray-600 font-medium ">Coupon: </span>
                <span className="font-semibold">{order?.applied_coupon?.code}</span>
              </p>

              <p className="flex items-center gap-2">
                <span className="text-gray-600 font-medium">Discount Amount:</span>
                <span className={`px-3 py-1 rounded-full text-sm font-semibold`} >
                  <PriceDisplay price={order?.applied_discount} />
                </span>
              </p>
            </div>
          )}


        </div>
      </div>
    );
  }



};

export default Page;
