import React, { useState, useRef, useEffect } from 'react'
import { Plus, Trash2, Sparkles, ListChecks, ChevronDown } from 'lucide-react'
import { t } from '@/lib/i18n'
// import { useQuery } from '@tanstack/react-query' // Used only by DepartmentsConfig (disabled)
// import { apiClient } from '@/api/client' // Used only by DepartmentsConfig (disabled)

function getAvailableIcons() {
    return [
        { emoji: '💬', label: t('Chat') },
        { emoji: '💰', label: t('Prices') },
        { emoji: '🛒', label: t('Shopping') },
        { emoji: '📞', label: t('Phone') },
        { emoji: '📧', label: t('Email') },
        { emoji: '❓', label: t('Question') },
        { emoji: '📅', label: t('Calendar') },
        { emoji: '🔍', label: t('Search') },
        { emoji: '⏰', label: t('Business Hours') },
        { emoji: '📍', label: t('Location') },
        { emoji: '🚚', label: t('Shipping') },
        { emoji: '↩️', label: t('Returns') },
        { emoji: '⭐', label: t('Star') },
        { emoji: '🎁', label: t('Gift') },
        { emoji: '💳', label: t('Payment') },
        { emoji: '📦', label: t('Package') },
        { emoji: '🏠', label: t('Home') },
        { emoji: '👋', label: t('Hi') },
        { emoji: '✨', label: t('Sparkles') },
        { emoji: '🎯', label: t('Target') },
        { emoji: '💡', label: t('Idea') },
        { emoji: '🔧', label: t('Support') },
        { emoji: '📱', label: t('Mobile') },
        { emoji: '🖥️', label: t('Desktop') },
    ]
}

interface Question {
    text: string
    icon: string
    instructions?: string
}

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

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

interface OpeningScreenSettings {
    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[]
}

interface OpeningScreenConfigProps {
    settings: OpeningScreenSettings
    onChange: (settings: OpeningScreenSettings) => void
}

/* Used only by DepartmentsConfig (disabled)
interface ContactList {
    id: number
    name: string
}
*/

const modeIcons = {
    questions_ai: Sparkles,
    questions_answers: ListChecks,
    // departments: Users, // Temporarily disabled
}

function getModeLabels() {
    return {
        questions_ai: t('Questions + AI'),
        questions_answers: t('Questions + Answers'),
    }
}

function getModeDescriptions() {
    return {
        questions_ai: t('Define questions, AI answers'),
        questions_answers: t('Pre-made questions and answers'),
    }
}

export function OpeningScreenConfig({ settings, onChange }: OpeningScreenConfigProps) {
    const mode = settings.mode || 'questions_ai'

    return (
        <div className="space-y-6">
            {/* Mode Selection */}
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('Opening Message Type')}
                </label>
                <div className="grid grid-cols-2 gap-3">
                    {Object.entries(getModeLabels()).map(([key, label]) => {
                        const Icon = modeIcons[key as keyof typeof modeIcons]
                        return (
                            <ModeButton
                                key={key}
                                mode={key}
                                label={label}
                                description={getModeDescriptions()[key as keyof ReturnType<typeof getModeDescriptions>]}
                                icon={<Icon className="w-5 h-5" />}
                                selected={mode === key}
                                onClick={() => onChange({ ...settings, mode: key as OpeningScreenSettings['mode'] })}
                            />
                        )
                    })}
                </div>
            </div>

            {/* Welcome Text */}
            <div>
                <label className="flex items-center gap-2 mb-2">
                    <input
                        type="checkbox"
                        checked={settings.show_welcome ?? true}
                        onChange={(e) => onChange({ ...settings, show_welcome: e.target.checked })}
                        className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm font-medium text-gray-700">{t('Show opening text')}</span>
                </label>
                {settings.show_welcome && (
                    <input
                        type="text"
                        value={settings.welcome_text || ''}
                        onChange={(e) => onChange({ ...settings, welcome_text: e.target.value })}
                        placeholder={t('Hello! How can I help?')}
                        className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
                    />
                )}
            </div>

            <hr className="border-gray-200" />

            {/* Mode-specific settings */}
            {mode === 'questions_ai' && (
                <QuestionsAIConfig settings={settings} onChange={onChange} />
            )}
            {mode === 'questions_answers' && (
                <QuestionsAnswersConfig settings={settings} onChange={onChange} />
            )}
            {/* departments mode temporarily disabled
            {mode === 'departments' && (
                <DepartmentsConfig settings={settings} onChange={onChange} />
            )}
            */}

        </div>
    )
}

