import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Star, Edit2, Trash2, Sparkles, Zap, Wand2, Loader2 } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
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
    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
}

export function Personalities() {
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const [newToneName, setNewToneName] = useState('')
    const [newToneDescription, setNewToneDescription] = useState('')
    const [showToneModal, setShowToneModal] = useState(false)
    const [generatingPrompt, setGeneratingPrompt] = useState(false)

    // Fetch personalities
    const { data: personalitiesData, isLoading: loadingPersonalities } = useQuery({
        queryKey: ['personalities', currentLanguage],
        queryFn: () => apiClient.get<{ data: { personalities: Personality[] } }>('personalities', { language: currentLanguage }),
    })

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

    // Delete personality mutation
    const deletePersonality = useMutation({
        mutationFn: (id: number) => apiClient.delete(`personalities/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['personalities', currentLanguage] })
        },
    })

    // Set default personality mutation
    const setDefault = useMutation({
        mutationFn: (id: number) => apiClient.put(`personalities/${id}/default`, {}),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['personalities', currentLanguage] })
        },
    })

    // Create tone mutation
    const createTone = useMutation({
        mutationFn: (data: { name: string; description?: string; system_prompt?: string; emoji?: string; language?: string }) => 
            apiClient.post('tones', { ...data, language: data.language || currentLanguage }),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['tones', currentLanguage] })
            setNewToneName('')
            setNewToneDescription('')
            setShowToneModal(false)
        },
    })

    // Delete tone mutation
    const deleteTone = useMutation({
        mutationFn: (id: number) => apiClient.delete(`tones/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['tones', currentLanguage] })
        },
    })

    // Generate system prompt for new tone
    const generateTonePrompt = async () => {
        if (!newToneName.trim()) return

        setGeneratingPrompt(true)
        try {
            const response = await apiClient.post<{ data: { system_prompt: string } }>('tones/generate-prompt', {
                name: newToneName,
                description: newToneDescription,
            })

            const generatedPrompt = response.data?.system_prompt || ''
            
            // Create the tone with generated prompt
            await createTone.mutateAsync({
                name: newToneName.trim(),
                description: newToneDescription.trim() || undefined,
                system_prompt: generatedPrompt,
                emoji: '✨',
            })
        } catch (error) {
            console.error('Error generating prompt:', error)
            alert(t('Error creating tone. Please try again.'))
        } finally {
            setGeneratingPrompt(false)
        }
    }

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

    const handleDeletePersonality = (id: number, name: string, isSystem: boolean) => {
        if (isSystem) {
            alert(t('Cannot delete a system personality'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete the personality "%s"?'), name))) {
            deletePersonality.mutate(id)
        }
    }

    const handleSetDefault = (id: number) => {
        setDefault.mutate(id)
    }

    const handleDeleteTone = (id: number, name: string, isSystem: boolean) => {
        if (isSystem) {
            alert(t('Cannot delete a system tone'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete the tone "%s"?'), name))) {
            deleteTone.mutate(id)
        }
    }

    // Get tone display info
    const getToneDisplay = (toneSlug: string) => {
        const tone = tones.find(t => t.slug === toneSlug)
        return tone ? `${tone.emoji || '🎭'} ${tone.name}` : toneSlug
    }

    if (loadingPersonalities || loadingTones) {
        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>
        )
    }

    return (
        <div className="space-y-6">
            <PageHeader 
                title={t('Personalities')} 
                subtitle={t('Manage bot personalities - define how the bot behaves and communicates')}
            >
                <Link to="/personalities/new">
                    <Button>
                        <Plus className="w-4 h-4 me-2" />
                        {t('Add Personality')}
                    </Button>
                </Link>
            </PageHeader>

            {/* Personalities Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {personalities.map((personality) => (
                    <Card key={personality.id} className="relative hover:shadow-md transition-shadow">
                        {/* Default Badge */}
                        {personality.is_default === 1 && (
                            <div className="absolute top-3 start-3 flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full">
                                <Star className="w-3 h-3" />
                                {t('Default')}
                            </div>
                        )}

                        {/* System Badge */}
                        {personality.is_system === 1 && (
                            <div className="absolute top-3 end-3 flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">
                                <Sparkles className="w-3 h-3" />
                                {t('System')}
                            </div>
                        )}

                        <CardContent className={`pt-${personality.is_default || personality.is_system ? '12' : '6'}`}>
                            <h3 className="font-bold text-lg mb-1">{personality.name}</h3>
                            {personality.description && (
                                <p className="text-sm text-gray-500 mb-4">{personality.description}</p>
                            )}

                            {/* Behavior Indicators */}
                            <div className="flex flex-wrap gap-2 mb-4">
                                {personality.proactive_engagement === 1 && (
                                    <span className="flex items-center gap-1 px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded-full">
                                        <Zap className="w-3 h-3" />
                                        {t('Proactive Engagement')}
                                    </span>
                                )}
                            </div>

                            {/* Tone */}
                            <p className="text-xs text-gray-400 mb-4">
                                {t('Tone:')} {getToneDisplay(personality.tone)}
                            </p>

                            {/* Actions */}
                            <div className="flex gap-2">
                                <Link to={`/personalities/${personality.id}`} className="flex-1">
                                    <Button variant="outline" size="sm" className="w-full">
                                        <Edit2 className="w-4 h-4 me-1" />
                                        {t('Edit')}
                                    </Button>
                                </Link>
                                
                                {personality.is_default !== 1 && (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => handleSetDefault(personality.id)}
                                        title={t('Set as default')}
                                    >
                                        <Star className="w-4 h-4" />
                                    </Button>
                                )}

                                {personality.is_system !== 1 && (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => handleDeletePersonality(personality.id, personality.name, personality.is_system === 1)}
                                        className="text-red-600 hover:bg-red-50"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </Button>
                                )}
                            </div>
                        </CardContent>
                    </Card>
                ))}

                {/* Empty State */}
                {personalities.length === 0 && (
                    <div className="col-span-full text-center py-12 text-gray-500">
                        <Sparkles className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p className="mb-4">{t('No personalities yet')}</p>
                        <Link to="/personalities/new">
                            <Button>{t('Add First Personality')}</Button>
                        </Link>
                    </div>
                )}
            </div>

            {/* Tones Management */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <Sparkles className="w-5 h-5 text-primary-600" />
                            {t('Tones')}
                        </div>
                        <Button
                            size="sm"
                            onClick={() => setShowToneModal(true)}
                        >
                            <Plus className="w-4 h-4 me-1" />
                            {t('New Tone')}
                        </Button>
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="text-sm text-gray-500 mb-4">
                        {t('Tones define the communication style of the bot. Each tone contains a built-in System Prompt that defines the conversation character.')}
                        <br />
                        <span className="text-xs text-gray-400">{t('You can create custom tones with automatic System Prompt generation using AI.')}</span>
                    </p>

                    {/* Tones list */}
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                        {tones.map((tone) => (
                            <div
                                key={tone.id}
                                className="group relative flex flex-col items-center p-4 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors"
                            >
                                <span className="text-3xl mb-2">{tone.emoji || '🎭'}</span>
                                <span className="text-sm font-medium text-center">{tone.name}</span>
                                {tone.description && (
                                    <span className="text-xs text-gray-500 text-center mt-1 line-clamp-2">
                                        {tone.description}
                                    </span>
                                )}
                                {tone.is_system === 1 ? (
                                    <span className="text-xs text-blue-600 mt-1">{t('System')}</span>
                                ) : (
                                    <button
                                        onClick={() => handleDeleteTone(tone.id, tone.name, tone.is_system === 1)}
                                        className="mt-2 flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors"
                                        title={t('Delete tone')}
                                    >
                                        <Trash2 className="w-3 h-3" />
                                        {t('Delete')}
                                    </button>
                                )}
                            </div>
                        ))}

                        {tones.length === 0 && (
                            <p className="col-span-full text-sm text-gray-400 text-center py-4">{t('No tones yet')}</p>
                        )}
                    </div>
                </CardContent>
            </Card>

            {/* 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... e.g.: An energetic and enthusiastic tone that encourages action')}
                                    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 automatically generate a System Prompt tailored to the tone you defined.')}
                                    </div>
                                </div>
                            </div>
                        </div>

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