"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import Image from "next/image";
import OrderConfirmation from "@/components/OrderConfirmation";
import BillingInfoDeliveryLocationCards, {
    type BillingLocationCardFields,
} from "@/components/BillingInfoDeliveryLocationCards";
import staticCopy from "@/i18n/staticCopy.json";
import {
    DEFAULT_LOCALE,
    getStoredLocale,
    LOCALE_CHANGE_EVENT,
    type LocaleCode,
} from "@/i18n/localeSwitcher";

type OrderConfirmationCopy =
    (typeof staticCopy.orderConfirmation)[keyof typeof staticCopy.orderConfirmation];


type ConfirmationItem = {
    id?: string;
    title?: string;
    subtitle?: string;
    image?: string;
    product_type?: string;
    product_waste_type?: string;
    tag?: string;
    tags?: string[];
    code?: string;
    quantity?: number;
    quantity_label?: string;
    quantity_unit?: string;
    frequency?: string;
    location?: string;
    unit_price?: number;
    unit_price_label?: string;
    line_total?: number;
    line_total_label?: string;
};

type ConfirmationData = {
    order?: {
        id?: string;
        order_number?: string;
        order_date?: { iso?: string; display?: string };
        expected_delivery?: string | null;
        status?: string;
        status_label?: string;
        payment_status?: string;
        payment_status_label?: string;
        transaction_id?: string;
        payment_method?: {
            provider_id?: string;
            label?: string;
            payment_intent_id?: string;
            payment_method_id?: string;
            brand?: string | null;
            last4?: string | null;
        };
        payment_card_brand?: string | null;
        payment_card_last4?: string | null;
    };
    summary?: {
        currency_code?: string;
        currency_symbol?: string;
        items?: ConfirmationItem[];
        item?: ConfirmationItem;
        subtotal?: number;
        subtotal_label?: string;
        subtotal_display_label?: string;
        vat_amount?: number;
        vat_amount_label?: string;
        vat_display_label?: string;
        shipping_amount?: number;
        shipping_amount_label?: string;
        shipping_display_label?: string;
        total_paid?: number;
        total_paid_label?: string;
        total_paid_display_label?: string;
        tax_rate?: number | null;
        tax_rate_label?: string | null;
        vat?: {
            amount?: number;
            amount_label?: string;
            rate?: number | null;
            rate_label?: string | null;
            display_label?: string;
        };
    };
    billing_information?: {
        company_name?: string;
        full_name?: string;
        vat_number?: string;
        country?: string;
        address_line?: string;
        city_line?: string;
        email?: string;
        phone?: string;
        display_label?: string;
    };
    service_location?: {
        company_name?: string;
        full_name?: string;
        country?: string;
        address_line?: string;
        city_line?: string;
        email?: string;
        phone?: string;
        shipping_method?: string;
        display_label?: string;
    };
    documents?: {
        invoice_url?: string;
        receipt_url?: string;
        email_receipt_url?: string;
    };
};

type MedusaOrder = {
    id: string;
    display_id: number;
    currency_code: string;
    subtotal: number;
    tax_total: number;
    shipping_total: number;
    total: number;
    items?: Array<{
        id: string;
        title: string;
        quantity: number;
        unit_price: number;
        metadata?: Record<string, unknown>;
    }>;
    shipping_methods?: Array<{ name: string; amount: number }>;
};

function formatMoney(amount: number, currency: string) {
    const sym = currency.toLowerCase() === "eur" ? "€" : currency.toUpperCase() + " ";
    return `${sym}${Number(amount).toFixed(2)}`;
}

function parseMoney(label: string): number {
    if (!label) return 0;
    const cleaned = label.replace(/[€$£¥]/g, '').replace(/,/g, '').trim();
    const parsed = parseFloat(cleaned);
    return isNaN(parsed) ? 0 : parsed;
}


