'use client';

import { UserProduct } from '@/types/user';
import { formatDate, formatPrice, getProductTypeLabel } from '@/lib/utils';
import { CheckCircleIcon, XCircleIcon, PlusCircleIcon } from '@heroicons/react/24/outline';
import { useState } from 'react';

interface UserProductsProps {
    products: UserProduct[];
    onSubscribe: (productId: number) => void;
    onUnsubscribe: (productId: number) => void;
    isLoading: boolean;
    availableProducts: { id: number; title: string | null; packageName?: string }[];
    selectedPackage?: string | null;
}

export default function UserProducts({
    products,
    onSubscribe,
    onUnsubscribe,
    isLoading,
    availableProducts,
    selectedPackage
}: UserProductsProps) {
    const [selectedProductId, setSelectedProductId] = useState<number | null>(null);

    const getSubscriptionStatus = (product: UserProduct) => {
        if (!product.pivot?.expire_at) {
            return {
                isActive: false,
                text: 'نامشخص',
                color: 'text-gray-600',
                icon: XCircleIcon
            };
        }

        const expireDate = new Date(product.pivot.expire_at);
        const now = new Date();
        const isActive = expireDate > now;

        return {
            isActive,
            text: isActive ? 'فعال' : 'منقضی شده',
            color: isActive ? 'text-green-600' : 'text-red-600',
            icon: isActive ? CheckCircleIcon : XCircleIcon
        };
    };

    // Get count of subscriptions for a specific product
    const getSubscriptionCount = (productId: number): number => {
        return products.filter(p => p.id === productId).length;
    };

    // Group products by package
    const productsByPackage = products.reduce((acc, product) => {
        const packageName = product.package_name?.name || 'نامشخص';
        if (!acc[packageName]) {
            acc[packageName] = [];
        }
        acc[packageName].push(product);
        return acc;
    }, {} as Record<string, UserProduct[]>);

    const handleSubscribeClick = (productId: number) => {
        setSelectedProductId(productId);
        onSubscribe(productId);
    };

    return (
        <div className="bg-white shadow overflow-hidden sm:rounded-lg">
            <div className="px-4 py-5 sm:px-6">
                <h3 className="text-lg leading-6 font-medium text-gray-900">
                    اشتراک‌های کاربر
                </h3>
            </div>

            {/* Current Subscriptions grouped by package */}
            <div className="border-t border-gray-200">
                {Object.keys(productsByPackage).length > 0 ? (
                    Object.entries(productsByPackage).map(([packageName, packageProducts]) => (
                        <div key={packageName} className="border-b border-gray-200 last:border-b-0">
                            <div className="bg-gray-50 px-4 py-2">
                                <h4 className="text-sm font-medium text-gray-700">
                                    پکیج: {packageName}
                                </h4>
                            </div>
                            <ul className="divide-y divide-gray-200">
                                {packageProducts.map((product) => {
                                    const status = getSubscriptionStatus(product);
                                    const StatusIcon = status.icon;
                                    const subscriptionCount = getSubscriptionCount(product.id);

                                    return (
                                        <li key={`${product.id}-${product.pivot?.purchase_token || Math.random()}`} className="px-4 py-4 sm:px-6">
                                            <div className="flex items-center justify-between">
                                                <div className="flex-1">
                                                    <div className="flex items-center justify-between">
                                                        <div className="flex items-center space-x-2 space-x-reverse">
                                                            <p className="text-sm font-medium text-indigo-600 truncate">
                                                                {product.title || 'محصول'}
                                                            </p>
                                                            {subscriptionCount > 1 && (
                                                                <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full">
                                                                    {subscriptionCount} اشتراک
                                                                </span>
                                                            )}
                                                        </div>
                                                        <div className="mr-2 flex-shrink-0 flex">
                                                            <p className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${status.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                                                <StatusIcon className={`h-4 w-4 ml-1 ${status.color}`} />
                                                                {status.text}
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <div className="mt-2 sm:flex sm:justify-between">
                                                        <div className="sm:flex">
                                                            <p className="flex items-center text-sm text-gray-500">
                                                                قیمت: {formatPrice(product.price)} تومان
                                                            </p>
                                                            <p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:mr-6">
                                                                نوع: {getProductTypeLabel(product.type)}
                                                            </p>
                                                            {product.pivot?.expire_at && (
                                                                <p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:mr-6">
                                                                    تاریخ انقضا: {formatDate(product.pivot.expire_at)}
                                                                </p>
                                                            )}
                                                        </div>
                                                        <div className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0">
                                                            <button
                                                                onClick={() => onUnsubscribe(product.id)}
                                                                disabled={isLoading}
                                                                className="text-red-600 hover:text-red-900 disabled:opacity-50"
                                                            >
                                                                لغو اشتراک
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </li>
                                    );
                                })}
                            </ul>
                        </div>
                    ))
                ) : (
                    <div className="px-4 py-5 sm:px-6 text-center text-gray-500">
                        کاربر هیچ اشتراکی ندارد
                    </div>
                )}
            </div>

            {/* Available Products for Subscription */}
            {availableProducts && availableProducts.length > 0 && selectedPackage && (
                <div className="border-t border-gray-200 px-4 py-5 sm:px-6">
                    <h4 className="text-md font-medium text-gray-900 mb-3">
                        افزودن اشتراک جدید برای پکیج {selectedPackage}
                    </h4>
                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                        {availableProducts.map((product) => {
                            const subscriptionCount = getSubscriptionCount(product.id);

                            return (
                                <button
                                    key={product.id}
                                    onClick={() => handleSubscribeClick(product.id)}
                                    disabled={isLoading}
                                    className="relative block w-full border-2 border-indigo-200 rounded-lg p-4 text-right hover:border-indigo-500 hover:bg-indigo-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                                >
                                    <div className="flex items-start justify-between">
                                        <div>
                                            <p className="text-sm font-medium text-gray-900">
                                                {product.title || 'محصول'}
                                            </p>
                                            {subscriptionCount > 0 && (
                                                <p className="mt-1 text-xs text-amber-600">
                                                    {subscriptionCount} اشتراک فعال دارد
                                                </p>
                                            )}
                                        </div>
                                        <PlusCircleIcon className="h-5 w-5 text-indigo-600" />
                                    </div>
                                    <p className="mt-2 text-xs text-gray-500">
                                        برای افزودن اشتراک جدید کلیک کنید
                                    </p>
                                </button>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
}