import { useState, useEffect } from 'react'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import Modal from '../components/common/Modal'
import Input from '../components/common/Input'
import Button from '../components/common/Button'

const NotificationModal = ({ isOpen, onClose, onSubmit, notification = null }) => {
    const initialFormData = {
        title: '',
        description: '',
        status: 1,
        type: 'general'
    }

    const [formData, setFormData] = useState(initialFormData)
    const [errors, setErrors] = useState({})
    const [isLoading, setIsLoading] = useState(false)

    useEffect(() => {
        if (notification) {
            setFormData({
                title: notification.title || '',
                description: notification.description || '',
                status: notification.status ?? 1,
                type: notification.type || 'general'
            })
        } else {
            setFormData(initialFormData)
        }
    }, [notification, isOpen])

    const handleChange = (e) => {
        const { name, value } = e.target
        setFormData(prev => ({
            ...prev,
            [name]: value
        }))
    }

    const handleEditorChange = (event, editor) => {
        const data = editor.getData()
        setFormData(prev => ({
            ...prev,
            description: data
        }))
    }

    const validateForm = () => {
        const newErrors = {}
        if (!formData.title) newErrors.title = 'Title is required'
        setErrors(newErrors)
        return Object.keys(newErrors).length === 0
    }

    const handleSubmit = async () => {
        if (!validateForm()) return

        setIsLoading(true)
        try {
            await onSubmit(formData)
            if (!notification) setFormData(initialFormData)
            setErrors({})
        } finally {
            setIsLoading(false)
        }
    }

    return (
        <Modal
            isOpen={isOpen}
            onClose={onClose}
            title={notification ? '📋 Edit Broadcast Notification' : '📢 Create New Broadcast'}
            size="4xl"
        >
            <div className="max-h-[75vh] overflow-y-auto px-2 space-y-8 custom-scrollbar pb-2">

                {/* ── BROADCAST HEADER ── */}
                <div className="space-y-6">
                    <Input
                        label="Broadcast Headline"
                        name="title"
                        value={formData.title}
                        onChange={handleChange}
                        error={errors.title}
                        required
                        placeholder="e.g., Scheduled Maintenance Announcement..."
                        className="text-xl font-black"
                    />

                    <div className="grid grid-cols-1 gap-6 bg-gray-50 p-6 rounded-3xl border-2 border-dashed border-[#409CA4]/20">
                        <div>
                            <label className="block text-lg font-black mb-2 text-[#111827]">Publication Status</label>
                            <select
                                name="status"
                                className="w-full px-4 py-4 rounded-xl border-2 border-gray-200 bg-white focus:border-[#409CA4] outline-none font-black text-[#111827] cursor-pointer"
                                value={formData.status}
                                onChange={(e) => setFormData(prev => ({ ...prev, status: parseInt(e.target.value) }))}
                            >
                                <option value={1}>✅ LIVE & VISIBLE</option>
                                <option value={0}>❌ HIDDEN / DRAFT</option>
                            </select>
                        </div>
                    </div>
                </div>

                {/* ── RICH CONTENT ── */}
                <div className="space-y-3">
                    <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-[#e8713a] rounded-lg flex items-center justify-center text-white shadow-md">
                            <span className="text-lg">✍️</span>
                        </div>
                        <label className="text-xl font-black text-[#111827]">Broadcast Content</label>
                    </div>
                    <div className="prose-lg max-w-none border-4 border-gray-100 rounded-3xl overflow-hidden shadow-inner ring-4 ring-gray-50">
                        <CKEditor
                            editor={ClassicEditor}
                            data={formData.description}
                            onChange={handleEditorChange}
                            config={{
                                placeholder: 'Draft your comprehensive broadcast message here...',
                                toolbar: [
                                    'heading', '|', 'bold', 'italic', 'link', '|', 'bulletedList', 'numberedList', 'blockQuote', '|', 'undo', 'redo'
                                ]
                            }}
                        />
                    </div>
                </div>

                <div className="flex gap-4 justify-end pt-6 border-t-4 border-gray-100 mt-4 pb-2">
                    <Button onClick={onClose} variant="outline" size="lg" disabled={isLoading} className="px-8 border-2">Cancel</Button>
                    <Button onClick={handleSubmit} isLoading={isLoading} size="lg" className="px-10">
                        {notification ? '📝 Save Changes' : '🚀 Publish Broadcast'}
                    </Button>
                </div>
            </div>
        </Modal>
    )
}

export default NotificationModal
