'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { usersApi } from '@/lib/api/users';
import { packagesApi } from '@/lib/api/packages';
import UserSearch from '@/components/admin/users/UserSearch';
import UserInfo from '@/components/admin/users/UserInfo';
import UserProducts from '@/components/admin/users/UserProducts';
import PackageSelector from '@/components/admin/users/PackageSelector';
import { User, Product } from '@/types/user';
import { PackageName } from '@/types/package';
import { formatPrice, getProductTypeLabel } from '@/lib/utils';

export default function UsersPage() {
    const { token } = useAuth();
    const [user, setUser] = useState<User | null>(null);
    const [products, setProducts] = useState<Product[]>([]);
    const [packages, setPackages] = useState<PackageName[]>([]);
    const [selectedPackage, setSelectedPackage] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);

    // Load packages on mount
    useEffect(() => {
        if (token) {
            loadPackages();
        }
    }, [token]);

    // Load products when package changes
    useEffect(() => {
        if (token && selectedPackage) {
            loadProducts(selectedPackage);
        }
    }, [selectedPackage, token]);

    const loadPackages = async () => {
        try {
            const data = await packagesApi.getAllPackages(token!);
            setPackages(data);
            if (data.length > 0 && !selectedPackage) {
                setSelectedPackage(data[0].name!);
            }
        } catch (err) {
            console.error('Failed to load packages:', err);
            setError('خطا در دریافت لیست پکیج‌ها');
        }
    };

    const loadProducts = async (packageName: string) => {
        try {
            console.log('Loading products for package:', packageName);
            const data = await usersApi.getProductsByPackage(packageName, token!);
            console.log('Products loaded:', data);
            setProducts(data);
        } catch (err) {
            console.error('Failed to load products:', err);
            setError('خطا در دریافت محصولات');
        }
    };

    const handleSearch = async (searchTerm: string) => {
        if (!selectedPackage) {
            setError('لطفا ابتدا یک پکیج انتخاب کنید');
            return;
        }

        setIsLoading(true);
        setError(null);
        setUser(null);

        try {
            console.log('Searching for user:', searchTerm, 'in package:', selectedPackage);
            const userData = await usersApi.getUserStatus(searchTerm, selectedPackage, token!);
            console.log('User data:', userData);
            setUser(userData);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در دریافت اطلاعات کاربر');
        } finally {
            setIsLoading(false);
        }
    };

    const handleSubscribe = async (productId: number) => {
        if (!user) return;

        // Get identifier (email or mobile) with null check
        const identifier = user.email || user.mobile;

        if (!identifier) {
            setError('کاربر فاقد ایمیل یا شماره موبایل است');
            return;
        }

        setIsLoading(true);
        setError(null);
        setSuccess(null);

        try {
            console.log('Subscribing user:', identifier, 'to product:', productId);
            await usersApi.subscribeUser(identifier, productId, token!);
            setSuccess('اشتراک با موفقیت اضافه شد');
            // Refresh user data with current selected package
            if (selectedPackage) {
                const userData = await usersApi.getUserStatus(identifier, selectedPackage, token!);
                setUser(userData);
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در افزودن اشتراک');
        } finally {
            setIsLoading(false);
        }
    };

    const handleUnsubscribe = async (productId: number) => {
        if (!user) return;

        // Get identifier (email or mobile) with null check
        const identifier = user.email || user.mobile;

        if (!identifier) {
            setError('کاربر فاقد ایمیل یا شماره موبایل است');
            return;
        }

        setIsLoading(true);
        setError(null);
        setSuccess(null);

        try {
            console.log('Unsubscribing user:', identifier, 'from product:', productId);
            await usersApi.unsubscribeUser(identifier, productId, token!);
            setSuccess('اشتراک با موفقیت لغو شد');
            // Refresh user data with current selected package
            if (selectedPackage) {
                const userData = await usersApi.getUserStatus(identifier, selectedPackage, token!);
                setUser(userData);
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در لغو اشتراک');
        } finally {
            setIsLoading(false);
        }
    };

    const handlePackageChange = (packageName: string) => {
        console.log('Package changed to:', packageName);
        setSelectedPackage(packageName);
        // Clear user when package changes to avoid showing wrong data
        setUser(null);
        setError(null);
        setSuccess(null);
    };

    // Filter available products (show ALL products, don't filter out ones user already has)
    const availableProducts = products;

    console.log('Current state:', {
        selectedPackage,
        productsCount: products.length,
        userProductsCount: user?.products?.length,
        availableProductsCount: availableProducts.length
    });

    return (
        <div className="p-6">
            <div className="max-w-7xl mx-auto">
                <h1 className="text-2xl font-bold text-gray-900 mb-6">
                    مدیریت کاربران
                </h1>

                {/* Package Selector */}
                {token && (
                    <PackageSelector
                        token={token}
                        selectedPackage={selectedPackage}
                        onPackageChange={handlePackageChange}
                        isLoading={isLoading}
                    />
                )}

                {/* Search Section - Only show if package is selected */}
                {selectedPackage && (
                    <UserSearch onSearch={handleSearch} isLoading={isLoading} />
                )}

                {/* Messages */}
                {error && (
                    <div className="mb-4 rounded-md bg-red-50 p-4">
                        <div className="flex">
                            <div className="flex-shrink-0">
                                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                </svg>
                            </div>
                            <div className="mr-3">
                                <p className="text-sm text-red-800">{error}</p>
                            </div>
                        </div>
                    </div>
                )}

                {success && (
                    <div className="mb-4 rounded-md bg-green-50 p-4">
                        <div className="flex">
                            <div className="flex-shrink-0">
                                <svg className="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                </svg>
                            </div>
                            <div className="mr-3">
                                <p className="text-sm text-green-800">{success}</p>
                            </div>
                        </div>
                    </div>
                )}

                {/* No Package Selected Message */}
                {!selectedPackage && packages.length === 0 && (
                    <div className="text-center py-12 bg-white rounded-lg shadow">
                        <p className="text-gray-500">هیچ پکیجی یافت نشد. ابتدا یک پکیج ایجاد کنید.</p>
                    </div>
                )}

                {/* Show products list even without user */}
                {selectedPackage && products.length > 0 && !user && (
                    <div className="mb-6">
                        <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">
                                    محصولات موجود در پکیج {selectedPackage}
                                </h3>
                            </div>
                            <div className="border-t border-gray-200 px-4 py-5 sm:px-6">
                                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                                    {products.map((product) => (
                                        <div
                                            key={product.id}
                                            className="relative block w-full border border-gray-200 rounded-lg p-4 text-right bg-gray-50"
                                        >
                                            <p className="text-sm font-medium text-gray-900">
                                                {product.title || 'محصول'}
                                            </p>
                                            <p className="mt-1 text-xs text-gray-500">
                                                قیمت: {formatPrice(product.price)} تومان
                                            </p>
                                            <p className="text-xs text-gray-500">
                                                نوع: {getProductTypeLabel(product.type)}
                                            </p>
                                        </div>
                                    ))}
                                </div>
                                <p className="mt-4 text-sm text-gray-500 text-center">
                                    برای افزودن اشتراک به کاربر، ابتدا یک کاربر جستجو کنید
                                </p>
                            </div>
                        </div>
                    </div>
                )}

                {/* User Info */}
                {user && <UserInfo user={user} />}

                {/* User Products */}
                {user && selectedPackage && (
                    <UserProducts
                        products={user.products || []}
                        availableProducts={availableProducts}
                        onSubscribe={handleSubscribe}
                        onUnsubscribe={handleUnsubscribe}
                        isLoading={isLoading}
                        selectedPackage={selectedPackage}
                    />
                )}
            </div>
        </div>
    );
}