function mapItemToSummaryItem(item: ConfirmationItem, copy: OrderConfirmationCopy) {
    const frequency = item.frequency ?? "";
    const isRecurring =
        frequency.toLowerCase().includes("month") ||
        frequency.toLowerCase().includes("recurring");
    const priceUnit = isRecurring ? copy.priceUnitPerMonth : (item.quantity_unit?.trim() || copy.priceUnitTotal);

    const rawCode = item.code ?? "";
    const lerCode = rawCode.includes(" - ")
        ? rawCode.split(" - ")[0].trim()
        : item.product_type?.trim() || rawCode.trim();

    return {
        image: item.image?.trim() || "/placeholder-product-1.jpg",
        productName: item.title ?? "",
        lerCode,
        quantity: item.quantity_label ?? String(item.quantity ?? ""),
        frequency,
        location: item.location ?? "",
        price: item.line_total_label ?? item.unit_price_label ?? "",
        priceUnit,
        subtitle: item.subtitle ?? "",
        productWasteType: item.product_waste_type ?? "",
        tags: item.tags ?? (item.tag ? [item.tag] : []),
    };
}

function buildBillingFields(
    bi: ConfirmationData["billing_information"],
    copy: OrderConfirmationCopy
): BillingLocationCardFields {
    if (!bi) return {};
    const address = [bi.address_line, bi.city_line].filter(Boolean).join(", ") || bi.display_label || "";
    return {
        companySubText: bi.full_name || bi.company_name,
        companyName: bi.vat_number ? `${copy.vatLabelPrefix}${bi.vat_number}` : bi.company_name,
        address,
        email: bi.email,
        phone: bi.phone,
    };
}

function buildDeliveryFields(sl: ConfirmationData["service_location"]): BillingLocationCardFields {
    if (!sl) return {};
    const address = [sl.address_line, sl.city_line].filter(Boolean).join(", ") || sl.display_label || "";
    return {
        companySubText: sl.full_name || sl.company_name,
        companyName: sl.shipping_method || sl.company_name,
        address,
        email: sl.email,
        phone: sl.phone,
    };
}


interface OrderConfirmationSectionProps {
    onDocumentsLoaded?: (documents: { invoice_url?: string; receipt_url?: string; email_receipt_url?: string }, orderId: string) => void;
}

