import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { getWidgetStrings } from '@shared/utils/widget-strings'

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

interface QAPair {
    id: number
    question: string
    answer: string
    icon?: string
}

interface Contact {
    id: number
    name: string
    role: string
    email: string
    phone: string
    image?: string
}

interface Department {
    name: string
    contacts: Contact[]
}

interface OpeningScreenData {
    mode: 'questions_ai' | 'questions_answers' | 'departments'
    welcome_text?: string
    questions?: Question[]
    ai_instructions?: string
    qa_pairs?: QAPair[]
    departments?: Department[]
    prompt?: string
    files?: Array<{ id: number; name: string; type: string; url: string }>
}

interface OpeningScreenProps {
    data: OpeningScreenData
    onQuestionClick: (question: string, aiInstructions?: string) => void
    onAnswerShow: (question: string, answer: string) => void
    primaryColor?: string
    welcomeText?: string
    botName?: string
    avatarUrl?: string | null
    language?: string
}

export function OpeningScreen({
    data,
    onQuestionClick,
    onAnswerShow,
    primaryColor = '#3BC2D0',
    welcomeText,
    botName,
    avatarUrl,
    language,
}: OpeningScreenProps) {
    const { mode } = data

    return (
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col h-full"
        >
            {/* Scrollable content area (welcome text, questions, etc.) */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {/* Welcome text — rendered as a bot message bubble at the top of the opening screen */}
                {welcomeText && (
                    <WelcomeMessageBubble
                        text={welcomeText}
                        botName={botName}
                        avatarUrl={avatarUrl}
                        primaryColor={primaryColor}
                    />
                )}

                {/* Mode-specific content */}
                {mode === 'questions_ai' && (
                    <QuestionsAI
                        questions={data.questions || []}
                        aiInstructions={data.ai_instructions}
                        onSelect={onQuestionClick}
                        primaryColor={primaryColor}
                        language={language}
                    />
                )}

                {mode === 'questions_answers' && (
                    <QuestionsAnswers
                        pairs={data.qa_pairs || []}
                        onSelect={onAnswerShow}
                        primaryColor={primaryColor}
                        language={language}
                    />
                )}

                {mode === 'departments' && (
                    <DepartmentsView
                        departments={data.departments || []}
                        primaryColor={primaryColor}
                        language={language}
                    />
                )}
            </div>
        </motion.div>
    )
}

// Mode 1: Questions with AI answers
function QuestionsAI({
    questions,
    aiInstructions,
    onSelect,
    primaryColor,
    language,
}: {
    questions: Question[]
    aiInstructions?: string
    onSelect: (question: string, aiInstructions?: string) => void
    primaryColor: string
    language?: string
}) {
    const ws = getWidgetStrings(language);
    if (!questions.length) return null;
    return (
        <div className="space-y-2">
            <p className="text-sm text-gray-500 text-center mb-3">
                {ws.openingFaqTitle}
            </p>
            <div className="flex flex-wrap gap-2 justify-center">
                {questions.map((q) => (
                    <motion.button
                        key={q.id}
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={() => onSelect(q.text, q.instructions || aiInstructions)}
                        className="px-4 py-2 bg-white border text-sm rounded-full 
                                   shadow-sm transition-colors"
                        style={{
                            borderColor: `${primaryColor}40`,
                            color: primaryColor,
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = `${primaryColor}10`
                            e.currentTarget.style.borderColor = primaryColor
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'white'
                            e.currentTarget.style.borderColor = `${primaryColor}40`
                        }}
                    >
                        {q.icon && <span className="me-1">{q.icon}</span>}
                        {q.text}
                    </motion.button>
                ))}
            </div>
        </div>
    )
}

// Mode 2: Questions with predefined answers
function QuestionsAnswers({
    pairs,
    onSelect,
    primaryColor,
    language,
}: {
    pairs: QAPair[]
    onSelect: (question: string, answer: string) => void
    primaryColor: string
    language?: string
}) {
    const ws = getWidgetStrings(language);
    if (!pairs.length) return null;
    return (
        <div className="space-y-2">
            <p className="text-sm text-gray-500 text-center mb-3">
                {ws.openingUsefulInfoTitle}
            </p>
            <div className="grid gap-2">
                {pairs.map((pair) => (
                    <motion.button
                        key={pair.id}
                        whileHover={{ scale: 1.01 }}
                        whileTap={{ scale: 0.99 }}
                        onClick={() => onSelect(pair.question, pair.answer)}
                        className="p-3 bg-white border border-gray-200 rounded-lg text-start
                                   transition-all"
                        onMouseEnter={(e) => {
                            e.currentTarget.style.borderColor = primaryColor
                            e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.borderColor = '#e5e7eb'
                            e.currentTarget.style.boxShadow = 'none'
                        }}
                    >
                        <span className="flex items-center gap-2 text-gray-700 font-medium">
                            {pair.icon && <span>{pair.icon}</span>}
                            {pair.question}
                        </span>
                    </motion.button>
                ))}
            </div>
        </div>
    )
}

// Mode 3: Departments and contacts
function DepartmentsView({
    departments,
    primaryColor,
    language,
}: {
    departments: Department[]
    primaryColor: string
    language?: string
}) {
    const [expanded, setExpanded] = useState<string | null>(null)
    const ws = getWidgetStrings(language);
    if (!departments.length) return null;

    return (
        <div className="space-y-3">
            <p className="text-sm text-gray-500 text-center mb-3 flex items-center justify-center gap-1">
                <span>👥</span>
                {ws.openingContactsTitle}
            </p>

            <div className="space-y-2">
                {departments.map((dept) => (
                    <div key={dept.name} className="border border-gray-200 rounded-lg overflow-hidden">
                        {/* Department Header */}
                        <button
                            onClick={() => setExpanded(expanded === dept.name ? null : dept.name)}
                            className="w-full p-3 bg-gray-50 flex items-center justify-between
                                       hover:bg-gray-100 transition-colors text-start"
                        >
                            <span className="font-medium text-gray-800">{dept.name}</span>
                            <span className="text-sm text-gray-500">
                                {ws.openingContactsCount.replace('%d', String(dept.contacts.length))}
                            </span>
                        </button>

                        {/* Contacts */}
                        <AnimatePresence>
                            {expanded === dept.name && (
                                <motion.div
                                    initial={{ height: 0 }}
                                    animate={{ height: 'auto' }}
                                    exit={{ height: 0 }}
                                    className="overflow-hidden"
                                >
                                    <div className="p-2 space-y-2">
                                        {dept.contacts.map((contact) => (
                                            <ContactCard
                                                key={contact.id}
                                                contact={contact}
                                                primaryColor={primaryColor}
                                            />
                                        ))}
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </div>
                ))}
            </div>
        </div>
    )
}

// Contact Card
function ContactCard({
    contact,
    primaryColor
}: {
    contact: Contact
    primaryColor: string
}) {
    return (
        <div className="p-3 bg-white rounded-lg border border-gray-100 flex items-center gap-3">
            {/* Avatar */}
            <div
                className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
                style={{ backgroundColor: `${primaryColor}20` }}
            >
                {contact.image ? (
                    <img
                        src={contact.image}
                        alt={contact.name}
                        className="w-full h-full rounded-full object-cover"
                    />
                ) : (
                    <span style={{ color: primaryColor }} className="font-semibold">
                        {contact.name.charAt(0)}
                    </span>
                )}
            </div>

            {/* Info */}
            <div className="flex-1 min-w-0">
                <p className="font-medium text-gray-800 truncate">{contact.name}</p>
                {contact.role && (
                    <p className="text-xs text-gray-500 truncate">{contact.role}</p>
                )}
            </div>

            {/* Actions */}
            <div className="flex gap-1">
                {contact.phone && (
                    <a
                        href={`tel:${contact.phone}`}
                        className="p-2 text-gray-400 rounded-full transition-colors"
                        style={{
                            ['--hover-color' as string]: primaryColor
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.color = primaryColor
                            e.currentTarget.style.backgroundColor = `${primaryColor}10`
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.color = '#9ca3af'
                            e.currentTarget.style.backgroundColor = 'transparent'
                        }}
                    >
                        📞
                    </a>
                )}
                {contact.email && (
                    <a
                        href={`mailto:${contact.email}`}
                        className="p-2 text-gray-400 rounded-full transition-colors"
                        onMouseEnter={(e) => {
                            e.currentTarget.style.color = primaryColor
                            e.currentTarget.style.backgroundColor = `${primaryColor}10`
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.color = '#9ca3af'
                            e.currentTarget.style.backgroundColor = 'transparent'
                        }}
                    >
                        ✉️
                    </a>
                )}
            </div>
        </div>
    )
}

// Welcome message bubble — styled like a bot message to appear above the opening screen content
function WelcomeMessageBubble({
    text,
    botName,
    avatarUrl,
    primaryColor
}: {
    text: string
    botName?: string
    avatarUrl?: string | null
    primaryColor: string
}) {
    return (
        <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="flex items-start gap-2 mb-2"
        >
            {/* Bot avatar */}
            <div
                className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0"
                style={{ backgroundColor: `${primaryColor}20` }}
            >
                {avatarUrl ? (
                    <img
                        src={avatarUrl}
                        alt={botName || 'Bot'}
                        className="w-full h-full rounded-full object-cover"
                    />
                ) : (
                    <span style={{ color: primaryColor }} className="text-sm font-semibold">
                        {(botName || 'B').charAt(0)}
                    </span>
                )}
            </div>

            {/* Message bubble */}
            <div
                className="px-4 py-2.5 rounded-2xl rounded-tl-sm max-w-[85%] text-sm leading-relaxed shadow-sm"
                style={{
                    backgroundColor: `${primaryColor}10`,
                    color: '#374151',
                }}
            >
                {text}
            </div>
        </motion.div>
    )
}

export default OpeningScreen

