
import React, { useState, useEffect } from 'react';
import type { Service, Application } from '../types';
import { LoginIcon, DashboardIcon, UsersIcon, SettingsIcon, LogoutIcon, LandIcon, CitizenIcon, TaxIcon, EditIcon, DeleteIcon, XIcon } from '../components/Icons';

const ADMIN_USERNAME = 'Sobsheba';
const ADMIN_PASSWORD = 'SIR@1993jul';

interface AdminPageProps {
    services: Service[];
    applications: Application[];
    addService: (service: Service) => void;
    updateService: (service: Service) => void;
    deleteService: (serviceId: string) => void;
    updateApplicationStatus: (applicationId: string, status: 'Pending' | 'Processing' | 'Completed') => void;
}

const initialNewServiceState = {
    id: '',
    title: '',
    description: '',
    category: 'ভূমি সেবা' as 'ভূমি সেবা' | 'নাগরিক সেবা' | 'কর সেবা',
    requiredDocs: '',
    charge: '',
    time: '',
    icon: 'LandIcon',
};

const iconToString = (IconComponent: React.ElementType): string => {
    if (IconComponent === LandIcon) return 'LandIcon';
    if (IconComponent === CitizenIcon) return 'CitizenIcon';
    if (IconComponent === TaxIcon) return 'TaxIcon';
    return 'LandIcon';
};

const translateStatus = (status: 'Pending' | 'Processing' | 'Completed') => {
  const map = {
    Pending: 'অপেক্ষমান',
    Processing: 'প্রক্রিয়াধীন',
    Completed: 'সম্পন্ন',
  };
  return map[status];
};