export default function OrderConfirmationSection({ onDocumentsLoaded }: OrderConfirmationSectionProps) {
    const searchParams = useSearchParams();
    const orderId = searchParams.get("orderId") ?? searchParams.get("order_id") ?? "";

    const [data, setData] = useState<ConfirmationData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);
    const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

    const t =
        staticCopy.orderConfirmation[uiLocale as keyof typeof staticCopy.orderConfirmation] ??
        staticCopy.orderConfirmation["en-EN"];

    useEffect(() => {
        const syncLocale = () => setUiLocale(getStoredLocale());
        syncLocale();
        window.addEventListener("storage", syncLocale);
        window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        return () => {
            window.removeEventListener("storage", syncLocale);
            window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        };
    }, []);

    useEffect(() => {
        if (!orderId) {
            setLoading(false);
            return;
        }

        async function fetchConfirmation() {
            try {
                const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
                if (!base) { setLoading(false); return; }

                const headers: Record<string, string> = {
                    "Content-Type": "application/json",
                    "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                };

                try {
                    const raw = localStorage.getItem("currentUser");
                    const user = raw ? JSON.parse(raw) : null;
                    const token = String(user?.token ?? user?.access_token ?? "").trim();
                    if (token) headers["Authorization"] = `Bearer ${token}`;
                } catch {  }

                const res = await fetch(
                    `${base}/store/orders/${encodeURIComponent(orderId)}/confirmation`,
                    { headers, cache: "no-store" }
                );

                if (!res.ok) {
                    setError(true);
                    setLoading(false);
                    return;
                }

                const json: ConfirmationData = await res.json();

                const hasZeroValues = 
                    (json.summary?.subtotal_label === "€0.00" || json.summary?.subtotal === 0) &&
                    (json.summary?.vat_amount_label === "€0.00" || json.summary?.vat_amount === 0) &&
                    (json.summary?.shipping_amount_label === "€0.00" || json.summary?.shipping_amount === 0);
                
                if (hasZeroValues) {
                    try {
                        const orderRes = await fetch(
                            `${base}/store/orders/${encodeURIComponent(orderId)}`,
                            { headers, cache: "no-store" }
                        );
                        if (orderRes.ok) {
                            const orderData = await orderRes.json() as { order?: MedusaOrder };
                            if (orderData.order) {
                                const order = orderData.order;
                                const currency = order.currency_code ?? "eur";
                                const shippingAmount = order.shipping_methods?.[0]?.amount ?? order.shipping_total ?? 0;
                                
                                if (json.summary) {
                                    json.summary.subtotal_label = formatMoney(order.subtotal, currency);
                                    json.summary.vat_amount_label = formatMoney(order.tax_total, currency);
                                    json.summary.shipping_amount_label = formatMoney(shippingAmount, currency);
                                    json.summary.total_paid_label = formatMoney(order.total, currency);
                                }
                            }
                        }
                    } catch (fallbackErr) {
                    }
                }
                
                setData(json);
                
                if (onDocumentsLoaded && json.documents && orderId) {
                    onDocumentsLoaded(json.documents, orderId);
                }
            } catch {
                setError(true);
            } finally {
                setLoading(false);
            }
        }

        fetchConfirmation();
    }, [orderId, onDocumentsLoaded]);
    
    if (loading) {
        return (
            <div className="flex flex-col gap-[30px] md:gap-[50px]">
                {[1, 2, 3].map((i) => (
                    <div
                        key={i}
                        className="h-[160px] rounded-[20px] bg-[#F7FAF8] border border-[#DAE6DC] animate-pulse"
                    />
                ))}
            </div>
        );
    }

    if (error || !data) {
        return (
            <div className="rounded-[20px] bg-[#FEF2F2] border border-red-200 p-6 text-center">
                <p className="font-outfit text-red-600">{t.loadError}</p>
            </div>
        );
    }

    const { order: oc, summary, billing_information, service_location } = data;

    const brand = oc?.payment_card_brand ?? oc?.payment_method?.brand;
    const last4 = oc?.payment_card_last4 ?? oc?.payment_method?.last4;
    const paymentMethodLabel = brand && last4
        ? `${brand.charAt(0).toUpperCase() + brand.slice(1)} ${t.paymentEndingIn} ${last4}`
        : oc?.payment_method?.label ?? "";

    const rawItems: ConfirmationItem[] =
        Array.isArray(summary?.items) && summary!.items!.length > 0
            ? summary!.items!
            : summary?.item
                ? [summary.item]
                : [];
    const orderSummaryItems = rawItems.map((item) => mapItemToSummaryItem(item, t));

    const subtotalLabel = summary?.subtotal_label ?? "";
    const vatLabel = summary?.vat_amount_label ?? summary?.vat?.amount_label ?? "";
    const shippingLabel = summary?.shipping_amount_label ?? undefined;
    const totalPaidLabel = summary?.total_paid_label ?? "";
    const rateRaw = summary?.vat?.rate_label ?? summary?.tax_rate_label;
    const vatPercentLabel = (rateRaw != null && String(rateRaw).trim() !== "") ? String(rateRaw) : t.defaultVatRate;

    const subtotalAmount = parseMoney(subtotalLabel);
    const shippingAmount = parseMoney(shippingLabel ?? "");
    const totalExclVatAmount = subtotalAmount + shippingAmount;
    const currencyCode = summary?.currency_code ?? "eur";
    const totalExclVatLabel = formatMoney(totalExclVatAmount, currencyCode);

    const billingFields = buildBillingFields(billing_information, t);
    const deliveryFields = buildDeliveryFields(service_location);

    return (
        <div className="flex flex-col gap-[30px] md:gap-[50px]">
            <OrderConfirmation
                orderNumber={oc?.order_number}
                orderDate={oc?.order_date?.display}
                paymentMethod={paymentMethodLabel}
                transactionId={oc?.transaction_id}
            />

            <section className="bg-[#F7FAF8] rounded-[20px] border border-[#DAE6DC] px-6 py-7 md:p-[15px_30px] font-outfit shadow-xl">
                <h4 className="font-outfit font-medium text-[#053F31] mb-[10px] pb-[10px] border-b border-[#DAE6DC]">
                    {t.sectionOrderSummary}
                </h4>
                <div>
                    {orderSummaryItems.map((item, idx) => (
                        <div key={idx} className="py-5 border-b border-[#000000]/10 last:border-b-0">
                            <div className="flex items-start gap-3">
                                <div className="relative h-[90px] w-[90px] md:h-[152px] md:w-[152px] shrink-0 overflow-hidden rounded-[12px]">
                                    <Image
                                        src={item.image}
                                        alt={item.productName}
                                        fill
                                        className="object-cover"
                                        unoptimized
                                    />
                                </div>
                                <div className="flex flex-1 flex-col md:flex-row md:items-start md:justify-between gap-2 md:gap-4 min-w-0">
                                    <div className="min-w-0">
                                        <span className="font-outfit text-[16px] md:text-[18px] font-normal text-[#000000] mb-[5px] block">
                                            {item.productName}
                                        </span>
                                        <div className="flex flex-col space-y-[4px] mt-[5px]">
                                            {item.lerCode && (
                                                <p className="font-outfit text-[14px] md:text-[16px] text-[#757575] font-light">
                                                    <span className="font-light text-[#000000]">{t.lerCode}</span>
                                                    {item.lerCode}
                                                </p>
                                            )}
                                            <p className="font-outfit text-[14px] md:text-[16px] text-[#757575] font-light">
                                                <span className="font-light text-[#000000]">{t.quantity}</span>
                                                {item.quantity}
                                            </p>
                                            <p className="font-outfit text-[14px] md:text-[16px] text-[#757575] font-light">
                                                <span className="font-light text-[#000000]">{t.frequency}</span>
                                                {item.frequency}
                                            </p>
                                            <p className="font-outfit text-[14px] md:text-[16px] text-[#757575] font-light">
                                                <span className="font-light text-[#000000]">{t.location}</span>
                                                {item.location}
                                            </p>
                                        </div>
                                    </div>  
                                    <div className="flex items-baseline shrink-0 md:text-right mt-1">
                                        <p className="font-outfit text-[18px] md:text-[22px] font-semibold">{item.price}</p>
                                        <span className="font-outfit text-[14px] md:text-[16px] font-light">/{item.priceUnit}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>

                <div className="border-t border-[#053F31]/50 pt-2 flex flex-col gap-2 mt-2">
                    <div className="flex items-center justify-between">
                        <span className="font-outfit text-[16px] font-normal text-[#333333]">{t.subtotal}</span>
                        <span className="font-outfit !text-[20px] font-semibold text-[#053F31]">{subtotalLabel}</span>
                    </div>
                    {shippingLabel && (
                        <div className="flex items-center justify-between">
                            <span className="font-outfit text-[16px] font-normal text-[#333333]">{t.transportCost}</span>
                            <span className="font-outfit !text-[20px] font-semibold text-[#053F31]">{shippingLabel}</span>
                        </div>
                    )}
                    <div className="border-t border-[#D9D9D9] my-1" />
                    <div className="flex items-center justify-between">
                        <span className="font-outfit text-[16px] font-normal text-[#333333]">{t.totalExclVat}</span>
                        <span className="font-outfit !text-[20px] font-semibold text-[#053F31]">{totalExclVatLabel}</span>
                    </div>
                    <div className="flex items-center justify-between">
                        <span className="font-outfit text-[16px] font-normal text-[#333333]">
                           {t.vatPlus}{vatPercentLabel ? ` (${vatPercentLabel})` : ""}
                        </span>
                        <span className="font-outfit !text-[20px] font-semibold text-[#053F31]">{vatLabel}</span>
                    </div>
                    <div className="border-t border-[#D9D9D9] my-1" />
                    <div className="flex items-center justify-between">
                        <span className="font-outfit text-[16px] font-normal text-[#000000]">{t.grandTotal}</span>
                        <h3 className="font-outfit text-[22px] font-bold text-[#053F31]">{totalPaidLabel}</h3>
                    </div>
                </div>
            </section>

            <BillingInfoDeliveryLocationCards
                billing={billingFields}
                delivery={deliveryFields}
            />
        </div>
    );
}
