import { useState, useEffect } from "react";
import Swal from 'sweetalert2';
import { useNavigate, useParams } from "react-router-dom";
import IconSquareCheck from "../components/Icon/IconSquareCheck";
import IconCaretLeft from "../components/Icon/IconCaretLeft";
import IconMapPin from "../components/Icon/IconMapPin";
import IconChartSquare from "../components/Icon/IconChartSquare";
import IconTag from "../components/Icon/IconTag";
import { orderApi } from "../api/orderApi";

/* ── Types ─────────────────────────────────────────────── */
interface PatronOrder {
  dbId: string;
  code: string;
  date: string;
  patronName: string;
  address: string;
  status: string;
  product: {
    sku: string;
    name: string;
    category: string;
    image?: string;
    price: number;
    qty: number;
  };
}

/* ── Mock data removed, using dynamic API call ─────────────────── */


/* ── Confirmation Portal Page ───────────────────────────── */
const ConfirmOrderPortal = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [confirmed, setConfirmed] = useState(false);
  const [order, setOrder] = useState<PatronOrder | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [alreadyConfirmed, setAlreadyConfirmed] = useState(false);

  useEffect(() => {
    const fetchOrder = async () => {
      try {
        setLoading(true);
        if (!id) throw new Error("No Order ID provided");

        const res = await orderApi.getOrderByNo(id);
        if (res.success && res.data) {
          const dbOrder = res.data;
          const formatted: PatronOrder = {
            dbId: dbOrder.id.toString(),
            code: dbOrder.order_no,
            date: new Date(dbOrder.created_at || dbOrder.date || Date.now()).toLocaleDateString('en-US', { day: '2-digit', month: 'short' }).toUpperCase(),
            patronName: dbOrder.customer_name,
            address: dbOrder.shipping_address || 'No address provided',
            status: dbOrder.status,
            product: {
              sku: dbOrder.product?.product_code || dbOrder.product_id?.toString() || 'N/A',
              name: dbOrder.product?.name || dbOrder.product_name || 'Unknown Product',
              category: dbOrder.product?.category_id?.toString() || 'General',
              image: dbOrder.product?.image_url,
              price: Number(dbOrder.amount) / (Number(dbOrder.qty) || 1),
              qty: dbOrder.qty || 1,
            }
          };
          setOrder(formatted);
          if (dbOrder.status !== 'Pending') {
            setAlreadyConfirmed(true);
          }
        } else {
          setError("Order not found");
        }
      } catch (err: any) {
        console.error(err);
        setError("Failed to load order details");
      } finally {
        setLoading(false);
      }
    };

    fetchOrder();
  }, [id]);

  if (loading) {
    return (
      <div className="min-h-screen bg-[#EBEBEB] flex items-center justify-center">
        <div className="h-10 w-10 animate-spin rounded-full border-4 border-amber-500 border-t-transparent"></div>
      </div>
    );
  }

  if (error || !order) {
    return <div className="min-h-screen bg-[#EBEBEB] flex items-center justify-center font-bold text-rose-500">{error || "Order not found"}</div>;
  }

  const { product } = order;

  return (
    <div className="min-h-screen bg-[#EBEBEB] flex flex-col">

      {/* ── Top announcement bar ── */}
      <div className="bg-[#F5A623] w-full px-4 py-3 flex items-center justify-between gap-4 shrink-0">
        <div className="flex items-center gap-3 flex-1 min-w-0">
          {/* Dark pill label */}
          <div className="bg-[#0D0D0D] text-white text-[10px] font-extrabold tracking-widest uppercase px-4 py-1.5 rounded-full shrink-0 whitespace-nowrap select-none">
            GUEST VIEW
          </div>
          <p className="text-[12px] font-semibold text-[#1a0a00] leading-tight truncate">
            You are viewing the guest-facing Client Secure Invoice matching reference{" "}
            <span className="font-extrabold">{order.code}</span>.
            Approval updates this order to the packing lists in real-time.
          </p>
        </div>
        <button
          onClick={() => navigate('/manage_order')}
          className="shrink-0 flex items-center gap-1.5 bg-[#0D0D0D] hover:bg-[#222] text-white text-[11px] font-bold px-3.5 py-1.5 rounded-full transition-all cursor-pointer whitespace-nowrap"
        >
          <IconCaretLeft />
          Return to Dashboard
        </button>
      </div>

      {/* ── Centre card ── */}
      <div className="flex-1 flex items-center justify-center p-4">
        <div className="w-full max-w-lg">
          <div
            className="rounded-[22px] overflow-hidden shadow-2xl"
            style={{ boxShadow: "0 30px 80px -10px rgba(0,0,0,0.45)" }}
          >
            <div
              style={{
                background: "linear-gradient(160deg, #C8651A 0%, #7B1A0A 55%, #3D0A0A 100%)",
              }}
              className="px-6 pt-6 pb-7"
            >
              {/* Row: badge + code */}
              <div className="flex items-start justify-between mb-3">
                <span className="text-[9px] font-extrabold tracking-[0.18em] text-white/80 uppercase bg-white/10 px-2.5 py-1 rounded-full border border-white/15">
                  PATRON APPROVAL SUITE
                </span>
                <div className="text-right">
                  <div className="text-[11px] font-extrabold text-amber-300 tracking-widest">CODE: {order.code}</div>
                  <div className="text-[10px] text-white/60 tracking-wider mt-0.5">{order.date}</div>
                </div>
              </div>
              {/* Brand title */}
              <div className="mt-1">
                <div className="text-[22px] font-extrabold text-white tracking-tight leading-tight font-serif">
                  SHAS Jewels — Secure Client Invoice
                </div>
              </div>
            </div>

            {/* ── Card body (near-black) ── */}
            <div className="bg-[#111111] px-6 pb-6 pt-6 space-y-5">

              {/* Brand identity */}
              <div className="text-center py-2">
                <div className="text-[22px] font-extrabold tracking-[0.12em] text-amber-400 uppercase font-serif">
                  SHAS TRADITIONAL
                </div>
                <div className="text-[10px] tracking-[0.22em] text-slate-400 font-medium mt-1 uppercase">
                  Goldsmiths &amp; Diamantaires Since 1994
                </div>
              </div>

              {/* Greeting box */}
              <div className="bg-neutral-900/70 border border-[#2A2A2A] rounded-xl px-5 py-4 text-center">
                <p className="text-[13px] text-slate-300 leading-relaxed">
                  Greetings, patron{" "}
                  <span className="font-extrabold text-white">{order.patronName}!</span>{" "}
                  Your customised jewellery placement reservation has been prepared. Please verify and confirm details below:
                </p>
              </div>

              {/* Delivery address box */}
              <div className="bg-neutral-900/70 border border-[#2A2A2A] rounded-xl px-5 py-4 space-y-2">
                <div className="flex items-center gap-1.5 text-amber-400">
                  <IconMapPin />
                  <span className="text-[9px] font-extrabold tracking-[0.18em] uppercase">Insured Delivery Node</span>
                </div>
                <div className="text-[11px] text-slate-400 font-medium">Insured Priority Courier Deliver To:</div>
                <div className="text-[14px] font-bold text-white leading-snug">{order.address}</div>
              </div>

              {/* Proposed item box */}
              <div className="bg-neutral-900/70 border border-[#2A2A2A] rounded-xl px-5 py-4 space-y-4">
                <div className="flex items-center gap-1.5 text-amber-400">
                  <IconTag />
                  <span className="text-[9px] font-extrabold tracking-[0.18em] uppercase">Proposed Item</span>
                </div>

                {/* Product row */}
                <div className="bg-neutral-900/70 border border-[#333] rounded-xl p-3 flex items-center gap-3">
                  {/* Image / placeholder */}
                  <div className="w-14 h-14 rounded-lg bg-[#333] border border-[#444] flex-shrink-0 overflow-hidden flex items-center justify-center">
                    {product.image ? (
                      <img src={product.image} alt={product.name} className="w-full h-full object-cover" />
                    ) : (
                      <div className="text-slate-500 text-xs font-bold text-center px-1 leading-tight">
                        {product.name.slice(0, 2).toUpperCase()}
                      </div>
                    )}
                  </div>
                  <div>
                    <div className="text-[10px] font-mono font-bold text-amber-500 tracking-widest mb-0.5">{product.sku}</div>
                    <div className="text-[15px] font-extrabold text-white leading-tight">{product.name}</div>
                    <div className="text-[11px] text-slate-400 mt-0.5">{product.category}</div>
                  </div>
                </div>
                <div className="space-y-2.5 pt-1">
                  <div className="flex items-center justify-between text-[12.5px]">
                    <span className="text-slate-400 font-medium">Bespoke Value ({product.qty} Unit)</span>
                    <span className="text-white font-bold font-mono">₹ {product.price.toLocaleString("en-IN")}</span>
                  </div>
                  <div className="flex items-center justify-between text-[12.5px]">
                    <span className="text-slate-400 font-medium">Shipping</span>
                    <span className="text-emerald-400 font-extrabold text-[11px] tracking-widest uppercase">Free</span>
                  </div>
                  <div className="border-t border-[#2A2A2A] pt-2.5 flex items-center justify-between">
                    <span className="text-amber-400 font-extrabold text-[13px]">Total Secured Due</span>
                    <span className="text-amber-400 font-extrabold text-[18px] font-mono">₹{(product.price * product.qty).toLocaleString("en-IN")}</span>
                  </div>
                </div>
              </div>

              {/* CTA button */}
              {alreadyConfirmed ? (
                <div className="w-full flex flex-col items-center justify-center p-5 bg-slate-500/10 rounded-xl border border-slate-500/20 text-center space-y-2">
                  <div className="text-[14px] font-extrabold text-slate-400 uppercase tracking-widest">Link Expired</div>
                  <div className="text-center">
                    <p className="text-[10px] text-slate-500 leading-relaxed">This confirmation link has expired because the order has already been processed.</p>
                  </div>
                </div>
              ) : !confirmed ? (
                <button
                  onClick={async () => {
                    if (submitting) return;
                    setSubmitting(true);
                    try {
                      await orderApi.updateOrder(order.dbId, { status: 'Confirmed' });
                      setConfirmed(true);
                    } catch (err) {
                      console.error("Failed to confirm order", err);
                      // Fallback: still show as confirmed visually if you want, or show error alert
                      Swal.fire({
                        icon: 'error',
                        title: 'Something went wrong while confirming. Please try again.',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 3000,
                        padding: '10px 20px',
                      });
                    } finally {
                      setSubmitting(false);
                    }
                  }}
                  disabled={submitting}
                  className={`w-full flex items-center justify-center gap-2 py-4 rounded-xl text-[14px] font-extrabold tracking-wide text-amber-300 transition-all cursor-pointer ${submitting ? 'opacity-75 cursor-not-allowed' : 'active:scale-[0.98]'}`}
                  style={{
                    background: "linear-gradient(90deg, #8B0000 0%, #A61010 50%, #8B0000 100%)",
                    boxShadow: "0 4px 24px -4px rgba(139,0,0,0.6)",
                  }}
                >
                  <IconSquareCheck />
                  Verify &amp; Confirm Placement
                </button>
              ) : (
                <div className="w-full flex flex-col items-center justify-center p-4 bg-emerald-500/10 rounded-xl border border-emerald-500/20 text-center space-y-2">
                  <div className=" flex items-center justify-center gap-2">
                    <IconSquareCheck className="text-emerald-400" />
                    <span className="text-[14px] font-extrabold text-emerald-400">Placement Confirmed!</span>
                  </div>
                  <div className="text-center">
                    <p className="text-[10px] text-slate-400 leading-relaxed">Your reservation has been approved and moved to certified packing queue. Thank you for your patronage!</p>
                  </div>
                </div>
              )}

              {/* Fine print */}
              <p className="text-center text-[9px] tracking-[0.14em] text-slate-600 uppercase leading-relaxed pt-1">
                By confirming description metrics, you verify the courier coordinates<br />above are exact.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConfirmOrderPortal;