'use client';

import { Promotion } from '@/types/promotion';
import { getPromotionTypeLabel } from '@/types/promotion';
import { PencilIcon, TrashIcon, EyeIcon, EyeSlashIcon } from '@heroicons/react/24/outline';
import { formatDate } from '@/lib/utils';
import Image from 'next/image';
import { useState } from 'react';

interface PromotionListProps {
    promotions: Promotion[];
    onEdit: (promotion: Promotion) => void;
    onDelete: (promotion: Promotion) => void;
    onToggleActive: (promotion: Promotion) => void;
    isLoading: boolean;
}

export default function PromotionList({ promotions, onEdit, onDelete, onToggleActive, isLoading }: PromotionListProps) {
    const [imageErrors, setImageErrors] = useState<Record<number, boolean>>({});

    if (isLoading) {
        return (
            <div className="flex justify-center items-center py-12">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
            </div>
        );
    }

    if (!promotions || promotions.length === 0) {
        return (
            <div className="text-center py-12 bg-white rounded-lg shadow">
                <p className="text-gray-500">هیچ تبلیغاتی یافت نشد</p>
            </div>
        );
    }

    // Sort promotions by priority (higher priority first) and then by creation date
    const sortedPromotions = [...promotions].sort((a, b) => {
        if (a.priority && b.priority) {
            return b.priority - a.priority;
        }
        if (a.priority) return -1;
        if (b.priority) return 1;
        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
    });

    const handleImageError = (id: number) => {
        setImageErrors(prev => ({ ...prev, [id]: true }));
    };

    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>
            <ul className="divide-y divide-gray-200">
                {sortedPromotions.map((promotion) => (
                    <li key={promotion.id} className="px-6 py-4 hover:bg-gray-50">
                        <div className="flex items-start justify-between">
                            <div className="flex-1 min-w-0">
                                <div className="flex items-start space-x-4 space-x-reverse">
                                    {/* Promotion Image - Using unoptimized Image component */}
                                    {promotion.image_url && !imageErrors[promotion.id] && (
                                        <div className="flex-shrink-0">
                                            <div className="relative h-20 w-20 rounded-lg overflow-hidden border border-gray-200">
                                                <Image
                                                    src={promotion.image_url}
                                                    alt={promotion.title || 'Promotion'}
                                                    fill
                                                    className="object-cover"
                                                    onError={() => handleImageError(promotion.id)}
                                                    unoptimized={true} // This disables image optimization
                                                />
                                            </div>
                                        </div>
                                    )}

                                    {/* Promotion Details */}
                                    <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">
                                                    {promotion.title || 'بدون عنوان'}
                                                </p>
                                                <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                                    {getPromotionTypeLabel(promotion.type)}
                                                </span>
                                                {promotion.is_active ? (
                                                    <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                                                        فعال
                                                    </span>
                                                ) : (
                                                    <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
                                                        غیرفعال
                                                    </span>
                                                )}
                                            </div>
                                        </div>

                                        {promotion.subtitle && (
                                            <p className="mt-1 text-sm text-gray-600">
                                                {promotion.subtitle}
                                            </p>
                                        )}

                                        {promotion.action_text && (
                                            <p className="mt-1 text-xs text-gray-500">
                                                متن دکمه: {promotion.action_text}
                                            </p>
                                        )}

                                        <div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
                                            {promotion.priority && (
                                                <div className="text-xs text-gray-500">
                                                    <span className="font-medium">اولویت:</span> {promotion.priority}
                                                </div>
                                            )}
                                            
                                            {promotion.start_at && (
                                                <div className="text-xs text-gray-500">
                                                    <span className="font-medium">شروع:</span> {formatDate(promotion.start_at)}
                                                </div>
                                            )}
                                            
                                            {promotion.end_at && (
                                                <div className="text-xs text-gray-500">
                                                    <span className="font-medium">پایان:</span> {formatDate(promotion.end_at)}
                                                </div>
                                            )}
                                        </div>

                                        {/* URLs */}
                                        <div className="mt-2 space-y-1">
                                            {promotion.url_site && (
                                                <div className="text-xs text-gray-500 truncate">
                                                    <span className="font-medium">وبسایت:</span> {promotion.url_site}
                                                </div>
                                            )}
                                            {promotion.url_myket && (
                                                <div className="text-xs text-gray-500 truncate">
                                                    <span className="font-medium">مایکت:</span> {promotion.url_myket}
                                                </div>
                                            )}
                                            {promotion.url_bazzar && (
                                                <div className="text-xs text-gray-500 truncate">
                                                    <span className="font-medium">بازار:</span> {promotion.url_bazzar}
                                                </div>
                                            )}
                                            {promotion.url_google_play && (
                                                <div className="text-xs text-gray-500 truncate">
                                                    <span className="font-medium">گوگل‌پلی:</span> {promotion.url_google_play}
                                                </div>
                                            )}
                                        </div>

                                        <div className="mt-2 text-xs text-gray-400">
                                            آخرین به‌روزرسانی: {formatDate(promotion.updated_at)}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Action Buttons */}
                            <div className="mr-4 flex-shrink-0 flex flex-col space-y-2">
                                <button
                                    onClick={() => onToggleActive(promotion)}
                                    className={`p-2 rounded-full hover:bg-gray-100 ${
                                        promotion.is_active ? 'text-green-600' : 'text-gray-400'
                                    }`}
                                    title={promotion.is_active ? 'غیرفعال کردن' : 'فعال کردن'}
                                >
                                    {promotion.is_active ? (
                                        <EyeIcon className="h-5 w-5" />
                                    ) : (
                                        <EyeSlashIcon className="h-5 w-5" />
                                    )}
                                </button>
                                <button
                                    onClick={() => onEdit(promotion)}
                                    className="text-indigo-600 hover:text-indigo-900 p-2 rounded-full hover:bg-indigo-50"
                                >
                                    <PencilIcon className="h-5 w-5" />
                                </button>
                                <button
                                    onClick={() => onDelete(promotion)}
                                    className="text-red-600 hover:text-red-900 p-2 rounded-full hover:bg-red-50"
                                >
                                    <TrashIcon className="h-5 w-5" />
                                </button>
                            </div>
                        </div>
                    </li>
                ))}
            </ul>
        </div>
    );
}