import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { ArrowRight, Save, Sparkles, Zap, Wand2, RefreshCw, Loader2, Plus, ChevronDown, Bot, AlertTriangle } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { LinkedBotsSection } from '@/components/common/LinkedBotsSection'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { apiClient } from '@/api/client'
import { t, sprintf } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'

interface Personality {
    id: number
    name: string
    slug: string
    description: string | null
    system_prompt: string
    tone: string
    proactive_engagement: number
    proactive_delay_seconds: number
    custom_instructions: string | null
    is_default: number
    is_system: number
}

interface Tone {
    id: number
    name: string
    slug: string
    emoji: string | null
    description: string | null
    system_prompt: string | null
    is_system: number
    is_active: number
}

interface FormData {
    name: string
    slug: string
    description: string
    system_prompt: string
    tone: string
    proactive_engagement: boolean
    proactive_delay_seconds: number
    custom_instructions: string
    is_default: boolean
}

const defaultFormData: FormData = {
    name: '',
    slug: '',
    description: '',
    system_prompt: `You are a friendly and professional customer service representative.

Behavior guidelines:
- Take every question seriously and provide comprehensive answers
- Maintain a warm and inviting tone

Communication style:
- Use friendly and accessible language
- Be concise yet thorough`,
    tone: 'friendly',
    proactive_engagement: true,
    proactive_delay_seconds: 4,
    custom_instructions: '',
    is_default: false,
}

