import { useState, useEffect } from 'react';
import Modal from '../components/Modal';

type Props = {
    open: boolean;
    onClose: () => void;
    selectedCount: number;
    orderStatuses: any[];
    paymentStatuses: any[];
    onConfirmOrderStatus: (targetStatus: string) => void;
    onConfirmPaymentStatus: (targetStatus: string) => void;
};

const DEFAULT_ORDER_STATUSES = [
    { name: 'Confirmed', bgColor: '#3b82f6', textColor: '#ffffff' },
    { name: 'Processing', bgColor: '#f59e0b', textColor: '#ffffff' },
    { name: 'Packed', bgColor: '#a855f7', textColor: '#ffffff' },
    { name: 'Shipped', bgColor: '#0ea5e9', textColor: '#ffffff' },
    { name: 'Delivered', bgColor: '#10b981', textColor: '#ffffff' },
    { name: 'Cancelled', bgColor: '#6b7280', textColor: '#ffffff' },
];

const DEFAULT_PAYMENT_STATUSES = [
    { name: 'Paid', bgColor: '#10b981', textColor: '#ffffff' },
    { name: 'Pending', bgColor: '#f59e0b', textColor: '#ffffff' },
    { name: 'Unpaid', bgColor: '#ef4444', textColor: '#ffffff' },
    { name: 'Refunded', bgColor: '#6b7280', textColor: '#ffffff' },
];

const OrderStatusUpdateModal = ({
    open,
    onClose,
    selectedCount,
    orderStatuses,
    paymentStatuses,
    onConfirmOrderStatus,
    onConfirmPaymentStatus,
}: Props) => {
    const [activeTab, setActiveTab] = useState<'order' | 'payment'>('order');

    const orderStatusesToUse = Array.isArray(orderStatuses) && orderStatuses.length > 0
        ? orderStatuses.filter((s: any) => s.status !== false && s.status !== 0 && s.status !== '0')
        : DEFAULT_ORDER_STATUSES;
    const paymentStatusesToUse = Array.isArray(paymentStatuses) && paymentStatuses.length > 0
        ? paymentStatuses.filter((s: any) => s.status !== false && s.status !== 0 && s.status !== '0')
        : DEFAULT_PAYMENT_STATUSES;

    const [selectedOrderStatus, setSelectedOrderStatus] = useState<string>('');
    const [selectedPaymentStatus, setSelectedPaymentStatus] = useState<string>('');

    useEffect(() => {
        if (open) {
            if (orderStatusesToUse.length > 0) {
                setSelectedOrderStatus(orderStatusesToUse[0]?.name || '');
            }
            if (paymentStatusesToUse.length > 0) {
                setSelectedPaymentStatus(paymentStatusesToUse[0]?.name || '');
            }
        }
    }, [open, orderStatuses, paymentStatuses]);

    const handleSubmit = () => {
        if (activeTab === 'order') {
            if (!selectedOrderStatus) return;
            onConfirmOrderStatus(selectedOrderStatus);
        } else {
            if (!selectedPaymentStatus) return;
            onConfirmPaymentStatus(selectedPaymentStatus);
        }
        onClose();
    };

    const currentStatuses = activeTab === 'order' ? orderStatusesToUse : paymentStatusesToUse;
    const currentSelected = activeTab === 'order' ? selectedOrderStatus : selectedPaymentStatus;
    const setCurrentSelected = activeTab === 'order' ? setSelectedOrderStatus : setSelectedPaymentStatus;

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Bulk Status Update"
            width="md"
            footer={
                <div className="flex items-center gap-2">
                    <button
                        type="button"
                        onClick={onClose}
                        className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        onClick={handleSubmit}
                        disabled={!currentSelected || selectedCount === 0}
                        className="px-4 py-2 text-sm font-bold text-white bg-[#461901] hover:bg-[#5a2101] rounded-lg transition cursor-pointer disabled:opacity-50"
                    >
                        Update {activeTab === 'order' ? 'Order' : 'Payment'} Status ({selectedCount})
                    </button>
                </div>
            }
        >
            <div className="space-y-4 py-1">
                {/* Order Status / Payment Status Tabs */}
                <div className="flex border border-slate-200 rounded-xl p-1 bg-slate-100">
                    <button
                        type="button"
                        onClick={() => setActiveTab('order')}
                        className={`flex-1 py-2 text-center text-xs font-bold rounded-lg transition cursor-pointer ${
                            activeTab === 'order'
                                ? 'bg-[#461901] text-white shadow-xs'
                                : 'text-slate-600 hover:text-slate-900 hover:bg-slate-200/60'
                        }`}
                    >
                        Order Status
                    </button>
                    <button
                        type="button"
                        onClick={() => setActiveTab('payment')}
                        className={`flex-1 py-2 text-center text-xs font-bold rounded-lg transition cursor-pointer ${
                            activeTab === 'payment'
                                ? 'bg-[#461901] text-white shadow-xs'
                                : 'text-slate-600 hover:text-slate-900 hover:bg-slate-200/60'
                        }`}
                    >
                        Payment Status
                    </button>
                </div>

                <div className="p-3 bg-amber-50 border border-amber-200 rounded-xl text-xs text-amber-900 flex items-center justify-between">
                    <span>Selected Orders to Update:</span>
                    <span className="font-extrabold text-sm text-[#461901]">{selectedCount}</span>
                </div>

                <div>
                    <label className="block text-xs font-bold text-gray-700 uppercase tracking-wider mb-2">
                        Select Target {activeTab === 'order' ? 'Order' : 'Payment'} Status
                    </label>
                    <div className="grid grid-cols-2 gap-2.5">
                        {currentStatuses.map((status: any) => {
                            const isSelected = currentSelected === status.name;
                            const bg = status.bgColor || (activeTab === 'order' ? '#461901' : '#10b981');
                            const text = status.textColor || '#ffffff';

                            return (
                                <button
                                    key={status.name || status.id}
                                    type="button"
                                    onClick={() => setCurrentSelected(status.name)}
                                    className={`flex items-center justify-between p-3 rounded-xl border transition-all text-left cursor-pointer ${
                                        isSelected
                                            ? 'border-[#461901] bg-amber-50/80 ring-2 ring-[#461901]/30 shadow-sm'
                                            : 'border-slate-200 hover:border-slate-300 bg-white'
                                    }`}
                                >
                                    <span className="text-xs font-bold text-slate-800">
                                        {status.name}
                                    </span>
                                    <span
                                        className="px-2 py-0.5 rounded-full text-[10px] font-extrabold uppercase shadow-xs"
                                        style={{ backgroundColor: bg, color: text }}
                                    >
                                        {status.name}
                                    </span>
                                </button>
                            );
                        })}
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default OrderStatusUpdateModal;
