
import React, { useState, useCallback } from 'react';
import { 
    UserIcon, 
    ListIcon, 
    UploadCloudIcon, 
    XIcon, 
    CheckCircleIcon, 
    ClockIcon, 
    AlertCircleIcon, 
    PhoneIcon
} from '../Icons';

interface ImageFile {
  id: number;
  url: string;
  file: File;
}

const AccountPage: React.FC = () => {
    // Mock user state - in a real app this comes from context/API
    const [fullName, setFullName] = useState('');
    const [nationalCode, setNationalCode] = useState('');
    const [phoneNumber, setPhoneNumber] = useState('09123456789'); // Mock
    const [idCardImage, setIdCardImage] = useState<ImageFile | null>(null);
    const [verificationStatus, setVerificationStatus] = useState<'unverified' | 'pending' | 'verified'>('unverified');

    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files[0]) {
            const file = files[0];
            setIdCardImage({
                id: Date.now(),
                url: URL.createObjectURL(file),
                file: file
            });
        }
    };

    const removeImage = () => {
        if (idCardImage) {
            URL.revokeObjectURL(idCardImage.url);
            setIdCardImage(null);
        }
    };

    const onDrop = useCallback((event: React.DragEvent<HTMLLabelElement>) => {
        event.preventDefault();
        event.stopPropagation();
        const files = event.dataTransfer.files;
        if (files && files[0] && files[0].type.startsWith('image/')) {
            const file = files[0];
            setIdCardImage({
                id: Date.now(),
                url: URL.createObjectURL(file),
                file: file
            });
        }
    }, []);

    const onDragOver = (event: React.DragEvent<HTMLLabelElement>) => {
        event.preventDefault();
        event.stopPropagation();
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        // Mock submission
        setVerificationStatus('pending');
        window.scrollTo(0,0);
    };

    const renderStatusBanner = () => {
        switch (verificationStatus) {
            case 'verified':
                return (
                    <div className="bg-green-500/10 border border-green-500/20 rounded-2xl p-6 flex items-center gap-4 mb-8">
                        <div className="bg-green-500 rounded-full p-2">
                            <CheckCircleIcon className="w-8 h-8 text-white" />
                        </div>
                        <div>
                            <h3 className="font-bold text-green-600 dark:text-green-400 text-lg">حساب کاربری تایید شده</h3>
                            <p className="text-green-700/80 dark:text-green-400/80 text-sm mt-1">هویت شما تایید شده است و می‌توانید از تمام امکانات استفاده کنید.</p>
                        </div>
                    </div>
                );
            case 'pending':
                return (
                    <div className="bg-custom-orange/10 border border-custom-orange/20 rounded-2xl p-6 flex items-center gap-4 mb-8">
                        <div className="bg-custom-orange rounded-full p-2">
                            <ClockIcon className="w-8 h-8 text-white" />
                        </div>
                        <div>
                            <h3 className="font-bold text-custom-orange text-lg">در حال بررسی مدارک</h3>
                            <p className="text-custom-orange/80 text-sm mt-1">مدارک شما ارسال شده و در صف بررسی توسط کارشناسان است.</p>
                        </div>
                    </div>
                );
            case 'unverified':
            default:
                return (
                    <div className="bg-gray-500/10 border border-gray-500/20 dark:bg-gray-700/30 dark:border-gray-600 rounded-2xl p-6 flex items-center gap-4 mb-8">
                        <div className="bg-gray-500 dark:bg-gray-600 rounded-full p-2">
                            <AlertCircleIcon className="w-8 h-8 text-white" />
                        </div>
                        <div>
                            <h3 className="font-bold text-gray-700 dark:text-gray-200 text-lg">حساب کاربری تایید نشده</h3>
                            <p className="text-gray-600 dark:text-gray-400 text-sm mt-1">لطفاً برای استفاده از خدمات، فرم زیر را تکمیل و کارت ملی خود را ارسال کنید.</p>
                        </div>
                    </div>
                );
        }
    };

    const isReadOnly = verificationStatus !== 'unverified';

    return (
        <div className="flex flex-col max-w-4xl mx-auto">
             <div className="mb-8">
                <h1 className="text-3xl font-bold text-gray-800 dark:text-white">حساب کاربری</h1>
                <p className="text-gray-500 dark:text-gray-400 mt-1">مدیریت اطلاعات شخصی و احراز هویت.</p>
            </div>

            {renderStatusBanner()}

            <form onSubmit={handleSubmit} className="space-y-8">
                {/* Personal Info Card */}
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                    <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">اطلاعات هویتی</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">نام و نام خانوادگی</label>
                            <div className="relative">
                                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <UserIcon className="w-5 h-5 text-gray-400" />
                                </div>
                                <input
                                    type="text"
                                    className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition disabled:opacity-60 disabled:cursor-not-allowed"
                                    placeholder="مثال: علی رضایی"
                                    value={fullName}
                                    onChange={(e) => setFullName(e.target.value)}
                                    disabled={isReadOnly}
                                    required
                                />
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">کد ملی</label>
                            <div className="relative">
                                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <ListIcon className="w-5 h-5 text-gray-400" />
                                </div>
                                <input
                                    type="text"
                                    maxLength={10}
                                    className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition disabled:opacity-60 disabled:cursor-not-allowed font-mono dir-ltr text-right"
                                    placeholder="0123456789"
                                    value={nationalCode}
                                    onChange={(e) => {
                                        const val = e.target.value.replace(/[^0-9]/g, '');
                                        setNationalCode(val);
                                    }}
                                    disabled={isReadOnly}
                                    required
                                />
                            </div>
                        </div>
                         <div>
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">شماره موبایل</label>
                            <div className="relative">
                                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <PhoneIcon className="w-5 h-5 text-gray-400" />
                                </div>
                                <input
                                    type="text"
                                    className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition opacity-60 cursor-not-allowed font-mono dir-ltr text-right"
                                    value={phoneNumber}
                                    readOnly
                                    disabled
                                />
                            </div>
                        </div>
                    </div>
                </div>

                {/* ID Card Upload */}
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                    <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">تصویر کارت ملی</h3>
                    
                    {!idCardImage ? (
                         <label 
                            htmlFor="id-card-upload" 
                            className={`flex flex-col items-center justify-center w-full h-64 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl bg-custom-light-bg dark:bg-custom-dark-blue transition-colors ${!isReadOnly ? 'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800' : 'opacity-60 cursor-not-allowed'}`}
                            onDrop={!isReadOnly ? onDrop : undefined}
                            onDragOver={!isReadOnly ? onDragOver : undefined}
                        >
                            <div className="flex flex-col items-center justify-center pt-5 pb-6 text-center px-4">
                                <div className="p-4 bg-gray-200 dark:bg-gray-700 rounded-full mb-4">
                                     <UploadCloudIcon className="w-8 h-8 text-gray-500 dark:text-gray-400" />
                                </div>
                                <p className="mb-2 text-lg font-medium text-gray-700 dark:text-gray-200">
                                    تصویر روی کارت ملی خود را بارگذاری کنید
                                </p>
                                <p className="text-sm text-gray-500 dark:text-gray-400">
                                    {isReadOnly ? 'امکان تغییر تصویر وجود ندارد' : 'برای انتخاب کلیک کنید یا تصویر را اینجا رها کنید'}
                                </p>
                                <p className="text-xs text-gray-400 dark:text-gray-500 mt-2">JPG, PNG (Max. 2MB)</p>
                            </div>
                            <input id="id-card-upload" type="file" className="hidden" accept="image/*" onChange={handleImageUpload} disabled={isReadOnly} />
                        </label>
                    ) : (
                        <div className="relative group rounded-xl overflow-hidden border border-gray-200 dark:border-gray-700">
                            <img src={idCardImage.url} alt="ID Card Preview" className="w-full h-64 object-cover" />
                             {!isReadOnly && (
                                 <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                    <button 
                                        type="button"
                                        onClick={removeImage} 
                                        className="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors"
                                    >
                                        <XIcon className="w-5 h-5" />
                                        <span>حذف و انتخاب مجدد</span>
                                    </button>
                                </div>
                             )}
                        </div>
                    )}
                </div>

                {!isReadOnly && (
                    <div className="flex justify-end">
                        <button 
                            type="submit" 
                            className="bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-3 px-8 rounded-xl transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50 disabled:bg-gray-400 disabled:cursor-not-allowed"
                            disabled={!fullName || !nationalCode || !idCardImage}
                        >
                            ثبت اطلاعات و درخواست تایید
                        </button>
                    </div>
                )}
            </form>

            {/* Debugging / Demo Controls - Can be removed in prod */}
            <div className="mt-12 p-4 border border-dashed border-gray-300 dark:border-gray-700 rounded-lg opacity-50 hover:opacity-100 transition-opacity">
                <p className="text-xs text-gray-500 mb-2">تنظیمات دمو (برای مشاهده وضعیت‌های مختلف):</p>
                <div className="flex gap-2">
                    <button type="button" onClick={() => setVerificationStatus('unverified')} className="px-3 py-1 bg-gray-200 dark:bg-gray-700 rounded text-xs">تایید نشده</button>
                    <button type="button" onClick={() => setVerificationStatus('pending')} className="px-3 py-1 bg-yellow-200 dark:bg-yellow-900 rounded text-xs">در حال بررسی</button>
                    <button type="button" onClick={() => setVerificationStatus('verified')} className="px-3 py-1 bg-green-200 dark:bg-green-900 rounded text-xs">تایید شده</button>
                </div>
            </div>
        </div>
    );
};

export default AccountPage;
