'use client';

import { useState, useEffect } from 'react';
import { Promotion, CreatePromotionData, UpdatePromotionData, PROMOTION_TYPES } from '@/types/promotion';
import { PhotoIcon, XMarkIcon } from '@heroicons/react/24/outline';
import Image from 'next/image';

interface PromotionFormProps {
    promotion?: Promotion | null;
    onSubmit: (data: CreatePromotionData | UpdatePromotionData) => Promise<void>;
    onCancel: () => void;
    isLoading: boolean;
}

export default function PromotionForm({ promotion, onSubmit, onCancel, isLoading }: PromotionFormProps) {
    const [formData, setFormData] = useState<CreatePromotionData | UpdatePromotionData>({
        type: 'slider',
        title: '',
        subtitle: '',
        action_text: '',
        url_myket: '',
        url_bazzar: '',
        url_google_play: '',
        url_site: '',
        priority: 0,
        start_at: '',
        end_at: '',
    });

    const [imageFile, setImageFile] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);
    const [isActive, setIsActive] = useState(true);

    useEffect(() => {
        if (promotion) {
            // Format dates for input fields
            const startAt = promotion.start_at ? promotion.start_at.slice(0, 16) : '';
            const endAt = promotion.end_at ? promotion.end_at.slice(0, 16) : '';
            
            setFormData({
                type: promotion.type || 'slider',
                title: promotion.title || '',
                subtitle: promotion.subtitle || '',
                action_text: promotion.action_text || '',
                url_myket: promotion.url_myket || '',
                url_bazzar: promotion.url_bazzar || '',
                url_google_play: promotion.url_google_play || '',
                url_site: promotion.url_site || '',
                priority: promotion.priority || 0,
                start_at: startAt,
                end_at: endAt,
            });

            setIsActive(promotion.is_active);

            if (promotion.image_url) {
                setImagePreview(promotion.image_url);
            }
        } else {
            // Set default priority
            setFormData(prev => ({ ...prev, priority: 0 }));
        }
    }, [promotion]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value === '' ? null : value,
        }));
    };

    const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value === '' ? null : parseInt(value, 10),
        }));
    };

    const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setImageFile(file);
            setFormData(prev => ({ ...prev, image: file }));
            
            // Create preview
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreview(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    const removeImage = () => {
        setImageFile(null);
        setImagePreview(null);
        setFormData(prev => ({ ...prev, image: null }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        
        // Format dates properly
        let submitData: any = { ...formData };
        
        if (submitData.start_at) {
            submitData.start_at = submitData.start_at.replace('T', ' ') + ':00';
        }
        
        if (submitData.end_at) {
            submitData.end_at = submitData.end_at.replace('T', ' ') + ':00';
        }
        
        // Add is_active for updates
        if (promotion) {
            submitData.is_active = isActive;
        }
        
        await onSubmit(submitData);
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-lg shadow">
            <div>
                <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">
                    {promotion ? 'ویرایش تبلیغ' : 'ایجاد تبلیغ جدید'}
                </h3>
            </div>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                {/* Type */}
                <div>
                    <label htmlFor="type" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        نوع <span className="text-red-500">*</span>
                    </label>
                    <select
                        id="type"
                        name="type"
                        required
                        value={formData.type || 'slider'}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    >
                        {Object.entries(PROMOTION_TYPES).map(([value, label]) => (
                            <option key={value} value={value}>
                                {label}
                            </option>
                        ))}
                    </select>
                </div>

                {/* Title */}
                <div>
                    <label htmlFor="title" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        عنوان
                    </label>
                    <input
                        type="text"
                        id="title"
                        name="title"
                        value={formData.title || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                        placeholder="عنوان تبلیغ"
                    />
                </div>

                {/* Subtitle */}
                <div className="md:col-span-2">
                    <label htmlFor="subtitle" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        زیرعنوان
                    </label>
                    <input
                        type="text"
                        id="subtitle"
                        name="subtitle"
                        value={formData.subtitle || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                        placeholder="زیرعنوان تبلیغ"
                    />
                </div>

                {/* Action Text */}
                <div>
                    <label htmlFor="action_text" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        متن دکمه
                    </label>
                    <input
                        type="text"
                        id="action_text"
                        name="action_text"
                        value={formData.action_text || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                        placeholder="مثال: همین حالا نصب کن"
                    />
                </div>

                {/* Priority */}
                <div>
                    <label htmlFor="priority" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        اولویت
                    </label>
                    <input
                        type="number"
                        id="priority"
                        name="priority"
                        min="0"
                        value={formData.priority || 0}
                        onChange={handleNumberChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                        placeholder="عدد بالاتر = اولویت بیشتر"
                    />
                </div>

                {/* Start Date */}
                <div>
                    <label htmlFor="start_at" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        تاریخ شروع
                    </label>
                    <input
                        type="datetime-local"
                        id="start_at"
                        name="start_at"
                        value={formData.start_at || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    />
                </div>

                {/* End Date */}
                <div>
                    <label htmlFor="end_at" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        تاریخ پایان
                    </label>
                    <input
                        type="datetime-local"
                        id="end_at"
                        name="end_at"
                        value={formData.end_at || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    />
                </div>
            </div>

            {/* URLs Section */}
            <div className="border-t border-gray-200 dark:border-gray-800 pt-4">
                <h4 className="text-md font-medium text-gray-900 dark:text-gray-100 mb-3">لینک‌ها</h4>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                    {/* Myket URL */}
                    <div>
                        <label htmlFor="url_myket" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            لینک مایکت
                        </label>
                        <input
                            type="url"
                            id="url_myket"
                            name="url_myket"
                            value={formData.url_myket || ''}
                            onChange={handleInputChange}
                            className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                            placeholder="https://myket.ir/app/..."
                        />
                    </div>

                    {/* Bazaar URL */}
                    <div>
                        <label htmlFor="url_bazzar" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            لینک بازار
                        </label>
                        <input
                            type="url"
                            id="url_bazzar"
                            name="url_bazzar"
                            value={formData.url_bazzar || ''}
                            onChange={handleInputChange}
                            className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                            placeholder="https://cafebazaar.ir/app/..."
                        />
                    </div>

                    {/* Google Play URL */}
                    <div>
                        <label htmlFor="url_google_play" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            لینک گوگل‌پلی
                        </label>
                        <input
                            type="url"
                            id="url_google_play"
                            name="url_google_play"
                            value={formData.url_google_play || ''}
                            onChange={handleInputChange}
                            className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                            placeholder="https://play.google.com/store/apps/..."
                        />
                    </div>

                    {/* Site URL */}
                    <div>
                        <label htmlFor="url_site" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            لینک وبسایت
                        </label>
                        <input
                            type="url"
                            id="url_site"
                            name="url_site"
                            value={formData.url_site || ''}
                            onChange={handleInputChange}
                            className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                            placeholder="https://example.com"
                        />
                    </div>
                </div>
            </div>

            {/* Image Upload */}
            <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    تصویر
                </label>
                <div className="flex items-center space-x-3 space-x-reverse">
                    <label className="cursor-pointer flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm 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 transition-colors">
                        <PhotoIcon className="h-5 w-5 ml-2 text-gray-400 dark:text-gray-500" />
                        انتخاب تصویر
                        <input
                            type="file"
                            accept="image/*"
                            onChange={handleImageChange}
                            className="hidden"
                        />
                    </label>
                    {imagePreview && (
                        <button
                            type="button"
                            onClick={removeImage}
                            className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 transition-colors"
                        >
                            <XMarkIcon className="h-5 w-5" />
                        </button>
                    )}
                </div>
                {imagePreview && (
                    <div className="mt-2 relative h-32 w-32 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-800">
                        <img
                            src={imagePreview}
                            alt="Preview"
                            className="w-full h-full object-cover"
                        />
                    </div>
                )}
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    حداکثر حجم: ۲ مگابایت
                </p>
            </div>

            {/* Active Status (only for edit) */}
            {promotion && (
                <div className="flex items-center">
                    <input
                        type="checkbox"
                        id="is_active"
                        checked={isActive}
                        onChange={(e) => setIsActive(e.target.checked)}
                        className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 dark:border-gray-600 dark:bg-gray-800 rounded"
                    />
                    <label htmlFor="is_active" className="mr-2 block text-sm text-gray-900 dark:text-gray-100">
                        فعال
                    </label>
                </div>
            )}

            {/* Form Actions */}
            <div className="flex justify-end space-x-3 space-x-reverse pt-4 border-t dark:border-gray-800">
                <button
                    type="button"
                    onClick={onCancel}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm 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 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 transition-colors"
                >
                    انصراف
                </button>
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 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"
                >
                    {isLoading ? 'در حال ذخیره...' : promotion ? 'به‌روزرسانی' : 'ایجاد'}
                </button>
            </div>
        </form>
    );
}