import React from 'react'
import { Type, HeartHandshake, Info, MoreHorizontal, Smile } from 'lucide-react'
import { GhostButton } from './settings-ui'
import { Separator } from './separator'
import { Popover, PopoverContent, PopoverTrigger } from './popover'
import { WhatsAppEditor } from './whatsapp-editor'
import { EmojiPickerButton, FormattingHelpButton } from './whatsapp-toolbar'
import { WhatsAppSpamChecker, WhatsAppQAResults } from './whatsapp-qa-diagnostic'
import { cn } from "@/lib/utils"


interface Rule {
    
    [key: string]: unknown;
    trigger_key?: string;
}

interface WhatsAppEditorSectionProps {
    rule: Rule;
    updateRule: (updates: Partial<Rule>) => void;
    isAdmin: boolean;
    isCampaign: boolean;
    isMeta: boolean;
    messageField: string;
    finalEditorId: string;
    placeholders?: Record<string, string>;
    onOpenPersonalization: (editorId: string) => void;
    onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;

}

export function WhatsAppEditorSection({
    rule,
    updateRule,
    isAdmin,
    isCampaign,
    isMeta,
    messageField,
    finalEditorId,
    placeholders,
    onOpenPersonalization,
    onKeyDown,

}: WhatsAppEditorSectionProps) {
    const [isQAOpen, setQAOpen] = React.useState(false);

    const activeContent = String(rule[messageField] || '');

    const handleContentChange = (val: string) => {
        updateRule({ [messageField]: val });
    };


    const greetings = [
        { label: 'اهلا', value: 'اهلا {{user_login}}' },
        { label: 'مرحبا', value: 'مرحبا بك يا {{user_login}}' },
        { label: 'السلام عليكم', value: 'السلام عليكم ورحمة الله وبركاته' },
        { label: 'تحية طيبة', value: 'تحية طيبة وبعد،' },
        { label: 'عزيزي', value: 'عزيزي {{user_login}}،' },
        { label: 'Hi (Eng)', value: 'Hi {{user_login}} 👋' },
        { label: 'Welcome', value: 'Welcome to {{site_name}}!' }
    ];

    const [visibleTools, setVisibleTools] = React.useState<string[]>(['greetings', 'personalize', 'emoji']);

    const ALL_TOOLS = [
        { id: 'greetings', label: 'Greetings', icon: HeartHandshake },
        { id: 'personalize', label: 'Personalize', icon: Type },
        { id: 'emoji', label: 'Emoji', icon: Smile },
        { id: 'formatting', label: 'Help', icon: Info },
    ];

    const handleToolSelect = (toolId: string) => {
        if (!visibleTools.includes(toolId)) {
            const newVisible = [...visibleTools];
            newVisible[2] = toolId; // Swap the last one
            setVisibleTools(newVisible);
        }
    };

    const renderTool = (toolId: string) => {
        switch (toolId) {
            case 'greetings':
                return (
                    <Popover key="greetings">
                        <PopoverTrigger asChild>
                            <GhostButton
                                className="h-8 px-2.5 text-[12px] font-bold text-slate-600 hover:text-emerald-600 transition-all gap-1.5 hover:bg-emerald-50/30 rounded-md"
                                icon={HeartHandshake}
                            >
                                Greetings
                            </GhostButton>
                        </PopoverTrigger>
                        <PopoverContent className="w-48 p-1 rounded-xl border-slate-200 shadow-xl" align="start">
                            <div className="p-2 border-b border-slate-50 mb-1">
                                <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest pl-1">Smart Greetings</span>
                            </div>
                            <div className="grid grid-cols-1 gap-0.5">
                                {greetings.map((g, i) => (
                                    <button
                                        key={i}
                                        onClick={() => {
                                            const newVal = (activeContent ? g.value + '\n' + activeContent : g.value);
                                            handleContentChange(newVal);
                                        }}
                                        className="flex items-center w-full px-3 py-2 text-[11px] font-bold text-slate-600 hover:bg-slate-50 rounded-lg transition-all text-right border-none"
                                        style={{ direction: /[\u0600-\u06FF]/.test(g.label) ? 'rtl' : 'ltr' }}
                                    >
                                        {g.label}
                                    </button>
                                ))}
                            </div>
                        </PopoverContent>
                    </Popover>
                );
            case 'personalize':
                return (
                    <GhostButton
                        key="personalize"
                        className="h-8 px-2.5 text-[12px] font-bold text-slate-600 hover:text-primary transition-all gap-1.5 hover:bg-primary/5 rounded-md"
                        onClick={() => onOpenPersonalization(finalEditorId)}
                        icon={Type}
                    >
                        Personalize
                    </GhostButton>
                );
            case 'emoji':
                return <EmojiPickerButton key="emoji" targetId={finalEditorId} value={activeContent} onChange={handleContentChange} />;
            case 'formatting':
                return <FormattingHelpButton key="formatting" targetId={finalEditorId} value={activeContent} onChange={handleContentChange} />;
            default:
                return null;
        }
    };

    return (
        <div className="flex-1 lg:w-[50%] flex flex-col min-w-0">
            <WhatsAppEditor 
                targetId={finalEditorId}
                value={activeContent}
                onChange={handleContentChange}
                onKeyDown={onKeyDown}
                placeholder={isMeta ? "Type session message..." : "Enter WhatsApp message content..."}
                minHeight={isCampaign ? "320px" : (isAdmin ? "120px" : "280px")}
                className="rounded-none border-0"
                placeholders={placeholders || {}}
            />
            
            <div className="px-3 py-2 bg-white flex items-center justify-between shrink-0 mb-0 mt-0 border-t border-slate-100">
                <div className="flex items-center gap-1">
                    {visibleTools.map(renderTool)}

                    <Popover>
                        <PopoverTrigger asChild>
                            <GhostButton
                                className="h-8 w-8 p-0 text-slate-400 hover:text-emerald-600 transition-all hover:bg-emerald-50/30 rounded-md"
                                icon={MoreHorizontal}
                            >
                                {null}
                            </GhostButton>
                        </PopoverTrigger>
                        <PopoverContent className="w-56 p-1 rounded-xl border-slate-200 shadow-2xl" align="start">
                            <div className="p-2 border-b border-slate-50 mb-1">
                                <span className="text-[9px] font-black text-slate-300 uppercase tracking-[0.2em] pl-1">All Tools</span>
                            </div>
                            <div className="grid grid-cols-1 gap-0.5">
                                {ALL_TOOLS.map((tool) => (
                                    <button
                                        key={tool.id}
                                        onClick={() => handleToolSelect(tool.id)}
                                        className={cn(
                                            "flex items-center gap-3 w-full px-3 py-2 text-[11px] font-bold rounded-lg transition-all text-left",
                                            visibleTools.includes(tool.id) ? "bg-slate-50 text-emerald-600" : "text-slate-600 hover:bg-slate-50"
                                        )}
                                    >
                                        <tool.icon className="w-3.5 h-3.5 opacity-60" />
                                        {tool.label}
                                        {visibleTools.includes(tool.id) && <div className="ml-auto w-1 h-1 rounded-full bg-emerald-500" />}
                                    </button>
                                ))}
                            </div>
                        </PopoverContent>
                    </Popover>
                </div>
                <div className="flex items-center gap-3">
                    <WhatsAppSpamChecker 
                        value={activeContent} 
                        isOpen={isQAOpen}
                        onToggle={() => setQAOpen(!isQAOpen)}
                    />

                    <Separator orientation="vertical" className="h-3" />

                    <span className="text-[10px] text-slate-400 font-bold tracking-tight opacity-70 px-2 shrink-0">
                        {activeContent.length} CHARS
                    </span>
                </div>
            </div>

            {/* Integrated QA Diagnostic Panel - Tied to this side */}
            <WhatsAppQAResults 
                value={activeContent}
                isOpen={isQAOpen}
                triggerKey={rule.trigger_key}
            />
        </div>
    );
}
