import React, { useEffect, useState } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { api } from '@/lib/api/client';
import { toast } from 'sonner';
import SubscriptionTimeline from '../../components/SubscriptionTimeline';

// Define types based on CheckoutController response
// Define types based on CheckoutController response
interface BaseResponse {
    ok?: boolean;
    error?: string;
}

interface OrderDetailsResponse extends BaseResponse {
    id: number;
    number: string;
    status: string;
    created_via: string;
    total: number;
    currency: string;
    currency_symbol: string;
    items: Array<{
        id: number;
        name: string;
        qty: number;
        total: number;
        image?: string;
    }>;
    available_gateways: Array<{
        id: string;
        title: string;
        description: string;
        icon?: string;
    }>;
    subscription?: {
        id: number;
        status: string;
        billing_period: string;
        billing_interval: number;
        start_date: string;
        next_payment_date: string | null;
        end_date: string | null;
    };
}

interface PaymentResponse extends BaseResponse {
    redirect?: string;
    messages?: string;
}

const OrderPay: React.FC = () => {
    const { orderId } = useParams<{ orderId: string }>();
    const [searchParams] = useSearchParams();
    const orderKey = searchParams.get('key');
    // const navigate = useNavigate();

    const [order, setOrder] = useState<OrderDetailsResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const [selectedGateway, setSelectedGateway] = useState<string>('');
    const [processing, setProcessing] = useState(false);

    useEffect(() => {
        if (orderId) {
            fetchOrder();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [orderId]);

    const fetchOrder = async () => {
        try {
            const endpoint = `/checkout/order/${orderId}${orderKey ? `?key=${orderKey}` : ''}`;
            const response = await api.get<OrderDetailsResponse>(endpoint);

            if (response.error) {
                toast.error(response.error);
                return;
            }
            if (response.ok) {
                setOrder(response as OrderDetailsResponse);
                if (response.available_gateways?.length > 0) {
                    setSelectedGateway(response.available_gateways[0].id);
                }
            }
        } catch (error) {
            console.error('Failed to fetch order', error);
            toast.error('Failed to load order details');
        } finally {
            setLoading(false);
        }
    };

    const handlePayment = async () => {
        if (!selectedGateway) {
            toast.error('Please select a payment method');
            return;
        }

        setProcessing(true);
        try {
            const response = await api.post<PaymentResponse>(`/checkout/pay-order/${orderId}`, {
                payment_method: selectedGateway,
                key: orderKey
            });

            if (response.ok && response.redirect) {
                window.location.href = response.redirect;
            } else {
                toast.error(response.error || 'Payment failed');
            }
        } catch (error) {
            console.error('Payment error', error);
            toast.error('An error occurred while processing payment');
        } finally {
            setProcessing(false);
        }
    };

    // Helper to format price with proper currency locale
    const formatPrice = (amount: number, currency: string) => {
        try {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: currency,
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
            }).format(amount);
        } catch {
            // Fallback
            return `${currency} ${amount.toFixed(0)}`;
        }
    };

    if (loading) return <div className="p-8 text-center">Loading order details...</div>;
    if (!order) return <div className="p-8 text-center text-red-500">Order not found</div>;

    const isRenewal = order.created_via === 'subscription_renewal';

    return (
        <div className="max-w-3xl mx-auto p-6">
            <h1 className="text-2xl font-bold mb-6">Complete Payment</h1>

            {order.subscription && (
                <SubscriptionTimeline subscription={order.subscription} />
            )}

            {isRenewal && !order.subscription && (
                <div className="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6">
                    <div className="flex">
                        <div className="flex-shrink-0">
                            <svg className="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                            </svg>
                        </div>
                        <div className="ml-3">
                            <p className="text-sm text-blue-700">
                                This is a payment for your <span className="font-bold">subscription renewal</span>.
                                Completing this payment will extend your subscription period.
                            </p>
                        </div>
                    </div>
                </div>
            )}

            <div className="bg-white rounded-lg shadow p-6 mb-6">
                <h2 className="text-xl font-semibold mb-4">Order Summary <span className="text-gray-400 font-normal">#{order.number}</span></h2>
                <div className="space-y-4">
                    {order.items.map((item) => (
                        <div key={item.id} className="flex justify-between items-center border-b pb-4 last:border-0 last:pb-0">
                            <div className="flex items-center gap-4">
                                {item.image ? (
                                    <img src={item.image} alt={item.name} className="w-16 h-16 object-cover rounded bg-gray-100" />
                                ) : (
                                    <div className="w-16 h-16 bg-gray-100 rounded flex items-center justify-center text-gray-400">
                                        <span className="text-xs">No img</span>
                                    </div>
                                )}
                                <div>
                                    <div className="font-medium text-lg">{item.name}</div>
                                    <div className="text-sm text-gray-500">Qty: {item.qty}</div>
                                </div>
                            </div>
                            <div className="font-medium text-lg">
                                {formatPrice(item.total, order.currency)}
                            </div>
                        </div>
                    ))}

                    <div className="border-t pt-4 mt-4">
                        <div className="flex justify-between items-center text-gray-600 mb-2">
                            <span>Subtotal</span>
                            <span>{formatPrice(order.total, order.currency)}</span>
                        </div>
                        <div className="flex justify-between items-center font-bold text-xl mt-4">
                            <span>Total to Pay</span>
                            <span className="text-primary">{formatPrice(order.total, order.currency)}</span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-xl font-semibold mb-4">Select Payment Method</h2>

                {order.available_gateways.length === 0 ? (
                    <div className="p-4 bg-yellow-50 text-yellow-700 rounded-md border border-yellow-200">
                        No payment methods are available for this order. Please contact support.
                    </div>
                ) : (
                    <div className="space-y-3 mb-6">
                        {order.available_gateways.map((gateway) => (
                            <label
                                key={gateway.id}
                                className={`flex items-start p-4 border rounded-lg cursor-pointer transition-all ${selectedGateway === gateway.id
                                    ? 'border-primary bg-primary/5 ring-1 ring-primary'
                                    : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                                    }`}
                            >
                                <div className="flex items-center h-5">
                                    <input
                                        type="radio"
                                        name="payment_method"
                                        value={gateway.id}
                                        checked={selectedGateway === gateway.id}
                                        onChange={(e) => setSelectedGateway(e.target.value)}
                                        className="h-4 w-4 text-primary border-gray-300 focus:ring-primary"
                                    />
                                </div>
                                <div className="ml-3 text-sm">
                                    <span className="block font-medium text-gray-900 text-base">
                                        {gateway.title || gateway.id}
                                    </span>
                                    {gateway.description && (
                                        <span className="block text-gray-500 mt-1">
                                            {gateway.description}
                                        </span>
                                    )}
                                </div>
                            </label>
                        ))}
                    </div>
                )}

                <button
                    onClick={handlePayment}
                    disabled={processing || !selectedGateway}
                    className="w-full bg-primary text-primary-foreground py-4 px-6 rounded-lg font-bold text-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"
                >
                    {processing ? 'Processing Payment...' : `Pay ${formatPrice(order.total, order.currency)}`}
                </button>
            </div>
        </div>
    );
};

export default OrderPay;