// Mode Button Component
function ModeButton({ 
    label, 
    description, 
    icon,
    selected, 
    onClick 
}: { 
    mode: string
    label: string
    description: string
    icon: React.ReactNode
    selected: boolean
    onClick: () => void
}) {
    return (
        <button
            type="button"
            onClick={onClick}
            className={`p-4 rounded-lg border-2 text-right transition-all ${
                selected 
                    ? 'border-primary-500 bg-primary-50 ring-2 ring-primary-200' 
                    : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
            }`}
        >
            <div className="flex items-center gap-2 mb-1">
                <span className={selected ? 'text-primary-600' : 'text-gray-500'}>
                    {icon}
                </span>
                <span className={`font-medium ${selected ? 'text-primary-700' : 'text-gray-800'}`}>
                    {label}
                </span>
            </div>
            <p className="text-xs text-gray-500">{description}</p>
        </button>
    )
}

// Mode 1: Questions AI Config
function QuestionsAIConfig({ settings, onChange }: OpeningScreenConfigProps) {
    const questions = settings.questions || []

    const addQuestion = () => {
        onChange({
            ...settings,
            questions: [...questions, { text: '', icon: '❓', instructions: '' }]
        })
    }

    const updateQuestion = (idx: number, field: string, value: string) => {
        const updated = [...questions]
        updated[idx] = { ...updated[idx], [field]: value }
        onChange({ ...settings, questions: updated })
    }

    const removeQuestion = (idx: number) => {
        onChange({
            ...settings,
            questions: questions.filter((_, i) => i !== idx)
        })
    }

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <div>
                    <label className="block text-sm font-medium text-gray-700">
                        {t('Structured Questions')}
                    </label>
                    <p className="text-xs text-gray-500">
                        {t('Questions displayed to the customer in the opening message. On click, the question is sent to AI with the instructions you defined.')}
                    </p>
                </div>
                <button
                    type="button"
                    onClick={addQuestion}
                    className="flex items-center gap-1 px-3 py-1.5 text-sm text-primary-600 hover:bg-primary-50 rounded-lg transition-colors"
                >
                    <Plus className="w-4 h-4" />
                    {t('Add Question')}
                </button>
            </div>

            {questions.length === 0 ? (
                <div className="text-center py-6 bg-gray-50 rounded-lg border border-dashed border-gray-300">
                    <p className="text-gray-500 text-sm">{t('No structured questions')}</p>
                    <button
                        type="button"
                        onClick={addQuestion}
                        className="mt-2 text-primary-600 text-sm hover:underline"
                    >
                        {t('Add first question')}
                    </button>
                </div>
            ) : (
                <div className="space-y-3">
                    {questions.map((q, idx) => (
                        <div key={idx} className="p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div className="flex items-start gap-3">
                                {/* Icon Dropdown */}
                                <div className="flex-shrink-0">
                                    <label className="block text-xs text-gray-500 mb-1">{t('Icon')}</label>
                                    <IconDropdown
                                        value={q.icon || '❓'}
                                        onChange={(icon) => updateQuestion(idx, 'icon', icon)}
                                    />
                                </div>

                                {/* Question Text and AI Instructions */}
                                <div className="flex-1 space-y-2">
                                    <div>
                                        <label className="block text-xs text-gray-500 mb-1">{t('Question Text')}</label>
                                        <input
                                            type="text"
                                            value={q.text || ''}
                                            onChange={(e) => updateQuestion(idx, 'text', e.target.value)}
                                            placeholder={t('e.g.: What are the opening hours?')}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-xs text-gray-500 mb-1">{t('AI instructions for this question')}</label>
                                        <textarea
                                            value={q.instructions || ''}
                                            onChange={(e) => updateQuestion(idx, 'instructions', e.target.value)}
                                            placeholder={t('e.g.: Answer briefly, opening hours are Sun-Thu 9:00-17:00...')}
                                            rows={2}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
                                        />
                                    </div>
                                </div>

                                {/* Delete */}
                                <button
                                    type="button"
                                    onClick={() => removeQuestion(idx)}
                                    className="p-2 text-red-500 hover:bg-red-100 rounded-lg transition-colors mt-5"
                                >
                                    <Trash2 className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <p className="text-xs text-gray-500 bg-blue-50 p-3 rounded-lg">
                💡 <strong>{t('Tip:')}</strong> {t('When a customer clicks a question, the question is sent to AI with the instructions you defined. This way you can direct the answer exactly as you want.')}
            </p>
        </div>
    )
}

// Mode 2: Questions & Answers Config
function QuestionsAnswersConfig({ settings, onChange }: OpeningScreenConfigProps) {
    const pairs = settings.qa_pairs || []

    const addPair = () => {
        onChange({
            ...settings,
            qa_pairs: [...pairs, { question: '', answer: '', icon: '' }]
        })
    }

    const updatePair = (idx: number, field: string, value: string) => {
        const updated = [...pairs]
        updated[idx] = { ...updated[idx], [field]: value }
        onChange({ ...settings, qa_pairs: updated })
    }

    const removePair = (idx: number) => {
        onChange({
            ...settings,
            qa_pairs: pairs.filter((_, i) => i !== idx)
        })
    }

    return (
        <div className="space-y-4">
            <h4 className="font-medium text-gray-800 flex items-center gap-2">
                <ListChecks className="w-4 h-4 text-primary-500" />
                {t('Questions & Answers')}
            </h4>

            <div className="space-y-4">
                {pairs.map((pair, idx) => (
                    <div key={idx} className="p-4 border border-gray-200 rounded-lg bg-gray-50 space-y-3">
                        <div className="flex gap-2">
                            <input
                                type="text"
                                value={pair.icon || ''}
                                onChange={(e) => updatePair(idx, 'icon', e.target.value)}
                                placeholder="❓"
                                className="w-12 px-2 py-2 border border-gray-300 rounded-lg text-center bg-white"
                            />
                            <input
                                type="text"
                                value={pair.question}
                                onChange={(e) => updatePair(idx, 'question', e.target.value)}
                                placeholder={t('The question...')}
                                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg bg-white"
                            />
                            <button
                                type="button"
                                onClick={() => removePair(idx)}
                                className="p-2 text-red-500 hover:bg-red-100 rounded-lg transition-colors"
                            >
                                <Trash2 className="w-4 h-4" />
                            </button>
                        </div>
                        <textarea
                            value={pair.answer}
                            onChange={(e) => updatePair(idx, 'answer', e.target.value)}
                            placeholder={t('The answer...')}
                            rows={2}
                            className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white"
                        />
                    </div>
                ))}
            </div>

            <button
                type="button"
                onClick={addPair}
                className="flex items-center gap-2 text-primary-600 hover:text-primary-700 font-medium"
            >
                <Plus className="w-4 h-4" />
                {t('Add question and answer')}
            </button>
        </div>
    )
}

/* Mode 3: Departments Config — temporarily disabled
function DepartmentsConfig({ settings, onChange }: OpeningScreenConfigProps) {
    const { data: contactListsData } = useQuery({
        queryKey: ['contact-lists-dropdown'],
        queryFn: () => apiClient.get<{ data: { lists: ContactList[] } }>('contact-lists/dropdown'),
    })

    const contactLists = contactListsData?.data?.lists || []

    return (
        <div className="space-y-4">
            <h4 className="font-medium text-gray-800 flex items-center gap-2">
                <Users className="w-4 h-4 text-primary-500" />
                {t('Department settings')}
            </h4>

            <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('Contact list')}
                </label>
                <select
                    value={settings.contact_list_id || ''}
                    onChange={(e) => onChange({ 
                        ...settings, 
                        contact_list_id: e.target.value ? Number(e.target.value) : null 
                    })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary-500 focus:border-primary-500"
                >
                    <option value="">{t('Primary list')}</option>
                    {contactLists.map((list) => (
                        <option key={list.id} value={list.id}>{list.name}</option>
                    ))}
                </select>
            </div>

            <div className="space-y-2">
                <label className="flex items-center gap-2">
                    <input
                        type="checkbox"
                        checked={settings.show_departments !== false}
                        onChange={(e) => onChange({ ...settings, show_departments: e.target.checked })}
                        className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-gray-700">{t('Show department headings')}</span>
                </label>

                <label className="flex items-center gap-2">
                    <input
                        type="checkbox"
                        checked={settings.show_contact_cards !== false}
                        onChange={(e) => onChange({ ...settings, show_contact_cards: e.target.checked })}
                        className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-gray-700">{t('Show contact cards')}</span>
                </label>
            </div>

            <div className="p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-blue-800">
                    💡 {t('Make sure your contacts include a "Department" column in the CSV file')}
                </p>
            </div>
        </div>
    )
}
*/

// Icon Dropdown Component
function IconDropdown({ value, onChange }: { value: string; onChange: (icon: string) => void }) {
    const [isOpen, setIsOpen] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)

    // Close dropdown when clicking outside
    const handleClickOutside = (e: MouseEvent) => {
        if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
            setIsOpen(false)
        }
    }

    // Add/remove event listener
    useEffect(() => {
        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside)
            return () => document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [isOpen])

    return (
        <div className="relative" ref={dropdownRef}>
            <button
                type="button"
                onClick={() => setIsOpen(!isOpen)}
                className="w-16 h-10 flex items-center justify-center gap-1 border border-gray-300 rounded-lg text-xl bg-white hover:bg-gray-50 transition-colors"
            >
                <span className="text-xl">{value || '💬'}</span>
                <ChevronDown className="w-3 h-3 text-gray-400" />
            </button>
            
            {isOpen && (
                <div className="absolute top-full right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 p-3 min-w-[240px]">
                    <div className="grid grid-cols-6 gap-2">
                        {getAvailableIcons().map((icon) => (
                            <button
                                key={icon.emoji}
                                type="button"
                                onClick={() => {
                                    onChange(icon.emoji)
                                    setIsOpen(false)
                                }}
                                className={`w-9 h-9 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors text-xl ${
                                    value === icon.emoji ? 'bg-primary-100 ring-2 ring-primary-400' : ''
                                }`}
                                title={icon.label}
                            >
                                {icon.emoji}
                            </button>
                        ))}
                    </div>
                </div>
            )}
        </div>
    )
}

export default OpeningScreenConfig