const AdminPage: React.FC<AdminPageProps> = ({ services, applications, addService, updateService, deleteService, updateApplicationStatus }) => {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    
    const [newService, setNewService] = useState(initialNewServiceState);
    const [addServiceSuccess, setAddServiceSuccess] = useState(false);

    const [editingService, setEditingService] = useState<Service | null>(null);
    const [editFormState, setEditFormState] = useState(initialNewServiceState);

    const [selectedApplication, setSelectedApplication] = useState<Application | null>(null);

    useEffect(() => {
        if (editingService) {
            setEditFormState({
                ...editingService,
                requiredDocs: editingService.requiredDocs.join(', '),
                icon: iconToString(editingService.icon),
            });
        }
    }, [editingService]);

    const handleLogin = (e: React.FormEvent) => {
        e.preventDefault();
        if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) {
            setIsLoggedIn(true); setError(''); setUsername(''); setPassword('');
        } else {
            setError('ব্যবহারকারীর নাম অথবা পাসওয়ার্ড সঠিক নয়।');
        }
    };
    
    const handleLogout = () => setIsLoggedIn(false);

    const handleNewServiceChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setNewService(prev => ({ ...prev, [name]: value }));
    };
    
    const handleEditFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setEditFormState(prev => ({...prev, [name]: value}));
    };

    const stringToIcon = (iconString: string) => {
        const iconMap = { LandIcon, CitizenIcon, TaxIcon };
        return iconMap[iconString as keyof typeof iconMap] || LandIcon;
    };

    const handleAddService = (e: React.FormEvent) => {
        e.preventDefault();
        const newServiceToAdd: Service = {
            id: `service-${Date.now()}`,
            ...newService,
            requiredDocs: newService.requiredDocs.split(',').map(s => s.trim()),
            icon: stringToIcon(newService.icon),
        };
        addService(newServiceToAdd);
        setNewService(initialNewServiceState);
        setAddServiceSuccess(true);
        setTimeout(() => setAddServiceSuccess(false), 3000);
    };
    
    const handleUpdateService = (e: React.FormEvent) => {
        e.preventDefault();
        if (!editingService) return;
        
        const updatedServiceData: Service = {
            ...editingService,
            ...editFormState,
            requiredDocs: editFormState.requiredDocs.split(',').map(s => s.trim()),
            icon: stringToIcon(editFormState.icon),
        };
        
        updateService(updatedServiceData);
        setEditingService(null);
    };

    const handleDeleteService = (serviceId: string) => {
        if (window.confirm('আপনি কি নিশ্চিতভাবে এই সেবাটি মুছে ফেলতে চান?')) {
            deleteService(serviceId);
        }
    };
    
    const handleStatusUpdate = (status: 'Processing' | 'Completed') => {
        if (selectedApplication) {
            updateApplicationStatus(selectedApplication.id, status);
            setSelectedApplication(prevApp => prevApp ? { ...prevApp, status } : null);
        }
    };

    if (!isLoggedIn) {
        return (
            <div className="flex items-center justify-center min-h-[calc(100vh-160px)] bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
                <div className="max-w-md w-full space-y-8">
                    <div><h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">অ্যাডমিন প্যানেলে লগইন করুন</h2></div>
                    <form className="mt-8 space-y-6 bg-white p-8 rounded-lg shadow-lg" onSubmit={handleLogin}>
                        <div className="rounded-md shadow-sm -space-y-px">
                             <div>
                                <label htmlFor="username" className="sr-only">ব্যবহারকারীর নাম</label>
                                <input id="username" name="username" type="text" required value={username} onChange={(e) => setUsername(e.target.value)} className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm" placeholder="ব্যবহারকারীর নাম" />
                            </div>
                            <div>
                                <label htmlFor="password"className="sr-only">পাসওয়ার্ড</label>
                                <input id="password" name="password" type="password" autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm" placeholder="পাসওয়ার্ড" />
                            </div>
                        </div>
                        {error && <p className="text-sm text-red-600 text-center">{error}</p>}
                        <div><button type="submit" className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"><span className="absolute left-0 inset-y-0 flex items-center pl-3"><LoginIcon className="h-5 w-5 text-green-500 group-hover:text-green-400" /></span>লগইন করুন</button></div>
                    </form>
                </div>
            </div>
        );
    }
    
    return (
        <div className="py-12 bg-gray-100">
            <div className="container mx-auto px-4">
                 <div className="flex justify-between items-center mb-8">
                    <h1 className="text-3xl font-bold text-gray-800">অ্যাডমিন ড্যাশবোর্ড</h1>
                    <button onClick={handleLogout} className="flex items-center bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded-lg transition-colors"><LogoutIcon className="h-5 w-5 mr-2"/>লগআউট</button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-1 gap-8">
                    <div className="bg-white p-6 rounded-lg shadow-md">
                        <h2 className="text-xl font-semibold text-gray-700 mb-4 flex items-center"><DashboardIcon className="w-6 h-6 mr-2 text-green-600"/>সকল আবেদন</h2>
                        <div className="overflow-x-auto">
                             <table className="min-w-full">
                                <thead className="bg-gray-100">
                                    <tr>
                                        <th className="px-4 py-2 text-left">আবেদন আইডি</th>
                                        <th className="px-4 py-2 text-left">সেবার নাম</th>
                                        <th className="px-4 py-2 text-left">আবেদনকারী</th>
                                        <th className="px-4 py-2 text-left">অবস্থা</th>
                                        <th className="px-4 py-2 text-left">কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {applications.length > 0 ? applications.map(app => (
                                        <tr key={app.id} className="border-b hover:bg-gray-50">
                                            <td className="px-4 py-2">{app.id}</td>
                                            <td className="px-4 py-2">{services.find(s => s.id === app.serviceId)?.title || 'অজানা সেবা'}</td>
                                            <td className="px-4 py-2">{app.fullName}</td>
                                            <td className="px-4 py-2">
                                                <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                                                    app.status === 'Pending' ? 'bg-yellow-200 text-yellow-800' :
                                                    app.status === 'Completed' ? 'bg-green-200 text-green-800' : 'bg-blue-200 text-blue-800'
                                                }`}>
                                                    {translateStatus(app.status)}
                                                </span>
                                            </td>
                                            <td className="px-4 py-2">
                                                <button onClick={() => setSelectedApplication(app)} className="text-sm bg-blue-500 text-white py-1 px-3 rounded-lg hover:bg-blue-600">বিস্তারিত</button>
                                            </td>
                                        </tr>
                                    )) : (
                                        <tr><td colSpan={5} className="text-center py-4 text-gray-500">কোনো নতুন আবেদন পাওয়া যায়নি।</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div className="bg-white p-6 rounded-lg shadow-md">
                        <h2 className="text-xl font-semibold text-gray-700 mb-4 flex items-center"><SettingsIcon className="w-6 h-6 mr-2 text-green-600"/>সেবা ব্যবস্থাপনা</h2>
                        <div className="overflow-x-auto">
                            <table className="min-w-full">
                                <thead className="bg-gray-100">
                                    <tr>
                                        <th className="px-4 py-2 text-left">শিরোনাম</th>
                                        <th className="px-4 py-2 text-left">বিভাগ</th>
                                        <th className="px-4 py-2 text-left">মূল্য</th>
                                        <th className="px-4 py-2 text-left">কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {services.map(service => (
                                        <tr key={service.id} className="border-b hover:bg-gray-50">
                                            <td className="px-4 py-2 font-medium">{service.title}</td>
                                            <td className="px-4 py-2">{service.category}</td>
                                            <td className="px-4 py-2">{service.charge}</td>
                                            <td className="px-4 py-2 flex items-center gap-2">
                                                <button onClick={() => setEditingService(service)} className="text-blue-600 hover:text-blue-800 p-1"><EditIcon className="w-5 h-5"/></button>
                                                <button onClick={() => handleDeleteService(service.id)} className="text-red-600 hover:text-red-800 p-1"><DeleteIcon className="w-5 h-5"/></button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div className="bg-white p-6 rounded-lg shadow-md">
                         <h2 className="text-xl font-semibold text-gray-700 mb-4 flex items-center"><DashboardIcon className="w-6 h-6 mr-2 text-green-600"/>নতুন সেবা যুক্ত করুন</h2>
                        {addServiceSuccess && <p className="text-sm text-green-600 mb-4">নতুন সেবা সফলভাবে যুক্ত হয়েছে!</p>}
                        <form onSubmit={handleAddService} className="grid grid-cols-1 md:grid-cols-2 gap-6">
                             <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">সেবার শিরোনাম</label><input type="text" name="title" value={newService.title} onChange={handleNewServiceChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                            <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">সেবার বিবরণ</label><textarea name="description" value={newService.description} onChange={handleNewServiceChange} required rows={3} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">বিভাগ</label><select name="category" value={newService.category} onChange={handleNewServiceChange} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2"><option>ভূমি সেবা</option><option>নাগরিক সেবা</option><option>কর সেবা</option></select></div>
                             <div><label className="block text-sm font-medium text-gray-700">আইকন</label><select name="icon" value={newService.icon} onChange={handleNewServiceChange} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2"><option value="LandIcon">ভূমি আইকন</option><option value="CitizenIcon">নাগরিক আইকন</option><option value="TaxIcon">কর আইকন</option></select></div>
                             <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">প্রয়োজনীয় নথিপত্র (কমা দ্বারা পৃথক করুন)</label><input type="text" name="requiredDocs" value={newService.requiredDocs} onChange={handleNewServiceChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">সেবামূল্য</label><input type="text" name="charge" value={newService.charge} onChange={handleNewServiceChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">প্রয়োজনীয় সময়</label><input type="text" name="time" value={newService.time} onChange={handleNewServiceChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                            <div className="md:col-span-2 text-right"><button type="submit" className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg transition-colors">সেবা যুক্ত করুন</button></div>
                        </form>
                    </div>

                </div>
            </div>

            {selectedApplication && (
                <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50">
                    <div className="bg-white p-8 rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                        <div className="flex justify-between items-center mb-6 border-b pb-4">
                            <h2 className="text-2xl font-bold text-gray-800">আবেদনের বিবরণ</h2>
                            <button onClick={() => setSelectedApplication(null)} className="text-gray-500 hover:text-gray-800"><XIcon className="w-6 h-6"/></button>
                        </div>
                        <div className="space-y-4">
                            <div><span className="font-semibold text-gray-600">আবেদন আইডি:</span> <span className="text-gray-800">{selectedApplication.id}</span></div>
                            <div><span className="font-semibold text-gray-600">সেবার নাম:</span> <span className="text-gray-800">{services.find(s => s.id === selectedApplication.serviceId)?.title}</span></div>
                            <div><span className="font-semibold text-gray-600">আবেদনকারীর নাম:</span> <span className="text-gray-800">{selectedApplication.fullName}</span></div>
                            <div><span className="font-semibold text-gray-600">মোবাইল নম্বর:</span> <span className="text-gray-800">{selectedApplication.mobile}</span></div>
                            <div><span className="font-semibold text-gray-600">ঠিকানা:</span> <span className="text-gray-800">{selectedApplication.address}</span></div>
                            <div><span className="font-semibold text-gray-600">TrxID:</span> <span className="text-gray-800">{selectedApplication.trxId}</span></div>
                             <div>
                                <span className="font-semibold text-gray-600">বর্তমান অবস্থা:</span>
                                <span className={`ml-2 px-3 py-1 text-sm font-semibold rounded-full ${
                                    selectedApplication.status === 'Pending' ? 'bg-yellow-200 text-yellow-800' :
                                    selectedApplication.status === 'Completed' ? 'bg-green-200 text-green-800' : 'bg-blue-200 text-blue-800'
                                }`}>
                                    {translateStatus(selectedApplication.status)}
                                </span>
                            </div>
                        </div>
                         <div className="mt-8 pt-6 border-t flex justify-end gap-4">
                            {selectedApplication.status === 'Pending' && (
                                <button onClick={() => handleStatusUpdate('Processing')} className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg">প্রক্রিয়াধীন হিসেবে চিহ্নিত করুন</button>
                            )}
                             {selectedApplication.status !== 'Completed' && (
                                <button onClick={() => handleStatusUpdate('Completed')} className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg">সম্পন্ন হিসেবে চিহ্নিত করুন</button>
                             )}
                            <button type="button" onClick={() => setSelectedApplication(null)} className="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg">বন্ধ করুন</button>
                        </div>
                    </div>
                </div>
            )}

            {editingService && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white p-8 rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-2xl font-bold text-gray-800">সেবা সম্পাদন করুন</h2>
                            <button onClick={() => setEditingService(null)} className="text-gray-500 hover:text-gray-800"><XIcon className="w-6 h-6"/></button>
                        </div>
                         <form onSubmit={handleUpdateService} className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">সেবার শিরোনাম</label><input type="text" name="title" value={editFormState.title} onChange={handleEditFormChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                            <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">সেবার বিবরণ</label><textarea name="description" value={editFormState.description} onChange={handleEditFormChange} required rows={3} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">বিভাগ</label><select name="category" value={editFormState.category} onChange={handleEditFormChange} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2"><option>ভূমি সেবা</option><option>নাগরিক সেবা</option><option>কর সেবা</option></select></div>
                             <div><label className="block text-sm font-medium text-gray-700">আইকন</label><select name="icon" value={editFormState.icon} onChange={handleEditFormChange} className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2"><option value="LandIcon">ভূমি আইকন</option><option value="CitizenIcon">নাগরিক আইকন</option><option value="TaxIcon">কর আইকন</option></select></div>
                             <div className="md:col-span-2"><label className="block text-sm font-medium text-gray-700">প্রয়োজনীয় নথিপত্র (কমা দ্বারা পৃথক করুন)</label><input type="text" name="requiredDocs" value={editFormState.requiredDocs} onChange={handleEditFormChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">সেবামূল্য</label><input type="text" name="charge" value={editFormState.charge} onChange={handleEditFormChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                             <div><label className="block text-sm font-medium text-gray-700">প্রয়োজনীয় সময়</label><input type="text" name="time" value={editFormState.time} onChange={handleEditFormChange} required className="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2" /></div>
                            <div className="md:col-span-2 flex justify-end gap-4 mt-4">
                                <button type="button" onClick={() => setEditingService(null)} className="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-6 rounded-lg transition-colors">বাতিল</button>
                                <button type="submit" className="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-6 rounded-lg transition-colors">হালনাগাদ করুন</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AdminPage;
