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

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

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

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

    if (!isOpen) return null

    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(),
            })
            onClose()
        } catch (error) {
            console.error('Failed to update notebook:', error)
            showError(t('updateFailedRetry'))
        } finally {
            setIsSubmitting(false)
        }
    }

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
            <div className="bg-white rounded-xl shadow-xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200">
                <div className="flex justify-between items-center px-6 py-4 border-b">
                    <h2 className="text-lg font-semibold text-slate-800">{t('editNotebookTitle')}</h2>
                    <button
                        onClick={onClose}
                        className="text-slate-400 hover:text-slate-600 transition-colors"
                    >
                        <X size={20} />
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">
                            {t('name')}
                        </label>
                        <input
                            type="text"
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder={t('namePlaceholder')}
                            required
                        />
                    </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-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder={t('descPlaceholder')}
                        />
                    </div>

                    <div className="flex justify-end pt-2">
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg mr-2 transition-colors"
                        >
                            {t('cancel')}
                        </button>
                        <button
                            type="submit"
                            disabled={isSubmitting || !name.trim()}
                            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <Save size={18} />
                            {isSubmitting ? t('saving') : t('save')}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    )
}
