
import React, { useState, useEffect } from 'react';
import type { Service, Application, User } from '../types';
import { UploadIcon } from '../components/Icons';

interface ApplicationPageProps {
  services: Service[];
  addApplication: (application: Application) => void;
  currentUser: User | null;
}

const ApplicationPage: React.FC<ApplicationPageProps> = ({ services, addApplication, currentUser }) => {
  const [selectedService, setSelectedService] = useState(services[0]?.id || '');
  const [fileName, setFileName] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submissionStatus, setSubmissionStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [submittedAppId, setSubmittedAppId] = useState('');
  const [formData, setFormData] = useState({
      fullName: '',
      mobile: '',
      address: '',
  });

  useEffect(() => {
    if (currentUser) {
      setFormData(prev => ({
          ...prev,
          fullName: currentUser.fullName,
          mobile: currentUser.mobile,
      }));
    }
  }, [currentUser]);

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

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      setFileName(event.target.files[0].name);
    } else {
      setFileName('');
    }
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsSubmitting(true);
    setSubmissionStatus('idle');

    const formEl = event.currentTarget;
    const formValues = new FormData(formEl);
    
    // Simulate API call
    setTimeout(() => {
      // Simulate a random success/error outcome
      if (Math.random() > 0.1) { // 90% success rate
        const newApplicationId = `#S${Date.now().toString().slice(-6)}`;
        const newApplication: Application = {
            id: newApplicationId,
            userId: currentUser ? currentUser.id : null,
            fullName: formData.fullName,
            mobile: formData.mobile,
            address: formData.address,
            serviceId: formValues.get('service') as string,
            trxId: formValues.get('trxId') as string,
            status: 'Pending',
            submissionDate: new Date().toLocaleDateString('bn-BD'),
        };
        
        addApplication(newApplication);
        setSubmittedAppId(newApplicationId);
        setSubmissionStatus('success');
        formEl.reset();
        setFileName('');
        setFormData({ fullName: currentUser?.fullName || '', mobile: currentUser?.mobile || '', address: '' });

      } else {
        setSubmissionStatus('error');
      }
      setIsSubmitting(false);
    }, 2000);
  };
  
  const selectedServiceDetails = services.find(s => s.id === selectedService);

  return (
    <div className="py-16 bg-gray-50">
      <div className="container mx-auto px-4">
        <div className="max-w-4xl mx-auto bg-white p-8 sm:p-12 rounded-2xl shadow-lg">
          <div className="text-center mb-10">
            <h1 className="text-3xl md:text-4xl font-extrabold text-gray-800">অনলাইন আবেদনপত্র</h1>
            <p className="mt-3 text-gray-600">সঠিক তথ্য দিয়ে নিচের আবেদনপত্রটি পূরণ করে জমা দিন।</p>
          </div>

          {submissionStatus === 'success' ? (
            <div className="text-center p-8 bg-green-50 border-l-4 border-green-500">
                <h2 className="text-2xl font-bold text-green-800">আপনার আবেদন সফলভাবে জমা হয়েছে!</h2>
                <p className="mt-2 text-green-700">আমাদের একজন প্রতিনিধি শীঘ্রই আপনার সাথে যোগাযোগ করবেন। আপনার আবেদন আইডি: <strong>{submittedAppId}</strong></p>
                <button onClick={() => setSubmissionStatus('idle')} className="mt-6 bg-green-600 text-white font-bold py-2 px-6 rounded-lg hover:bg-green-700">নতুন আবেদন করুন</button>
            </div>
          ) : (
            <form id="applicationForm" onSubmit={handleSubmit} className="space-y-8">
              {/* Personal Information */}
              <div>
                <h2 className="text-xl font-semibold text-gray-700 border-b pb-2 mb-6">ব্যক্তিগত তথ্যাদি</h2>
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <label htmlFor="fullName" className="block text-md font-medium text-gray-700 mb-1">আপনার পুরো নাম</label>
                    <input type="text" id="fullName" name="fullName" required value={formData.fullName} onChange={handleInputChange} readOnly={!!currentUser} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500 read-only:bg-gray-100" />
                  </div>
                  <div>
                    <label htmlFor="mobile" className="block text-md font-medium text-gray-700 mb-1">মোবাইল নম্বর</label>
                    <input type="tel" id="mobile" name="mobile" required value={formData.mobile} onChange={handleInputChange} readOnly={!!currentUser} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500 read-only:bg-gray-100" />
                  </div>
                   <div className="md:col-span-2">
                    <label htmlFor="address" className="block text-md font-medium text-gray-700 mb-1">বর্তমান ঠিকানা</label>
                    <textarea id="address" name="address" rows={3} required value={formData.address} onChange={handleInputChange} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500"></textarea>
                  </div>
                </div>
              </div>
              
              {/* Service Selection */}
               <div>
                <h2 className="text-xl font-semibold text-gray-700 border-b pb-2 mb-6">সেবার বিবরণ</h2>
                <div>
                  <label htmlFor="service" className="block text-md font-medium text-gray-700 mb-1">আপনি কোন সেবাটি গ্রহণ করতে চান?</label>
                  <select id="service" name="service" value={selectedService} onChange={(e) => setSelectedService(e.target.value)} required className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500 bg-white">
                    {services.map(service => (
                      <option key={service.id} value={service.id}>{service.title}</option>
                    ))}
                  </select>
                </div>
              </div>

              {/* File Upload */}
              <div>
                <h2 className="text-xl font-semibold text-gray-700 border-b pb-2 mb-6">প্রয়োজনীয় নথিপত্র</h2>
                 {selectedServiceDetails && (
                    <div className="mb-4 p-4 bg-green-50 text-green-800 rounded-lg border border-green-200">
                        <p className="font-semibold">প্রয়োজনীয় নথিপত্র:</p>
                        <ul className="list-disc list-inside mt-1">
                            {selectedServiceDetails.requiredDocs.map(doc => <li key={doc}>{doc}</li>)}
                        </ul>
                    </div>
                )}
                <div>
                  <label htmlFor="fileUpload" className="block text-md font-medium text-gray-700 mb-2">নথিপত্র আপলোড করুন (জাতীয় পরিচয়পত্র, দলিল ইত্যাদি)</label>
                  <div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                      <div className="space-y-1 text-center">
                          <UploadIcon className="mx-auto h-12 w-12 text-gray-400" />
                          <div className="flex text-sm text-gray-600">
                              <label htmlFor="file-upload" className="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500">
                                  <span>ফাইল নির্বাচন করুন</span>
                                  <input id="file-upload" name="file-upload" type="file" className="sr-only" onChange={handleFileChange} multiple />
                              </label>
                              <p className="pl-1">অথবা এখানে ড্র্যাগ অ্যান্ড ড্রপ করুন</p>
                          </div>
                          <p className="text-xs text-gray-500">PNG, JPG, PDF (সর্বোচ্চ 20MB)</p>
                      </div>
                  </div>
                  {fileName && <p className="mt-2 text-sm text-gray-600">নির্বাচিত ফাইল: {fileName}</p>}
                </div>
              </div>
              
              {/* Payment Section */}
              <div>
                <h2 className="text-xl font-semibold text-gray-700 border-b pb-2 mb-6">মূল্য পরিশোধ</h2>
                <div className="p-4 bg-yellow-50 text-yellow-800 rounded-lg border border-yellow-200">
                  <p>এটি একটি ম্যানুয়াল পেমেন্ট পদ্ধতি। সেবামূল্য বিকাশ/নগদ/রকেট-এর মাধ্যমে পরিশোধ করে নিচের নির্ধারিত স্থানে ট্রানজেকশন আইডি প্রদান করুন।</p>
                  <p className="font-bold mt-2">বিকাশ/নগদ/রকেট নম্বর: 01311465050</p>
                </div>
                 <div className="mt-6">
                    <label htmlFor="trxId" className="block text-md font-medium text-gray-700 mb-1">ট্রানজেকশন আইডি (TrxID)</label>
                    <input type="text" id="trxId" name="trxId" required className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-green-500 focus:border-green-500" placeholder="e.g., 9C4EG8A4B2"/>
                  </div>
              </div>

               {submissionStatus === 'error' && (
                  <div className="text-center p-4 bg-red-50 text-red-700 rounded-lg">
                    আবেদন জমা দেওয়ার সময় একটি ত্রুটি হয়েছে। অনুগ্রহ করে পুনরায় চেষ্টা করুন।
                  </div>
                )}

              {/* Submit Button */}
              <div className="text-center pt-6">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full md:w-auto text-lg bg-green-600 hover:bg-green-700 text-white font-bold py-4 px-16 rounded-full transition-all duration-300 shadow-lg focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50 disabled:bg-gray-400 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? 'জমা হচ্ছে...' : 'আবেদন জমা দিন'}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default ApplicationPage;
