'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { promotionsApi } from '@/lib/api/promotions';
import PromotionList from '@/components/admin/promotions/PromotionList';
import PromotionForm from '@/components/admin/promotions/PromotionForm';
import PageHeader from '@/components/admin/PageHeader';
import { showToast } from '@/components/Toast';
import { Promotion, CreatePromotionData, UpdatePromotionData } from '@/types/promotion';
import { PlusIcon } from '@heroicons/react/24/outline';

export default function PromotionsPage() {
    const { token } = useAuth();
    const [promotions, setPromotions] = useState<Promotion[]>([]);
    const [selectedPromotion, setSelectedPromotion] = useState<Promotion | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isFormVisible, setIsFormVisible] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const initialLoadRef = useRef(false);

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

    const loadPromotions = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const data = await promotionsApi.getPromotions(token!);
            setPromotions(data);
        } catch (err) {
            setError('خطا در دریافت لیست تبلیغات');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCreate = () => {
        setSelectedPromotion(null);
        setIsFormVisible(true);
    };

    const handleEdit = (promotion: Promotion) => {
        setSelectedPromotion(promotion);
        setIsFormVisible(true);
    };

    const handleDelete = async (promotion: Promotion) => {
        if (!confirm(`آیا از حذف تبلیغ "${promotion.title || 'بدون عنوان'}" اطمینان دارید؟`)) {
            return;
        }

        setIsLoading(true);
        setError(null);

        try {
            await promotionsApi.deletePromotion(promotion.id, token!);
            showToast('success', 'تبلیغ با موفقیت حذف شد');
            await loadPromotions();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در حذف تبلیغ');
        } finally {
            setIsLoading(false);
        }
    };

    const handleToggleActive = async (promotion: Promotion) => {
        setIsLoading(true);
        setError(null);

        try {
            await promotionsApi.toggleActive(promotion.id, !promotion.is_active, token!);
            showToast('success', `تبلیغ با موفقیت ${!promotion.is_active ? 'فعال' : 'غیرفعال'} شد`);
            await loadPromotions();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در تغییر وضعیت تبلیغ');
        } finally {
            setIsLoading(false);
        }
    };

    const handleSubmit = async (data: CreatePromotionData | UpdatePromotionData) => {
        setIsLoading(true);
        setError(null);

        try {
            if (selectedPromotion) {
                await promotionsApi.updatePromotion(selectedPromotion.id, data, token!);
                showToast('success', 'تبلیغ با موفقیت به‌روزرسانی شد');
            } else {
                await promotionsApi.createPromotion(data as CreatePromotionData, token!);
                showToast('success', 'تبلیغ با موفقیت ایجاد شد');
            }

            await loadPromotions();
            setIsFormVisible(false);
            setSelectedPromotion(null);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'خطا در ذخیره تبلیغ');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCancel = () => {
        setIsFormVisible(false);
        setSelectedPromotion(null);
        setError(null);
    };

    return (
        <div className="p-4 sm:p-8">
            <div className="max-w-7xl mx-auto">
                <PageHeader
                    title="مدیریت تبلیغات"
                    action={
                        !isFormVisible ? (
                            <button
                                onClick={handleCreate}
                                disabled={isLoading}
                                className="inline-flex items-center gap-2 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20"
                            >
                                <PlusIcon className="h-4 w-4" />
                                تبلیغ جدید
                            </button>
                        ) : undefined
                    }
                />

                {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>
                )}

                {isFormVisible ? (
                    <PromotionForm
                        promotion={selectedPromotion}
                        onSubmit={handleSubmit}
                        onCancel={handleCancel}
                        isLoading={isLoading}
                    />
                ) : (
                    <PromotionList
                        promotions={promotions}
                        onEdit={handleEdit}
                        onDelete={handleDelete}
                        onToggleActive={handleToggleActive}
                        isLoading={isLoading}
                    />
                )}
            </div>
        </div>
    );
}
