/**
 * Opening Screen Preset Detail Page
 * @since 1.1.0
 */

import { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { ArrowRight, Save, Loader2, Trash2, AlertTriangle, Check } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardContent } from '@/components/common/Card'
import { apiClient } from '@/api/client'
import { useLanguage } from '@/contexts/LanguageContext'
import { OpeningScreenConfig } from '@/components/widgets/OpeningScreenConfig'
import { LinkedBotsSection } from '@/components/common/LinkedBotsSection'
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges'
import { UnsavedChangesModal } from '@/components/common/UnsavedChangesModal'
import { t, sprintf } from '@/lib/i18n'

interface Question {
    text: string
    icon: string
}

interface QAPair {
    question: string
    answer: string
    icon: string
}

interface AttachedFile {
    id: number
    name: string
    type: string
    url: string
    path: string
}

interface OpeningScreenPresetData {
    id?: number
    name: string
    slug: string
    description: string
    is_default: number
    is_system: number
    mode: 'questions_ai' | 'questions_answers' | 'departments'
    welcome_text: string
    show_welcome: boolean
    questions: Question[]
    ai_instructions: string
    qa_pairs: QAPair[]
    contact_list_id: number | null
    show_departments: boolean
    show_contact_cards: boolean
    attached_files: AttachedFile[]
}

const defaultFormData: OpeningScreenPresetData = {
    name: '',
    slug: '',
    description: '',
    is_default: 0,
    is_system: 0,
    mode: 'questions_ai',
    welcome_text: t('Hello! How can I help?'),
    show_welcome: true,
    questions: [],
    ai_instructions: '',
    qa_pairs: [],
    contact_list_id: null,
    show_departments: true,
    show_contact_cards: true,
    attached_files: [],
}

