'use client';

import { useState, useEffect, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { referralApi } from '@/lib/api/referral';
import ReferralList from '@/components/admin/referral/ReferralList';
import PageHeader from '@/components/admin/PageHeader';
import ConfirmDialog from '@/components/admin/ConfirmDialog';
import { showToast } from '@/components/Toast';
import { ReferralRewardUser } from '@/types/referral';
import { ArrowPathIcon } from '@heroicons/react/24/outline';

export default function ReferralRewardsPage() {
    const { token } = useAuth();
    const [users, setUsers] = useState<ReferralRewardUser[]>([]);
    const [subscriptionTarget, setSubscriptionTarget] = useState(0);
    const [isLoading, setIsLoading] = useState(false);
    const [fulfillingId, setFulfillingId] = useState<number | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [fulfillTarget, setFulfillTarget] = useState<ReferralRewardUser | null>(null);

    const initialLoadRef = useRef(false);

    useEffect(() => {
        if (token && !initialLoadRef.current) {
            initialLoadRef.current = true;
            loadRewards();
        }
    }, [token]);

    const loadRewards = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const data = await referralApi.getPendingRewards(token!);
            setUsers(data.data || []);
            setSubscriptionTarget(data.subscription_target || 0);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در دریافت لیست پاداش‌های معرفی');
        } finally {
            setIsLoading(false);
        }
    };

    const handleFulfill = (user: ReferralRewardUser) => {
        setFulfillTarget(user);
    };

    const confirmFulfill = async () => {
        if (!fulfillTarget) return;
        const user = fulfillTarget;

        setFulfillingId(user.id);
        setIsLoading(true);
        setError(null);

        try {
            await referralApi.fulfillReward(user.id, token!);
            showToast('success', `اشتراک رایگان با موفقیت به «${user.name || user.mobile || user.email}» اعطا شد`);
            setUsers((prev) => prev.filter((u) => u.id !== user.id));
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در اعطای اشتراک رایگان');
        } finally {
            setFulfillingId(null);
            setIsLoading(false);
            setFulfillTarget(null);
        }
    };

    return (
        <div className="p-4 sm:p-8">
            <div className="max-w-7xl mx-auto">
                <PageHeader
                    title="پاداش‌های معرفی"
                    subtitle="کاربرانی که به حد نصاب دعوت موفق رسیده‌اند و هنوز اشتراک رایگان دریافت نکرده‌اند."
                    action={
                        <button
                            onClick={loadRewards}
                            disabled={isLoading}
                            className="inline-flex items-center gap-2 px-4 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-900 disabled:opacity-50 transition-colors shadow-sm"
                        >
                            <ArrowPathIcon className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
                            بروزرسانی
                        </button>
                    }
                />

                {error && (
                    <div className="mb-4 rounded-xl bg-red-50 dark:bg-red-950/40 ring-1 ring-red-200 dark:ring-red-800/60 p-4 flex items-center gap-3">
                        <p className="text-sm text-red-700 dark:text-red-300">{error}</p>
                        <button onClick={() => setError(null)} className="mr-auto text-red-400 hover:text-red-600">
                            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                )}

                {isLoading && users.length === 0 ? (
                    <div className="text-center py-16 bg-white dark:bg-gray-900 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
                        <div className="mx-auto h-10 w-10 border-4 border-indigo-200 dark:border-indigo-800 border-t-indigo-600 rounded-full animate-spin" />
                        <p className="mt-3 text-gray-500 dark:text-gray-400 text-sm">در حال بارگذاری...</p>
                    </div>
                ) : (
                    <ReferralList
                        users={users}
                        subscriptionTarget={subscriptionTarget}
                        onFulfill={handleFulfill}
                        isLoading={isLoading}
                        fulfillingId={fulfillingId}
                    />
                )}

                <ConfirmDialog
                    open={!!fulfillTarget}
                    title="اعطای پاداش معرفی"
                    message={`آیا از اعطای یک ماه اشتراک رایگان به «${fulfillTarget?.name || fulfillTarget?.mobile || fulfillTarget?.email || ''}» اطمینان دارید؟`}
                    confirmLabel="اعطای اشتراک"
                    tone="primary"
                    isLoading={isLoading}
                    onConfirm={confirmFulfill}
                    onCancel={() => setFulfillTarget(null)}
                />
            </div>
        </div>
    );
}
