'use client'
import { useState, useEffect } from 'react'
import { Truck, Sort, Flash } from 'iconsax-react'
import { ShopShippingType, ShipmentInfoType } from '../types/Types'

interface ShippingMethodSelectorProps {
    shippingData: ShopShippingType[]
    selectedShipments: Record<string, number>
    onShipmentSelect: (shopId: string, shipperId: number) => void
    onClearSelections?: () => void
}

const ShippingMethodSelector = ({
    shippingData,
    selectedShipments,
    onShipmentSelect,
    onClearSelections
}: ShippingMethodSelectorProps) => {
    const selectedCount = Object.keys(selectedShipments).length
    const totalShops = shippingData?.length || 0

    // State برای مرتب‌سازی
    const [sortBy, setSortBy] = useState<'price' | 'time' | 'default'>('default')
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc')

    // State برای collapse/expand محصولات
    const [expandedShops, setExpandedShops] = useState<Set<string>>(new Set())

    // تابع مرتب‌سازی روش‌های ارسال
    const sortShippers = (shippers: any[]) => {
        if (sortBy === 'default') return shippers

        return [...shippers].sort((a, b) => {
            let aValue, bValue

            if (sortBy === 'price') {
                aValue = a.totalShippingCost
                bValue = b.totalShippingCost
            } else if (sortBy === 'time') {
                aValue = a.shippingDaysRange?.[0] || 0
                bValue = b.shippingDaysRange?.[0] || 0
            }

            if (sortOrder === 'asc') {
                return aValue - bValue
            } else {
                return bValue - aValue
            }
        })
    }

    // هندلر تغییر مرتب‌سازی
    const handleSortChange = (newSortBy: 'price' | 'time' | 'default') => {
        if (sortBy === newSortBy) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
        } else {
            setSortBy(newSortBy)
            setSortOrder('asc')
        }
    }

    // هندلر toggle محصولات فروشگاه
    const toggleShopExpansion = (shopId: string) => {
        const newExpanded = new Set(expandedShops)
        if (newExpanded.has(shopId)) {
            newExpanded.delete(shopId)
        } else {
            newExpanded.add(shopId)
        }
        setExpandedShops(newExpanded)
    }

    // هندلر انتخاب سریع بهترین روش ارسال برای همه فروشگاه‌ها
    const handleQuickSelect = (criteria: 'cheapest' | 'fastest') => {
        const newSelections: Record<string, number> = {}

        shippingData?.forEach((shop) => {
            if (shop.shippers && shop.shippers.length > 0) {
                let bestShipper = shop.shippers[0]

                shop.shippers.forEach((shipper) => {
                    if (criteria === 'cheapest') {
                        if (shipper.totalShippingCost < bestShipper.totalShippingCost) {
                            bestShipper = shipper
                        }
                    } else if (criteria === 'fastest') {
                        const shipperTime = shipper.shippingDaysRange?.[0] || 999
                        const bestTime = bestShipper.shippingDaysRange?.[0] || 999
                        if (shipperTime < bestTime) {
                            bestShipper = shipper
                        }
                    }
                })

                newSelections[shop.shopId] = bestShipper.shipperId
            }
        })

        // اعمال انتخاب‌ها
        Object.entries(newSelections).forEach(([shopId, shipperId]) => {
            onShipmentSelect(shopId, shipperId)
        })
    }

    return (
        <div className="mt-5 border border-border rounded-2xl p-4 sm:p-6">
            <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                    <Truck size={20} color="#333333" />
                    <div>
                        <h3 className="text-lg font-semibold">روش ارسال</h3>
                        <p className="text-sm text-gray-600">
                            {selectedCount} از {totalShops} فروشگاه انتخاب شده
                        </p>
                        {selectedCount > 0 && (
                            <p className="text-sm text-gray-600">
                                مجموع ارسال: {Object.entries(selectedShipments).reduce((total, [shopId, shipperId]) => {
                                    const shop = shippingData?.find(s => s.shopId === shopId)
                                    const shipper = shop?.shippers?.find(s => s.shipperId === shipperId)
                                    return total + (shipper?.totalShippingCost || 0)
                                }, 0).toLocaleString('fa-IR')} تومان
                            </p>
                        )}
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {/* انتخاب سریع */}
                    <div className="flex items-center gap-1">
                        <Flash size={16} color="#666" />
                        <div className="flex gap-1">
                            <button
                                onClick={() => handleQuickSelect('cheapest')}
                                className="text-xs bg-green-100 hover:bg-green-200 text-green-800 px-2 py-1 rounded transition-colors"
                                title="انتخاب ارزان‌ترین روش برای همه فروشگاه‌ها"
                            >
                                ارزان‌ترین
                            </button>
                            <button
                                onClick={() => handleQuickSelect('fastest')}
                                className="text-xs bg-blue-100 hover:bg-blue-200 text-blue-800 px-2 py-1 rounded transition-colors"
                                title="انتخاب سریع‌ترین روش برای همه فروشگاه‌ها"
                            >
                                سریع‌ترین
                            </button>
                        </div>
                    </div>

                    {/* کنترل‌های مرتب‌سازی */}
                    <div className="flex items-center gap-1">
                        <Sort size={16} color="#666" />
                        <select
                            value={`${sortBy}-${sortOrder}`}
                            onChange={(e) => {
                                const [newSortBy, newSortOrder] = e.target.value.split('-') as ['price' | 'time' | 'default', 'asc' | 'desc']
                                setSortBy(newSortBy)
                                setSortOrder(newSortOrder)
                            }}
                            className="text-sm border border-gray-300 rounded px-2 py-1 bg-white"
                        >
                            <option value="default-asc">پیش‌فرض</option>
                            <option value="price-asc">ارزان‌ترین</option>
                            <option value="price-desc">گران‌ترین</option>
                            <option value="time-asc">سریع‌ترین</option>
                            <option value="time-desc">آهسته‌ترین</option>
                        </select>
                    </div>

                    {onClearSelections && Object.keys(selectedShipments).length > 0 && (
                        <button
                            onClick={onClearSelections}
                            className="text-sm text-red-600 hover:text-red-800 font-medium px-3 py-1 rounded-md hover:bg-red-50 transition-colors"
                        >
                            پاک کردن انتخاب‌ها
                        </button>
                    )}
                </div>
            </div>

            <div className="space-y-6">
                {shippingData?.map((shop) => (
                    <div key={shop.shopId} className="border border-gray-200 rounded-lg p-4">
                        <div className="flex items-center justify-between mb-4">
                            <div>
                                <h4 className="font-medium text-gray-900 text-lg">{shop.shopName}</h4>
                                <p className="text-sm text-gray-600">
                                    {shop.items?.length || 0} محصول
                                </p>
                            </div>
                            {selectedShipments[shop.shopId] && (
                                <div className="flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                                    <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                    انتخاب شد
                                </div>
                            )}
                        </div>

                        {/* نمایش محصولات فروشگاه */}
                        <div className="mb-6">
                            <button
                                onClick={() => toggleShopExpansion(shop.shopId)}
                                className="flex items-center justify-between w-full text-sm font-medium text-gray-700 mb-3 hover:text-gray-900 transition-colors"
                            >
                                <span>محصولات این فروشگاه ({shop.items?.length || 0})</span>
                                <svg
                                    className={`w-4 h-4 transition-transform ${expandedShops.has(shop.shopId) ? 'rotate-180' : ''}`}
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                </svg>
                            </button>
                            {expandedShops.has(shop.shopId) && (
                                <div className="space-y-3 max-h-48 overflow-y-auto">
                                    {shop.items?.map((item, index) => (
                                        <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-100">
                                            <img
                                                src={item.product.imagesUrl.cover}
                                                alt={item.product.title_fa}
                                                className="w-12 h-12 object-cover rounded-lg flex-shrink-0"
                                            />
                                            <div className="flex-1 min-w-0">
                                                <div className="text-sm font-medium text-gray-900 truncate mb-1">
                                                    {item.product.title_fa}
                                                </div>
                                                <div className="flex items-center justify-between">
                                                    <div className="text-xs text-gray-600">
                                                        تعداد: {item.quantity}
                                                    </div>
                                                    <div className="text-sm font-semibold text-gray-900">
                                                        {item.variant.price.selling_price.toLocaleString('fa-IR')} تومان
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* روش‌های ارسال */}
                        <div>
                            <h5 className="text-sm font-medium text-gray-700 mb-3">روش ارسال:</h5>
                            <div className="space-y-2">
                                {(() => {
                                    const shippers = sortShippers(shop.shippers || [])
                                    const cheapestPrice = Math.min(...shippers.map(s => s.totalShippingCost))

                                    return shippers.map((shipper) => {
                                        const priceDifference = shipper.totalShippingCost - cheapestPrice
                                        const isCheapest = priceDifference === 0

                                        return (
                                            <label
                                                key={shipper.shipperId}
                                                className={`flex items-center justify-between p-3 border rounded-lg cursor-pointer transition-colors ${selectedShipments[shop.shopId] === shipper.shipperId
                                                        ? 'border-primary bg-primary/5'
                                                        : 'border-gray-200 hover:bg-gray-50'
                                                    }`}
                                            >
                                                <div className="flex items-center gap-3">
                                                    <input
                                                        type="radio"
                                                        name={`shipment-${shop.shopId}`}
                                                        value={shipper.shipperId}
                                                        checked={selectedShipments[shop.shopId] === shipper.shipperId}
                                                        onChange={() => onShipmentSelect(shop.shopId, shipper.shipperId)}
                                                        className="text-primary focus:ring-primary"
                                                    />
                                                    <div>
                                                        <div className="font-medium text-gray-900 flex items-center gap-2">
                                                            {shipper.shipperName}
                                                            {isCheapest && (
                                                                <span className="text-xs bg-green-100 text-green-800 px-1.5 py-0.5 rounded">
                                                                    ارزان‌ترین
                                                                </span>
                                                            )}
                                                        </div>
                                                        <div className="text-sm text-gray-600">
                                                            زمان ارسال: {shipper.shippingDaysRange?.join(' تا ') || 'نامشخص'}
                                                        </div>
                                                    </div>
                                                </div>

                                                <div className="text-left">
                                                    <div className="font-medium text-gray-900 relative group">
                                                        {shipper.totalShippingCost.toLocaleString('fa-IR')} تومان
                                                        {priceDifference > 0 && (
                                                            <div className="text-xs text-orange-600 mt-1">
                                                                +{priceDifference.toLocaleString('fa-IR')} تومان
                                                            </div>
                                                        )}
                                                        <div className="absolute bottom-full right-0 mb-2 px-2 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap z-10">
                                                            هزینه ارسال کل این فروشگاه
                                                        </div>
                                                    </div>
                                                </div>
                                            </label>
                                        )
                                    })
                                })()}
                            </div>

                            {(!shop.shippers || shop.shippers.length === 0) && (
                                <div className="text-center py-4 text-gray-500">
                                    روش ارسالی برای این فروشگاه موجود نیست
                                </div>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    )
}

export default ShippingMethodSelector
