'use client';

import { useState, useEffect } from 'react';
import { PackageName, CreatePackageData, UpdatePackageData } from '@/types/package';
import { XMarkIcon, PhotoIcon, DocumentTextIcon } from '@heroicons/react/24/outline';

interface PackageFormProps {
    package?: PackageName | null;
    onSubmit: (data: CreatePackageData | UpdatePackageData) => Promise<void>;
    onCancel: () => void;
    isLoading: boolean;
}

export default function PackageForm({ package: pkg, onSubmit, onCancel, isLoading }: PackageFormProps) {
    const [formData, setFormData] = useState<CreatePackageData | UpdatePackageData>({
        name: '',
        title: '',
        v1_identifier: '',
        myket_access_token: '',
        cafe_config_id: null,
        web_app_url: '',
        tries: 0,
    });

    const [avatarFile, setAvatarFile] = useState<File | null>(null);
    const [firebaseFile, setFirebaseFile] = useState<File | null>(null);
    const [avatarPreview, setAvatarPreview] = useState<string | null>(null);

    useEffect(() => {
        if (pkg) {
            setFormData({
                name: pkg.name || '',
                title: pkg.title || '',
                v1_identifier: pkg.v1_identifier || '',
                myket_access_token: pkg.myket_access_token || '',
                cafe_config_id: pkg.cafe_config_id,
                web_app_url: pkg.web_app_url || '',
                tries: pkg.tries || 0,
            });
            if (pkg.image && typeof pkg.image === 'string') {
                setAvatarPreview(pkg.image);
            }
        }
    }, [pkg]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        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 handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setAvatarFile(file);
            setFormData(prev => ({ ...prev, avatar: file }));
            const reader = new FileReader();
            reader.onloadend = () => setAvatarPreview(reader.result as string);
            reader.readAsDataURL(file);
        }
    };

    const handleFirebaseChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setFirebaseFile(file);
            setFormData(prev => ({ ...prev, firebase_json: file }));
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        await onSubmit(formData);
    };

    const removeAvatar = () => {
        setAvatarFile(null);
        setAvatarPreview(null);
        setFormData(prev => ({ ...prev, avatar: null }));
    };

    const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
    const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';

    return (
        <form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
            <div className="pb-4 border-b border-gray-100 dark:border-gray-800">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                    {pkg ? 'ویرایش پکیج' : 'ایجاد پکیج جدید'}
                </h3>
            </div>

            <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                <div>
                    <label htmlFor="name" className={labelClass}>نام پکیج <span className="text-red-500">*</span></label>
                    <input type="text" id="name" name="name" required value={formData.name || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: com.approagency.meditation" dir="ltr" />
                </div>
                <div>
                    <label htmlFor="title" className={labelClass}>عنوان <span className="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" required value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: آرام لند" />
                </div>

                <div>
                    <label className={labelClass}>تصویر</label>
                    <div className="flex items-center gap-3">
                        <label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                            <PhotoIcon className="h-4 w-4 text-gray-400" />
                            انتخاب تصویر
                            <input type="file" accept="image/*" onChange={handleAvatarChange} className="hidden" />
                        </label>
                        {avatarPreview && (
                            <button type="button" onClick={removeAvatar} className="text-red-500 hover:text-red-700 transition-colors">
                                <XMarkIcon className="h-5 w-5" />
                            </button>
                        )}
                    </div>
                    {avatarPreview && (
                        <div className="mt-3">
                            <img src={avatarPreview} alt="Preview" className="h-20 w-20 object-cover rounded-xl ring-1 ring-gray-200 dark:ring-gray-800" />
                        </div>
                    )}
                </div>

                <div>
                    <label htmlFor="v1_identifier" className={labelClass}>شناسه V1</label>
                    <input type="text" id="v1_identifier" name="v1_identifier" value={formData.v1_identifier || ''} onChange={handleInputChange} className={inputClass} />
                </div>
                <div>
                    <label htmlFor="myket_access_token" className={labelClass}>توکن دسترسی Myket</label>
                    <input type="text" id="myket_access_token" name="myket_access_token" value={formData.myket_access_token || ''} onChange={handleInputChange} className={inputClass} />
                </div>
                <div>
                    <label htmlFor="cafe_config_id" className={labelClass}>شناسه کافه بازار</label>
                    <input type="number" id="cafe_config_id" name="cafe_config_id" value={formData.cafe_config_id || ''} onChange={handleNumberChange} className={inputClass} />
                </div>
                <div>
                    <label htmlFor="web_app_url" className={labelClass}>آدرس وب اپلیکیشن</label>
                    <input type="url" id="web_app_url" name="web_app_url" value={formData.web_app_url || ''} onChange={handleInputChange} className={inputClass} placeholder="https://example.com" dir="ltr" />
                </div>
                <div>
                    <label htmlFor="tries" className={labelClass}>تعداد تلاش‌ها</label>
                    <input type="number" id="tries" name="tries" value={formData.tries || 0} onChange={handleNumberChange} className={inputClass} />
                </div>
                <div className="md:col-span-2 pt-2 border-t border-gray-100 dark:border-gray-800">
                    <label className={labelClass}>فایل Firebase JSON</label>
                    <label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                        <DocumentTextIcon className="h-4 w-4 text-gray-400" />
                        انتخاب فایل
                        <input type="file" accept=".json,application/json" onChange={handleFirebaseChange} className="hidden" />
                    </label>
                    {firebaseFile && (
                        <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{firebaseFile.name}</p>
                    )}
                </div>
            </div>

            <div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
                <button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 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">
                    انصراف
                </button>
                <button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
                    {isLoading ? 'در حال ذخیره...' : pkg ? 'به‌روزرسانی' : 'ایجاد'}
                </button>
            </div>
        </form>
    );
}
