import React, { useEffect, useState } from 'react'
import { Plus, ChevronRight, Save } from 'lucide-react'
import { KnowledgeGroup, UpdateGroupData } from '../types'
import { useLanguage } from '../contexts/LanguageContext'

interface EditNotebookDrawerProps {
    isOpen: boolean
    onClose: () => void
    notebook: KnowledgeGroup
    onUpdate: (id: string, data: UpdateGroupData) => Promise<void>
}

export const EditNotebookDrawer: React.FC<EditNotebookDrawerProps> = ({
    isOpen,
    onClose,
    notebook,
    onUpdate,
}) => {
    const { t } = useLanguage()
    const [name, setName] = useState(notebook.name)
    const [description, setDescription] = useState(notebook.description || '')
    const [intro, setIntro] = useState(notebook.intro || '')
    const [isSubmitting, setIsSubmitting] = useState(false)

    // Reset form when notebook changes or drawer opens
    useEffect(() => {
        if (isOpen) {
            setName(notebook.name)
            setDescription(notebook.description || '')
            setIntro(notebook.intro || '')
        }
    }, [isOpen, notebook])

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        if (!name.trim()) return

        try {
            setIsSubmitting(true)
            await onUpdate(notebook.id, {
                name: name.trim(),
                description: description.trim(),
                intro: intro.trim(),
            })
            onClose()
        } catch (error) {
            console.error('Failed to update notebook:', error)
            alert(t('updateFailedRetry'))
        } finally {
            setIsSubmitting(false)
        }
    }

    return (
        <>
            {/* Backdrop */}
            {isOpen && (
                <div
                    className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40 transition-opacity duration-300"
                    onClick={onClose}
                />
            )}

            {/* Drawer */}
            <div
                className={`fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl z-50 transform transition-transform duration-300 ease-out ${isOpen ? 'translate-x-0' : 'translate-x-full'
                    }`}
            >
                <div className="flex flex-col h-full">
                    {/* Header */}
                    <div className="flex items-center justify-between px-6 py-4 border-b bg-slate-50">
                        <h2 className="text-xl font-semibold text-slate-800 flex items-center gap-2">
                            <Save className="w-5 h-5 text-blue-600" />
                            {t('editNotebookTitle')}
                        </h2>
                        <button
                            onClick={onClose}
                            className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-200 rounded-full transition-colors"
                        >
                            <ChevronRight size={24} />
                        </button>
                    </div>

                    {/* Content */}
                    <div className="flex-1 overflow-y-auto p-6">
                        <form id="edit-notebook-form" onSubmit={handleSubmit} className="space-y-6">
                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">
                                    {t('name')} <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="text"
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                    className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50"
                                    placeholder={t('namePlaceholder')}
                                    required
                                    autoFocus
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">
                                    {t('shortDescription')}
                                </label>
                                <input
                                    type="text"
                                    value={description}
                                    onChange={(e) => setDescription(e.target.value)}
                                    className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50"
                                    placeholder={t('descPlaceholder')}
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-700 mb-1">
                                    {t('detailedIntro')}
                                </label>
                                <textarea
                                    value={intro}
                                    onChange={(e) => setIntro(e.target.value)}
                                    className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50 h-64 resize-none leading-relaxed"
                                    placeholder={t('introPlaceholder')}
                                />
                                <p className="mt-1 text-xs text-slate-500">{t('introHelp')}</p>
                            </div>
                        </form>
                    </div>

                    {/* Footer */}
                    <div className="p-6 border-t bg-slate-50">
                        <button
                            type="submit"
                            form="edit-notebook-form"
                            disabled={isSubmitting || !name.trim()}
                            className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-blue-600/20"
                        >
                            <Save size={20} />
                            {isSubmitting ? t('saving') : t('save')}
                        </button>
                    </div>
                </div>
            </div>
        </>
    )
}