export function PersonalityDetail() {
    const { id } = useParams()
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const isNew = !id || id === 'new'
    const returnTo = searchParams.get('returnTo')

    // Redirect to archive when language changes while editing an existing entity
    const prevLangRef = useRef(currentLanguage)
    useEffect(() => {
        if (prevLangRef.current !== currentLanguage && !isNew) {
            navigate('/personalities')
        }
        prevLangRef.current = currentLanguage
    }, [currentLanguage, isNew, navigate])

    const [formData, setFormData] = useState<FormData>(defaultFormData)
    const [isSaving, setIsSaving] = useState(false)
    const [showSavedAnimation, setShowSavedAnimation] = useState(false)

    // Fix: Prevent save-button flicker between "Saved" and "Unsaved" states.
    const justSavedRef = useRef(false)
    const saveCooldownRef = useRef(false)
    const [isGeneratingPrompt, setIsGeneratingPrompt] = useState(false)
    const [isImprovingPrompt, setIsImprovingPrompt] = useState(false)
    const [showImprovementMenu, setShowImprovementMenu] = useState(false)
    const [showToneModal, setShowToneModal] = useState(false)
    const [newToneName, setNewToneName] = useState('')
    const [newToneDescription, setNewToneDescription] = useState('')
    const [isCreatingTone, setIsCreatingTone] = useState(false)
    const [isDataLoaded, setIsDataLoaded] = useState(false)

    // Fetch personality if editing
    const { data: personalityData, isLoading } = useQuery({
        queryKey: ['personality', id, currentLanguage],
        queryFn: () => apiClient.get<{ data: { personality: Personality } }>(`personalities/${id}`),
        enabled: !isNew && !!id,
    })

    // Fetch available tones
    const { data: tonesData } = useQuery({
        queryKey: ['tones', currentLanguage],
        queryFn: () => apiClient.get<{ data: { tones: Tone[] } }>('tones', { language: currentLanguage }),
    })

    // Create mutation
    const createPersonality = useMutation({
        mutationFn: (data: Record<string, unknown>) => apiClient.post<{ success: boolean; data: { personality: Personality } }>('personalities', { ...data, language: currentLanguage }),
        onSuccess: (response) => {
            queryClient.invalidateQueries({ queryKey: ['personalities', currentLanguage] })
            const newId = response?.data?.personality?.id
            if (newId) {
                navigate(`/personalities/${newId}`)
            } else {
                navigate('/personalities')
            }
        },
    })

    // Update mutation
    const updatePersonality = useMutation({
        mutationFn: (data: Record<string, unknown>) => apiClient.put(`personalities/${id}`, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['personalities', currentLanguage] })
            queryClient.invalidateQueries({ queryKey: ['personality', id] })
        },
    })

    // Load personality data
    useEffect(() => {
        if (personalityData?.data?.personality) {
            // Fix: Skip overwriting formData with server response right after a save.
            if (justSavedRef.current) {
                justSavedRef.current = false
                return
            }
            const p = personalityData.data.personality
            // Convert values to boolean (handle both number and string from API)
            const toBool = (val: unknown) => val === 1 || val === '1' || val === true
            setFormData({
                name: p.name || '',
                slug: p.slug || '',
                description: p.description || '',
                system_prompt: p.system_prompt || '',
                tone: p.tone || 'friendly',
                proactive_engagement: toBool(p.proactive_engagement),
                proactive_delay_seconds: Number(p.proactive_delay_seconds) || 8,
                custom_instructions: p.custom_instructions || '',
                is_default: toBool(p.is_default),
            })
            setIsDataLoaded(true)
        }
    }, [personalityData])

    // Unsaved changes detection
    const {
        hasUnsavedChanges,
        checkNavigationSafe,
        setOriginalData,
        showModal: showUnsavedModal,
        saveError,
        modalActions,
    } = useUnsavedChanges({
        currentData: formData,
        onSave: async () => { await handleSave() },
        onDiscard: (original) => {
            setFormData(original)
        },
        isLoaded: isNew || isDataLoaded,
    })

    const tones = tonesData?.data?.tones || []

    const handleChange = (field: keyof FormData, value: unknown) => {
        setFormData((prev) => ({ ...prev, [field]: value }))

        // Auto-generate slug from name for new personalities (ASCII only)
        if (field === 'name' && isNew && typeof value === 'string') {
            // Only keep ASCII letters, numbers, spaces and hyphens
            const slug = value
                .toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '') // Remove non-ASCII (including Hebrew)
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-') // Remove multiple hyphens
                .replace(/^-|-$/g, '') // Remove leading/trailing hyphens
            // If slug is empty (Hebrew name), generate timestamp-based slug
            const finalSlug = slug || `personality-${Date.now()}`
            setFormData((prev) => ({ ...prev, slug: finalSlug }))
        }
    }

    // Handle tone change - always apply selected tone prompt when available (same behavior as "reset tone")
    const handleToneChange = (toneSlug: string) => {
        const selectedTone = tones.find(t => t.slug === toneSlug)
        
        setFormData((prev) => ({
            ...prev,
            tone: toneSlug,
            ...(selectedTone?.system_prompt ? {
                system_prompt: selectedTone.system_prompt
            } : {})
        }))
    }

    // Load system prompt from selected tone
    const loadPromptFromTone = () => {
        const selectedTone = tones.find(t => t.slug === formData.tone)
        if (selectedTone?.system_prompt) {
            setFormData((prev) => ({
                ...prev,
                system_prompt: selectedTone.system_prompt || prev.system_prompt
            }))
        }
    }

    // Generate new system prompt using AI
    const generateNewPrompt = async () => {
        const selectedTone = tones.find(t => t.slug === formData.tone)
        if (!selectedTone) return

        setIsGeneratingPrompt(true)
        try {
            const response = await apiClient.post<{ data: { system_prompt: string } }>('tones/generate-prompt', {
                name: selectedTone.name,
                description: selectedTone.description || formData.description,
                language: currentLanguage,
            })

            const generatedPrompt = response.data?.system_prompt
            if (generatedPrompt) {
                setFormData((prev) => ({ ...prev, system_prompt: generatedPrompt }))
            }
        } catch (error) {
            console.error('Error generating prompt:', error)
            alert(t('Error generating prompt. Please try again.'))
        } finally {
            setIsGeneratingPrompt(false)
        }
    }

    // Improve existing system prompt
    const improvePrompt = async (improvementType: string) => {
        setShowImprovementMenu(false)
        setIsImprovingPrompt(true)
        
        try {
            const selectedTone = tones.find(t => t.slug === formData.tone)
            const response = await apiClient.post<{ data: { system_prompt: string } }>('tones/improve-prompt', {
                current_prompt: formData.system_prompt,
                tone_name: selectedTone?.name || '',
                improvement_type: improvementType,
                language: currentLanguage,
            })

            const improvedPrompt = response.data?.system_prompt
            if (improvedPrompt) {
                setFormData((prev) => ({ ...prev, system_prompt: improvedPrompt }))
            }
        } catch (error) {
            console.error('Error improving prompt:', error)
            alert(t('Error improving prompt. Please try again.'))
        } finally {
            setIsImprovingPrompt(false)
        }
    }

    // Create new tone
    const createNewTone = async () => {
        if (!newToneName.trim()) return

        setIsCreatingTone(true)
        try {
            // Generate system prompt for the new tone
            const generateResponse = await apiClient.post<{ data: { system_prompt: string } }>('tones/generate-prompt', {
                name: newToneName,
                description: newToneDescription,
                language: currentLanguage,
            })

            const generatedPrompt = generateResponse.data?.system_prompt || ''

            // Create the tone
            const createResponse = await apiClient.post<{ data: { tone: Tone } }>('tones', {
                name: newToneName.trim(),
                description: newToneDescription.trim() || undefined,
                system_prompt: generatedPrompt,
                emoji: '✨',
                language: currentLanguage,
            })

            // Refresh tones list
            queryClient.invalidateQueries({ queryKey: ['tones', currentLanguage] })

            // Select the new tone
            const newTone = createResponse.data?.tone
            if (newTone) {
                setFormData((prev) => ({
                    ...prev,
                    tone: newTone.slug,
                    system_prompt: generatedPrompt || prev.system_prompt,
                }))
            }

            // Close modal
            setShowToneModal(false)
            setNewToneName('')
            setNewToneDescription('')
        } catch (error) {
            console.error('Error creating tone:', error)
            alert(t('Error creating tone. Please try again.'))
        } finally {
            setIsCreatingTone(false)
        }
    }

    const handleSave = async () => {
        setIsSaving(true)
        try {
            const dataToSave = {
                ...formData,
                proactive_engagement: formData.proactive_engagement ? 1 : 0,
                proactive_delay_seconds: Math.max(1, Math.min(60, formData.proactive_delay_seconds || 8)),
                custom_instructions: formData.custom_instructions || '',
                is_default: formData.is_default ? 1 : 0,
            }

            if (isNew) {
                await createPersonality.mutateAsync(dataToSave)
            } else {
                await updatePersonality.mutateAsync(dataToSave)
                // Fix: Tell the load effect to skip overwriting formData on the next refetch
                justSavedRef.current = true
                // Show cute robot animation on successful save
                saveCooldownRef.current = true
                setShowSavedAnimation(true)
                setTimeout(() => {
                    setShowSavedAnimation(false)
                    saveCooldownRef.current = false
                }, 2000)
                // Reset original data after successful save
                setOriginalData()
            }
        } finally {
            setIsSaving(false)
        }
    }

    if (!isNew && isLoading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600" />
            </div>
        )
    }

    // Handle back navigation with unsaved changes check
    const handleBack = () => {
        checkNavigationSafe(() => {
            navigate(returnTo || '/personalities')
        })
    }

    return (
        <div className="space-y-6">
            {/* Unsaved Changes Modal */}
            <UnsavedChangesModal
                isOpen={showUnsavedModal}
                onCancel={modalActions.onCancel}
                onDiscard={modalActions.onDiscard}
                onSave={modalActions.onSave}
                onSaveAlways={modalActions.onSaveAlways}
                isSaving={isSaving}
                errorMessage={saveError}
            />

            <PageHeader
                title={isNew ? t('New Personality') : sprintf(t('Editing %s'), formData.name)}
                subtitle={t('Define the bot character and personality')}
            >
                <div className="flex gap-2">
                    <Button variant="outline" onClick={handleBack}>
                        <ArrowRight className="w-4 h-4 me-2" />
                        {t('Back')}
                    </Button>
                    <button
                        onClick={handleSave}
                        disabled={isSaving || !formData.name || !formData.system_prompt}
                        className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed ${
                            showSavedAnimation 
                                ? 'bg-green-500 hover:bg-green-600' 
                                : (hasUnsavedChanges && !saveCooldownRef.current)
                                    ? 'bg-amber-500 hover:bg-amber-600 animate-pulse'
                                    : 'bg-primary-600 hover:bg-primary-700'
                        } text-white`}
                    >
                        {showSavedAnimation ? (
                            <Bot className="w-4 h-4 animate-wiggle" />
                        ) : (
                            <Save className="w-4 h-4" />
                        )}
                        {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved! ✓') : (hasUnsavedChanges && !saveCooldownRef.current) ? t('Save Changes') : t('Save')}
                    </button>
                </div>
            </PageHeader>

            {/* Unsaved changes indicator — suppressed during save animation cooldown */}
            {hasUnsavedChanges && !showSavedAnimation && !saveCooldownRef.current && (
                <div className="fixed bottom-4 left-4 bg-amber-100 text-amber-800 px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm z-40">
                    <AlertTriangle className="w-4 h-4" />
                    {t('You have unsaved changes')}
                </div>
            )}

            <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 min-w-0">
                {/* Main Form */}
                <div className="xl:col-span-2 space-y-6 min-w-0">
                    {/* Basic Info */}
                    <Card>
                        <CardContent className="space-y-4 pt-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium mb-1">
                                        {t('Personality Name')} <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        value={formData.name}
                                        onChange={(e) => handleChange('name', e.target.value)}
                                        placeholder={t('e.g.: Danny the Marketer')}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium mb-1">{t('Slug')}</label>
                                    <input
                                        type="text"
                                        value={formData.slug}
                                        onChange={(e) => handleChange('slug', e.target.value)}
                                        placeholder={t('Generated automatically')}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium mb-1">{t('Short Description')}</label>
                                <input
                                    type="text"
                                    value={formData.description}
                                    onChange={(e) => handleChange('description', e.target.value)}
                                    placeholder={t('Short description of the personality')}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                />
                            </div>

                            {/* Tone Selection */}
                            <div>
                                <label className="block text-sm font-medium mb-2">
                                    {t('Tone')} <span className="text-red-500">*</span>
                                </label>
                                <p className="text-xs text-gray-500 mb-3">
                                    {t('Selecting a tone will update the System Prompt accordingly')}
                                </p>
                                <div className="flex flex-wrap gap-2">
                                    {tones.map((tone) => (
                                        <button
                                            key={tone.id}
                                            type="button"
                                            onClick={() => handleToneChange(tone.slug)}
                                            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-all ${
                                                formData.tone === tone.slug
                                                    ? 'bg-primary-100 text-primary-700 border-primary-300 border-2 shadow-sm'
                                                    : 'bg-gray-100 hover:bg-gray-200 border-2 border-transparent'
                                            }`}
                                        >
                                            <span className="text-lg">{tone.emoji || '🎭'}</span>
                                            <span>{tone.name}</span>
                                        </button>
                                    ))}
                                    
                                    {/* Add New Tone Button */}
                                    <button
                                        type="button"
                                        onClick={() => setShowToneModal(true)}
                                        className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm bg-gray-50 hover:bg-gray-100 border-2 border-dashed border-gray-300 text-gray-600 transition-colors"
                                    >
                                        <Plus className="w-4 h-4" />
                                        <span>{t('Add Tone')}</span>
                                    </button>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* System Prompt */}
                    <Card>
                        <CardContent className="pt-6">
                            <div className="flex items-center justify-between mb-2">
                                <label className="block text-sm font-medium">
                                    <Sparkles className="w-4 h-4 inline me-1" />
                                    {t('Personality Definition (System Prompt)')} <span className="text-red-500">*</span>
                                </label>
                                
                                <div className="flex gap-2">
                                    {/* Load from tone */}
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={loadPromptFromTone}
                                        title={t('Reset to the selected tone built-in prompt')}
                                    >
                                        <RefreshCw className="w-4 h-4 me-1" />
                                        {t('Reset Tone')}
                                    </Button>
                                    
                                    {/* Generate new prompt */}
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={generateNewPrompt}
                                        disabled={isGeneratingPrompt}
                                        title={t('Generate a new prompt with AI')}
                                    >
                                        {isGeneratingPrompt ? (
                                            <Loader2 className="w-4 h-4 me-1 animate-spin" />
                                        ) : (
                                            <Wand2 className="w-4 h-4 me-1" />
                                        )}
                                        {t('Generate New')}
                                    </Button>
                                    
                                    {/* Improve prompt */}
                                    <div className="relative">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setShowImprovementMenu(!showImprovementMenu)}
                                            disabled={isImprovingPrompt || !formData.system_prompt.trim()}
                                            title={t('Improve the prompt')}
                                        >
                                            {isImprovingPrompt ? (
                                                <Loader2 className="w-4 h-4 me-1 animate-spin" />
                                            ) : (
                                                <Sparkles className="w-4 h-4 me-1" />
                                            )}
                                            {t('Improve')}
                                            <ChevronDown className="w-3 h-3 ms-1" />
                                        </Button>
                                        
                                        {showImprovementMenu && (
                                            <div className="absolute top-full end-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-10 min-w-[180px]">
                                                <button
                                                    onClick={() => improvePrompt('general')}
                                                    className="w-full px-4 py-2 text-sm text-start hover:bg-gray-100"
                                                >
                                                    🔧 {t('General Improvement')}
                                                </button>
                                                <button
                                                    onClick={() => improvePrompt('concise')}
                                                    className="w-full px-4 py-2 text-sm text-start hover:bg-gray-100"
                                                >
                                                    📝 {t('Make Shorter')}
                                                </button>
                                                <button
                                                    onClick={() => improvePrompt('detailed')}
                                                    className="w-full px-4 py-2 text-sm text-start hover:bg-gray-100"
                                                >
                                                    📚 {t('More Detailed')}
                                                </button>
                                                <button
                                                    onClick={() => improvePrompt('friendly')}
                                                    className="w-full px-4 py-2 text-sm text-start hover:bg-gray-100"
                                                >
                                                    😊 {t('More Friendly')}
                                                </button>
                                                <button
                                                    onClick={() => improvePrompt('professional')}
                                                    className="w-full px-4 py-2 text-sm text-start hover:bg-gray-100"
                                                >
                                                    💼 {t('More Professional')}
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                            
                            <p className="text-xs text-gray-500 mb-2">
                                {t('This text defines how the bot behaves and responds. You can edit manually or use the AI tools.')}
                            </p>
                            
                            <textarea
                                value={formData.system_prompt}
                                onChange={(e) => handleChange('system_prompt', e.target.value)}
                                rows={14}
                                placeholder={t('Define the bot character...')}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 font-mono text-sm"
                            />
                        </CardContent>
                    </Card>

                    {/* Custom Instructions */}
                    <Card>
                        <CardContent className="pt-6">
                            <label className="block text-sm font-medium mb-2">
                                {t('Custom Instructions')}
                            </label>
                            <p className="text-xs text-gray-500 mb-2">
                                {t('Custom instructions appended to the system prompt. These instructions will also apply to bots using this personality.')}
                            </p>
                            <textarea
                                value={formData.custom_instructions}
                                onChange={(e) => handleChange('custom_instructions', e.target.value)}
                                placeholder={t('Additional instructions for the bot, e.g.: Always suggest scheduling a meeting, use simple language...')}
                                rows={4}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm"
                            />
                        </CardContent>
                    </Card>
                </div>

                {/* Sidebar */}
                <div className="space-y-6">
                    {/* Behavior Settings */}
                    <Card>
                        <CardContent className="pt-6 space-y-4">
                            <h3 className="font-medium">{t('Behavior Settings')}</h3>
                            <p className="text-xs text-gray-500 -mt-2">
                                {t('These settings affect the bot behavior in practice')}
                            </p>

                            <div className="group relative">
                                <label className="flex items-center gap-3 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={formData.proactive_engagement}
                                        onChange={(e) => handleChange('proactive_engagement', e.target.checked)}
                                        className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                    />
                                    <div className="flex items-center gap-2">
                                        <Zap className="w-4 h-4 text-purple-600" />
                                        <span className="text-sm">{t('Proactive Chat')}</span>
                                    </div>
                                </label>
                                <div className="absolute hidden group-hover:block bg-gray-900 text-white text-xs rounded-lg px-3 py-2 -top-12 start-0 w-64 z-20 shadow-lg">
                                    {t('The bot will proactively offer help after the visitor stays on a page for a certain time')}
                                    <div className="absolute w-2 h-2 bg-gray-900 rotate-45 -bottom-1 start-4"></div>
                                </div>
                            </div>

                            {/* Proactive Delay - only show when proactive is enabled */}
                            {formData.proactive_engagement && (
                                <div className="mr-7 mt-2">
                                    <label className="flex items-center gap-3 text-sm text-gray-600">
                                        <span>{t('Delay before proactive:')}</span>
                                        <input
                                            type="number"
                                            min={1}
                                            max={60}
                                            value={formData.proactive_delay_seconds}
                                            onChange={(e) => handleChange('proactive_delay_seconds', Math.max(1, Math.min(60, parseInt(e.target.value) || 8)))}
                                            className="w-16 px-2 py-1 border border-gray-300 rounded text-center text-sm"
                                        />
                                        <span>{t('seconds')}</span>
                                    </label>
                                    <p className="text-xs text-gray-400 mt-1">
                                        {t('How long to wait after the bot response before sending a proactive message')}
                                    </p>
                                </div>
                            )}

                            <hr className="my-4" />

                            <label className="flex items-center gap-3 cursor-pointer">
                                <input
                                    type="checkbox"
                                    checked={formData.is_default}
                                    onChange={(e) => handleChange('is_default', e.target.checked)}
                                    className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                                />
                                <span className="text-sm font-medium">{t('Set as Default')}</span>
                            </label>
                        </CardContent>
                    </Card>

                    {/* Selected Tone Info */}
                    {formData.tone && (
                        <Card>
                            <CardContent className="pt-6">
                                <h3 className="font-medium mb-3">{t('Selected Tone')}</h3>
                                {(() => {
                                    const selectedTone = tones.find(t => t.slug === formData.tone)
                                    if (!selectedTone) return <p className="text-sm text-gray-400">{t('Not found')}</p>
                                    return (
                                        <div className="flex items-start gap-3">
                                            <span className="text-3xl">{selectedTone.emoji || '🎭'}</span>
                                            <div>
                                                <p className="font-medium">{selectedTone.name}</p>
                                                {selectedTone.description && (
                                                    <p className="text-sm text-gray-500 mt-1">
                                                        {selectedTone.description}
                                                    </p>
                                                )}
                                                {selectedTone.is_system === 1 && (
                                                    <span className="inline-block text-xs text-blue-600 mt-2">
                                                        {t('System Tone')}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    )
                                })()}
                            </CardContent>
                        </Card>
                    )}
                </div>
            </div>

            {/* Linked Bots Section - only show for existing personalities */}
            {!isNew && (
                <LinkedBotsSection
                    entityType="personality"
                    entityId={Number(id)}
                />
            )}

            {/* Create Tone Modal */}
            {showToneModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 p-6">
                        <h3 className="text-lg font-bold mb-4 flex items-center gap-2">
                            <Wand2 className="w-5 h-5 text-primary-600" />
                            {t('Create New Tone')}
                        </h3>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium mb-1">
                                    {t('Tone Name')} <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="text"
                                    value={newToneName}
                                    onChange={(e) => setNewToneName(e.target.value)}
                                    placeholder={t('e.g.: Energetic, Calm, Persuasive...')}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                    autoFocus
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium mb-1">
                                    {t('Description (optional)')}
                                </label>
                                <textarea
                                    value={newToneDescription}
                                    onChange={(e) => setNewToneDescription(e.target.value)}
                                    placeholder={t('Describe the desired tone...')}
                                    rows={3}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                                />
                            </div>

                            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                                <div className="flex items-start gap-2">
                                    <Sparkles className="w-4 h-4 text-blue-600 mt-0.5" />
                                    <div className="text-sm text-blue-800">
                                        <strong>{t('AI Generation:')}</strong> {t('The system will generate a System Prompt tailored to the new tone and select it for the current personality.')}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="flex gap-2 mt-6">
                            <Button
                                variant="outline"
                                onClick={() => {
                                    setShowToneModal(false)
                                    setNewToneName('')
                                    setNewToneDescription('')
                                }}
                                disabled={isCreatingTone}
                            >
                                {t('Cancel')}
                            </Button>
                            <Button
                                onClick={createNewTone}
                                disabled={!newToneName.trim() || isCreatingTone}
                                className="flex-1"
                            >
                                {isCreatingTone ? (
                                    <>
                                        <Loader2 className="w-4 h-4 me-2 animate-spin" />
                                        {t('Creating tone...')}
                                    </>
                                ) : (
                                    <>
                                        <Wand2 className="w-4 h-4 me-2" />
                                        {t('Create Tone')}
                                    </>
                                )}
                            </Button>
                        </div>
                    </div>
                </div>
            )}

            {/* Click outside to close improvement menu */}
            {showImprovementMenu && (
                <div 
                    className="fixed inset-0 z-[5]" 
                    onClick={() => setShowImprovementMenu(false)}
                />
            )}
        </div>
    )
}