export function OpeningScreenPresetDetail() {
    const { id: rawId } = useParams<{ id: string }>()
    const navigate = useNavigate()
    const queryClient = useQueryClient()
    const { currentLanguage } = useLanguage()
    const [searchParams] = useSearchParams()
    const returnTo = searchParams.get('returnTo')
    
    // Normalize id - treat undefined/empty as 'new'
    const id = rawId || 'new'
    const isNew = id === 'new'
    // Redirect to archive when language changes while editing an existing entity
    const prevLangRef = useRef(currentLanguage)

    const [formData, setFormData] = useState<OpeningScreenPresetData>(defaultFormData)
    const [isSaving, setIsSaving] = useState(false)
    const [isDataLoaded, setIsDataLoaded] = useState(isNew)
    const [showSavedAnimation, setShowSavedAnimation] = useState(false)

    const justSavedRef = useRef(false)
    const saveCooldownRef = useRef(false)
    const setOriginalDataRef = useRef<(() => void) | null>(null)

    // Load preset data - only when editing existing preset (not 'new' and id is a valid number)
    const { data, isLoading } = useQuery({
        queryKey: ['opening-screen-preset', id],
        queryFn: () => apiClient.get<{ data: { preset: any } }>(`opening-screen-presets/${id}`),
        enabled: !isNew && !!id && id !== 'undefined' && !isNaN(Number(id)),
    })

    // Save function for unsaved changes hook
    const handleSave = useCallback(async () => {
        setIsSaving(true)
        try {
            const isCreating = !formData.id && id === 'new'
            
            if (isCreating) {
                const response = await apiClient.post<{ data: { preset: { id: number } } }>(
                    'opening-screen-presets',
                    { ...formData, language: currentLanguage }
                )
                if (response?.data?.preset?.id) {
                    navigate(`/opening-screen-presets/${response.data.preset.id}`, { replace: true })
                }
            } else {
                const presetId = formData.id || id
                await apiClient.put(`opening-screen-presets/${presetId}`, formData)
                justSavedRef.current = true
                setOriginalDataRef.current?.()
            }
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
            queryClient.invalidateQueries({ queryKey: ['opening-screen-preset', id] })
        } finally {
            setIsSaving(false)
        }
    }, [formData, id, queryClient, currentLanguage, navigate])

    // Unsaved changes hook
    const {
        hasUnsavedChanges,
        checkNavigationSafe,
        setOriginalData,
        showModal,
        saveError,
        modalActions,
    } = useUnsavedChanges({
        currentData: formData,
        onSave: handleSave,
        isLoaded: isDataLoaded,
    })

    useEffect(() => { setOriginalDataRef.current = setOriginalData }, [setOriginalData])

    // Redirect to list when language changes while editing an existing entity
    useEffect(() => {
        if (prevLangRef.current !== currentLanguage && !isNew) {
            navigate('/opening-screen-presets')
        }
        prevLangRef.current = currentLanguage
    }, [currentLanguage, isNew, navigate])

    // Initialize form data when loaded
    useEffect(() => {
        if (data?.data?.preset) {
            // Fix: Skip overwriting formData with server response right after a save.
            if (justSavedRef.current) {
                justSavedRef.current = false
                return
            }
            const preset = data.data.preset
            const loadedData: OpeningScreenPresetData = {
                ...defaultFormData,
                ...preset,
                show_welcome: Boolean(preset.show_welcome),
                show_departments: Boolean(preset.show_departments),
                show_contact_cards: Boolean(preset.show_contact_cards),
            }
            setFormData(loadedData)
            setIsDataLoaded(true)
        }
    }, [data])

    // Set original data after loading
    useEffect(() => {
        if (isDataLoaded) {
            setOriginalData()
        }
    }, [isDataLoaded, setOriginalData])

    // Create/Update mutation
    const saveMutation = useMutation({
        mutationFn: (data: OpeningScreenPresetData) => {
            // Check if creating new or updating existing
            // Use data.id presence OR url param to determine
            const isCreating = !data.id && id === 'new'
            
            if (isCreating) {
                return apiClient.post('opening-screen-presets', { ...data, language: currentLanguage })
            }
            // Use existing id from data or from URL param
            const presetId = data.id || id
            return apiClient.put(`opening-screen-presets/${presetId}`, data)
        },
        onSuccess: (response: any) => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
            queryClient.invalidateQueries({ queryKey: ['opening-screen-preset', id] })
            // Fix: Tell the load effect to skip overwriting formData on the next refetch
            justSavedRef.current = true
            setOriginalData() // Reset original data after save
            
            // Show saved animation with cooldown guard
            saveCooldownRef.current = true
            setShowSavedAnimation(true)
            setTimeout(() => {
                setShowSavedAnimation(false)
                saveCooldownRef.current = false
            }, 2000)
            
            // Redirect to the new preset's page after creation
            if (id === 'new' && response?.data?.preset?.id) {
                navigate(`/opening-screen-presets/${response.data.preset.id}`, { replace: true })
            }
        },
        onError: (error: any) => {
            console.error('Save failed:', error)
            alert(sprintf(t('Save error: %s'), error?.message || t('Unknown error')))
        },
    })

    // Delete mutation
    const deleteMutation = useMutation({
        mutationFn: () => apiClient.delete(`opening-screen-presets/${id}`),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['opening-screen-presets', currentLanguage] })
            navigate('/opening-screen-presets')
        },
        onError: () => {
            alert(t('Failed to delete preset. Please try again.'))
        },
    })

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        setIsSaving(true)
        
        try {
            await saveMutation.mutateAsync(formData)
        } finally {
            setIsSaving(false)
        }
    }

    const handleDelete = () => {
        if (formData.is_system === 1) {
            alert(t('Cannot delete a system opening screen preset'))
            return
        }
        if (confirm(sprintf(t('Are you sure you want to delete "%s"?'), formData.name))) {
            deleteMutation.mutate()
        }
    }

    const handleBack = () => {
        const backUrl = returnTo || '/opening-screen-presets'
        checkNavigationSafe(() => navigate(backUrl))
    }

    // Update form data helper
    const updateField = <K extends keyof OpeningScreenPresetData>(
        field: K,
        value: OpeningScreenPresetData[K]
    ) => {
        setFormData(prev => ({ ...prev, [field]: value }))
    }

    // Handle config changes from OpeningScreenConfig component
    const handleConfigChange = (newSettings: any) => {
        setFormData(prev => ({
            ...prev,
            mode: newSettings.mode,
            welcome_text: newSettings.welcome_text,
            show_welcome: newSettings.show_welcome,
            questions: newSettings.questions,
            ai_instructions: newSettings.ai_instructions,
            qa_pairs: newSettings.qa_pairs,
            contact_list_id: newSettings.contact_list_id,
            show_departments: newSettings.show_departments,
            show_contact_cards: newSettings.show_contact_cards,
            attached_files: newSettings.attached_files,
        }))
    }

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

    return (
        <div className="space-y-6 animate-fade-in">
            <PageHeader
                title={isNew ? t('New Opening Screen') : formData.name || t('Edit Opening Message')}
                subtitle={isNew ? t('Create a new opening screen for use in bots') : t('Edit opening screen settings')}
            >
                <div className="flex items-center gap-3">
                    <button
                        type="button"
                        onClick={handleBack}
                        className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 transition-colors"
                    >
                        <ArrowRight className="w-4 h-4" />
                        {t('Back')}
                    </button>
                    
                    {!isNew && formData.is_system !== 1 && (
                        <button
                            type="button"
                            onClick={handleDelete}
                            className="flex items-center gap-2 px-4 py-2 text-red-600 hover:text-red-700 transition-colors"
                        >
                            <Trash2 className="w-4 h-4" />
                            {t('Delete')}
                        </button>
                    )}

                    <button
                        type="submit"
                        form="preset-form"
                        disabled={isSaving}
                        className={`
                            flex items-center gap-2 px-4 py-2 rounded-lg transition-all
                            ${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
                            disabled:opacity-50 disabled:cursor-not-allowed
                        `}
                    >
                        {showSavedAnimation ? (
                            <Check className="w-4 h-4" />
                        ) : isSaving ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                            <Save className="w-4 h-4" />
                        )}
                        {isSaving ? t('Saving...') : showSavedAnimation ? t('Saved! ✓') : (hasUnsavedChanges && !saveCooldownRef.current) ? t('Save Changes') : isNew ? t('Create Preset') : t('Save')}
                    </button>
                </div>
            </PageHeader>

            <form id="preset-form" onSubmit={handleSubmit} className="space-y-6">
                {/* Basic Info */}
                <Card>
                    <CardContent className="p-6">
                        <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('Preset Details')}</h3>
                        
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    {t('Preset Name')} *
                                </label>
                                <input
                                    type="text"
                                    value={formData.name}
                                    onChange={(e) => updateField('name', e.target.value)}
                                    required
                                    placeholder={t('FAQ')}
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    {t('Description (optional)')}
                                </label>
                                <input
                                    type="text"
                                    value={formData.description}
                                    onChange={(e) => updateField('description', e.target.value)}
                                    placeholder={t('This preset displays FAQ...')}
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                />
                            </div>
                        </div>

                        {/* Default checkbox */}
                        <div className="mt-4">
                            <label className="flex items-center gap-2 cursor-pointer">
                                <input
                                    type="checkbox"
                                    checked={formData.is_default === 1}
                                    onChange={(e) => updateField('is_default', e.target.checked ? 1 : 0)}
                                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                />
                                <span className="text-sm text-gray-700">
                                    {t('Set as default for new bots')}
                                </span>
                            </label>
                        </div>
                    </CardContent>
                </Card>

                {/* Opening Screen Configuration */}
                <Card>
                    <CardContent className="p-6">
                        <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('Opening Screen Settings')}</h3>
                        
                        <OpeningScreenConfig
                            settings={{
                                mode: formData.mode,
                                welcome_text: formData.welcome_text,
                                show_welcome: formData.show_welcome,
                                questions: formData.questions,
                                ai_instructions: formData.ai_instructions,
                                qa_pairs: formData.qa_pairs,
                                contact_list_id: formData.contact_list_id,
                                show_departments: formData.show_departments,
                                show_contact_cards: formData.show_contact_cards,
                                attached_files: formData.attached_files,
                            }}
                            onChange={handleConfigChange}
                        />
                    </CardContent>
                </Card>
            </form>

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

            {/* Unsaved Changes Modal */}
            {/* 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>
            )}

            <UnsavedChangesModal
                isOpen={showModal}
                onCancel={modalActions.onCancel}
                onDiscard={modalActions.onDiscard}
                onSave={modalActions.onSave}
                onSaveAlways={modalActions.onSaveAlways}
                isSaving={isSaving}
                errorMessage={saveError}
            />
        </div>
    )
}

export default OpeningScreenPresetDetail
