import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { showNotification } from '@mantine/notifications';
import { Text, Group, Button, Tabs, Switch, ScrollArea, Paper, ActionIcon, NavLink } from '@mantine/core';
import {
    fetchAllNotificationTemplates,
    fetchAllNotificationChannels,
    fetchNotificationTemplate,
    updateNotificationTemplate,
} from '../../Notification/store/notificationTemplateSlice';
import { __ } from '@wordpress/i18n';

const S = {
    orange: '#ED7D31', orangeDk: '#D46A1E', orangeLt: '#FEF0E6',
    teal: '#39758D', tealLt: '#EBF1F4', tealDk: '#2C5C6E',
    bg: '#F4F6F8', white: '#FFFFFF', border: '#E2E8F0',
    text: '#1A202C', muted: '#64748B', light: '#94A3B8',
    danger: '#EF4444',
    shadow: '0 1px 3px rgba(0,0,0,.07)',
    radius: 12, radiusSm: 6,
};

const CHANNEL_COLORS = {
    email: '#3B82F6',
    sms: '#10B981',
    mobile: '#8B5CF6',
    'web-app': '#39758D',
    'web_app': '#39758D',
    browser: '#F59E0B',
};

const VARIABLES = [
    '[NAME]', '[TASK_NAME]', '[PROJECT_NAME]', '[COMPANY_NAME]',
    '[MEMBER_NAME]', '[CREATOR_NAME]', '[LOGIN_URL]', '[USERNAME]',
    '[PASSWORD]', '[MEMBER_ROLES]', '[PREVIOUS_ASSIGNED_DATE]', '[NEW_ASSIGNED_DATE]',
];

function Btn({ children, variant = 'primary', loading, style, disabled, onClick, type = 'button' }) {
    const colorMap = { primary: 'orange', ghost: 'gray' };
    const variantMap = { primary: 'filled', ghost: 'outline' };
    return (
        <Button type={type} variant={variantMap[variant] || 'filled'} color={colorMap[variant] || 'orange'}
            size="xs" disabled={disabled} loading={loading} onClick={onClick} style={{ fontWeight: 500, ...style }}>
            {children}
        </Button>
    );
}

function ChannelDot({ slug }) {
    const color = CHANNEL_COLORS[slug] || S.light;
    return (
        <span
            title={slug}
            style={{
                display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
                background: color, flexShrink: 0,
            }}
        />
    );
}

function parseChannelStatus(raw) {
    if (!raw) return {};
    if (typeof raw === 'object') return raw;
    try { return JSON.parse(raw); } catch { return {}; }
}

export default function NotificationTemplatesTabV3() {
    const dispatch = useDispatch();
    const { notificationTemplates, notificationChannels, notificationTemplate } =
        useSelector(state => state.notifications.notificationTemplate);
    const { loggedUserId } = useSelector(state => state.auth.user);

    const [isLoading, setIsLoading] = useState(true);
    const [selectedId, setSelectedId] = useState(null);
    const [loadingTemplate, setLoadingTemplate] = useState(false);
    const [activeChannel, setActiveChannel] = useState(null);
    const [isSaving, setIsSaving] = useState(false);

    // Edit form local state
    const [editTitle, setEditTitle] = useState('');
    const [editContent, setEditContent] = useState({});
    const [channelStatus, setChannelStatus] = useState({});
    const [emailSubject, setEmailSubject] = useState('');
    const [mobileTitle, setMobileTitle] = useState('');
    const [notifActionName, setNotifActionName] = useState('');

    // Variable picker
    const [varOpen, setVarOpen] = useState(false);
    const [varQuery, setVarQuery] = useState('');
    const [varCursor, setVarCursor] = useState(0);
    const [varHighlight, setVarHighlight] = useState(0);
    const textareaRefs = useRef({});
    const varDropdownRef = useRef(null);

    useEffect(() => {
        setIsLoading(true);
        Promise.all([
            dispatch(fetchAllNotificationTemplates()),
            dispatch(fetchAllNotificationChannels()),
        ]).then(() => setIsLoading(false));
    }, [dispatch]);

    // Sync right panel when the fetched single template changes
    useEffect(() => {
        if (!notificationTemplate || !notificationTemplate.id) return;
        setEditTitle(notificationTemplate.title || '');
        setEditContent(notificationTemplate.content || {});
        setChannelStatus(parseChannelStatus(notificationTemplate.channel_status));
        setEmailSubject(notificationTemplate.email_subject || '');
        setMobileTitle(notificationTemplate.mobile_notification_title || '');
        setNotifActionName(notificationTemplate.notification_action_name || '');
        // Default to first channel
        if (notificationChannels && notificationChannels.length > 0) {
            setActiveChannel(notificationChannels[0].slug);
        }
    }, [notificationTemplate]);

    const selectTemplate = useCallback((id) => {
        if (id === selectedId) return;
        setSelectedId(id);
        setLoadingTemplate(true);
        setVarOpen(false);
        dispatch(fetchNotificationTemplate(id)).then(() => setLoadingTemplate(false));
    }, [selectedId, dispatch]);

    // Save changes for current template
    const handleSave = async () => {
        if (!notificationTemplate?.id) return;
        setIsSaving(true);
        const data = {
            title: editTitle,
            description: notificationTemplate.description || '',
            content: editContent,
            channel_status: channelStatus,
            notification_action_name: notifActionName,
            email_subject: emailSubject,
            mobile_notification_title: mobileTitle,
            created_by: loggedUserId,
        };
        const res = await dispatch(updateNotificationTemplate({ id: notificationTemplate.id, data }));
        setIsSaving(false);
        const ok = res.payload?.status === 200;
        showNotification({
            title: ok ? __( 'Saved', 'lazytasks-project-task-management' ) : __( 'Error', 'lazytasks-project-task-management' ),
            message: res.payload?.message || '',
            color: ok ? 'green' : 'red',
            autoClose: 2500,
        });
    };

    // Variable picker logic
    const handleTextareaChange = (slug, e) => {
        const val = e.target.value;
        setEditContent(prev => ({ ...prev, [slug]: val }));
        const cursor = e.target.selectionStart;
        const before = val.slice(0, cursor);
        const match = before.match(/\/(\w*)$/);
        if (match) {
            setVarQuery(match[1]);
            setVarCursor(cursor);
            setVarOpen(true);
            setVarHighlight(0);
        } else {
            setVarOpen(false);
        }
    };

    const handleTextareaKeyDown = (slug, e) => {
        if (!varOpen) return;
        const filtered = VARIABLES.filter(v => v.toLowerCase().includes(varQuery.toLowerCase()));
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            setVarHighlight(h => Math.min(h + 1, filtered.length - 1));
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            setVarHighlight(h => Math.max(h - 1, 0));
        } else if (e.key === 'Enter' && filtered.length > 0) {
            e.preventDefault();
            insertVariable(slug, filtered[varHighlight]);
        } else if (e.key === 'Escape') {
            setVarOpen(false);
        }
    };

    const insertVariable = (slug, variable) => {
        const textarea = textareaRefs.current[slug];
        if (!textarea) return;
        const val = editContent[slug] || '';
        const cursor = textarea.selectionStart;
        const before = val.slice(0, cursor);
        const slashIdx = before.lastIndexOf('/');
        const newVal = val.slice(0, slashIdx) + variable + val.slice(cursor);
        setEditContent(prev => ({ ...prev, [slug]: newVal }));
        setVarOpen(false);
        // Move cursor after inserted variable
        const newCursor = slashIdx + variable.length;
        setTimeout(() => {
            if (textarea) {
                textarea.focus();
                textarea.setSelectionRange(newCursor, newCursor);
            }
        }, 0);
    };

    const filteredVars = VARIABLES.filter(v =>
        v.toLowerCase().includes(varQuery.toLowerCase())
    );

    // Channels that are visible (filter sms if not enabled — same as old component, we'll show all from API)
    const channels = notificationChannels || [];

    // Channels with content for list dots
    const templateChannelSlugs = (tpl) => {
        if (!tpl?.content) return [];
        return Object.keys(tpl.content).filter(k => tpl.content[k]);
    };

    const inputStyle = {
        width: '100%', height: 36, padding: '0 10px', borderRadius: S.radiusSm,
        border: `1px solid ${S.border}`, fontSize: 13, outline: 'none',
        fontFamily: 'inherit', color: S.text, background: S.white, boxSizing: 'border-box',
    };
    const labelStyle = { fontSize: 12, fontWeight: 600, color: '#495057', marginBottom: 5, display: 'block' };

    return (
        <div>
            {/* Header */}
            <Group justify="space-between" align="flex-start" mb={20}
                style={{ position: 'sticky', top: 0, zIndex: 10, background: '#F4F6F8', paddingTop: 4, paddingBottom: 4 }}>
                <div>
                    <Text fz={16} fw={700} c={S.text}>{__( 'Notification Templates', 'lazytasks-project-task-management' )}</Text>
                    <Text fz={12} c="dimmed" mt={2}>{__( 'Configure message templates for each notification event', 'lazytasks-project-task-management' )}</Text>
                </div>
                <Button size="xs" color="orange" loading={isSaving}
                    disabled={!notificationTemplate?.id || isSaving}
                    onClick={handleSave}
                    leftSection={
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
                            <polyline points="17 21 17 13 7 13 7 21" />
                            <polyline points="7 3 7 8 15 8" />
                        </svg>
                    }>
                    {isSaving ? __( 'Saving…', 'lazytasks-project-task-management' ) : __( 'Save', 'lazytasks-project-task-management' )}
                </Button>
            </Group>

            {isLoading ? (
                <div style={{ padding: 60, textAlign: 'center', color: S.muted, fontSize: 14 }}>
                    {__( 'Loading templates…', 'lazytasks-project-task-management' )}
                </div>
            ) : (
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: '300px 1fr',
                    border: `1px solid ${S.border}`,
                    borderRadius: S.radius,
                    overflow: 'hidden',
                    minHeight: 500,
                    background: S.white,
                    boxShadow: S.shadow,
                }}>
                    {/* LEFT PANEL — Template list */}
                    <div style={{ borderRight: `1px solid ${S.border}`, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
                        {/* List header */}
                        <div style={{
                            padding: '10px 14px', background: S.tealLt,
                            borderBottom: `1px solid ${S.border}`,
                            fontSize: 11, fontWeight: 700, color: S.muted,
                            textTransform: 'uppercase', letterSpacing: '0.06em',
                            flexShrink: 0,
                        }}>
                            {__( 'Templates', 'lazytasks-project-task-management' )}
                        </div>

                        <ScrollArea style={{ flex: 1 }}>
                        {notificationTemplates && notificationTemplates.length > 0 ? (
                            notificationTemplates.map(tpl => {
                                const isSelected = selectedId === tpl.id;
                                const slugs = templateChannelSlugs(tpl);
                                return (
                                    <NavLink
                                        key={tpl.id}
                                        active={isSelected}
                                        onClick={() => selectTemplate(tpl.id)}
                                        label={
                                            <Text fz={12} fw={isSelected ? 600 : 500} c={isSelected ? S.teal : S.text}
                                                style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                                {tpl.title}
                                            </Text>
                                        }
                                        description={
                                            <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap', marginTop: 2 }}>
                                                {slugs.map(slug => <ChannelDot key={slug} slug={slug} />)}
                                                {tpl.notification_action_name && (
                                                    <Text fz={10} c={S.light} style={{ fontFamily: 'monospace', maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                        {tpl.notification_action_name}
                                                    </Text>
                                                )}
                                            </div>
                                        }
                                        color="teal"
                                        styles={{
                                            root: {
                                                borderLeft: isSelected ? `3px solid ${S.teal}` : '3px solid transparent',
                                                borderBottom: `1px solid ${S.border}`,
                                                borderRadius: 0,
                                                padding: '10px 14px',
                                            },
                                        }}
                                    />
                                );
                            })
                        ) : (
                            <div style={{ padding: 24, textAlign: 'center', color: S.light, fontSize: 13 }}>
                                {__( 'No templates found', 'lazytasks-project-task-management' )}
                            </div>
                        )}
                        </ScrollArea>
                    </div>

                    {/* RIGHT PANEL — Edit form */}
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        {!selectedId ? (
                            <div style={{
                                flex: 1, display: 'flex', flexDirection: 'column',
                                alignItems: 'center', justifyContent: 'center',
                                color: S.light, gap: 8, padding: 40,
                            }}>
                                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={S.border} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M18 8h1a4 4 0 0 1 0 8h-1" />
                                    <path d="M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4V8z" />
                                    <line x1="6" y1="1" x2="6" y2="4" />
                                    <line x1="10" y1="1" x2="10" y2="4" />
                                    <line x1="14" y1="1" x2="14" y2="4" />
                                </svg>
                                <div style={{ fontSize: 13, color: S.muted }}>{__( 'Select a template to edit', 'lazytasks-project-task-management' )}</div>
                            </div>
                        ) : loadingTemplate ? (
                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: S.muted, fontSize: 13 }}>
                                {__( 'Loading…', 'lazytasks-project-task-management' )}
                            </div>
                        ) : notificationTemplate && notificationTemplate.id === selectedId ? (
                            <div style={{ padding: 20, flex: 1, display: 'flex', flexDirection: 'column', gap: 16 }}>
                                {/* Template title + hook */}
                                <div>
                                    <div style={{ fontSize: 15, fontWeight: 700, color: S.text }}>{editTitle}</div>
                                    {notifActionName && (
                                        <div style={{ fontSize: 11, color: S.muted, fontFamily: 'monospace', marginTop: 3 }}>
                                            {notifActionName}
                                        </div>
                                    )}
                                </div>

                                {/* Channel tab strip */}
                                {channels.length > 0 && (
                                    <Tabs value={activeChannel} onChange={setActiveChannel} color="teal">
                                        <Tabs.List>
                                            {channels.map(ch => {
                                                const dotColor = CHANNEL_COLORS[ch.slug] || S.light;
                                                return (
                                                    <Tabs.Tab key={ch.id} value={ch.slug}
                                                        leftSection={<span style={{ width: 7, height: 7, borderRadius: '50%', background: dotColor, display: 'inline-block' }} />}>
                                                        {ch.name}
                                                    </Tabs.Tab>
                                                );
                                            })}
                                        </Tabs.List>
                                    </Tabs>
                                )}

                                {/* Active channel form */}
                                {activeChannel && (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
                                        {/* Enable/Disable toggle */}
                                        <Switch
                                            checked={channelStatus[activeChannel] || false}
                                            onChange={(e) => setChannelStatus(prev => ({ ...prev, [activeChannel]: e.currentTarget.checked }))}
                                            color="orange"
                                            size="sm"
                                            label={<Text fz={13} fw={500} c={S.text}>{__( 'Enable', 'lazytasks-project-task-management' )}</Text>}
                                        />

                                        {/* Email subject */}
                                        {activeChannel === 'email' && (
                                            <div>
                                                <label style={labelStyle}>{__( 'Email Subject', 'lazytasks-project-task-management' )}</label>
                                                <input
                                                    style={inputStyle}
                                                    value={emailSubject}
                                                    onChange={e => setEmailSubject(e.target.value)}
                                                    placeholder={__( 'Enter email subject', 'lazytasks-project-task-management' )}
                                                />
                                            </div>
                                        )}

                                        {/* Mobile title */}
                                        {activeChannel === 'mobile' && (
                                            <div>
                                                <label style={labelStyle}>{__( 'Notification Title', 'lazytasks-project-task-management' )}</label>
                                                <input
                                                    style={inputStyle}
                                                    value={mobileTitle}
                                                    onChange={e => setMobileTitle(e.target.value)}
                                                    placeholder={__( 'Enter notification title', 'lazytasks-project-task-management' )}
                                                />
                                            </div>
                                        )}

                                        {/* Message body with variable picker */}
                                        <div style={{ flex: 1, position: 'relative' }}>
                                            <label style={labelStyle}>
                                                {__( 'Message Body', 'lazytasks-project-task-management' )}
                                                <span style={{ fontSize: 10, fontWeight: 400, color: S.light, marginLeft: 6 }}>
                                                    {__( 'Type / to insert a variable', 'lazytasks-project-task-management' )}
                                                </span>
                                            </label>
                                            <textarea
                                                ref={el => { textareaRefs.current[activeChannel] = el; }}
                                                value={editContent[activeChannel] || ''}
                                                onChange={e => handleTextareaChange(activeChannel, e)}
                                                onKeyDown={e => handleTextareaKeyDown(activeChannel, e)}
                                                onBlur={() => setTimeout(() => setVarOpen(false), 150)}
                                                placeholder={__( 'Enter message content…', 'lazytasks-project-task-management' )}
                                                rows={8}
                                                style={{
                                                    width: '100%', padding: '8px 10px', borderRadius: S.radiusSm,
                                                    border: `1px solid ${S.border}`, fontSize: 13, outline: 'none',
                                                    fontFamily: 'monospace', color: S.text, background: S.white,
                                                    resize: 'vertical', lineHeight: 1.6, boxSizing: 'border-box',
                                                }}
                                            />

                                            {/* Variable picker dropdown */}
                                            {varOpen && filteredVars.length > 0 && (
                                                <div
                                                    ref={varDropdownRef}
                                                    style={{
                                                        position: 'absolute', bottom: 'calc(100% - 38px)', left: 0,
                                                        background: S.white, border: `1px solid ${S.border}`,
                                                        borderRadius: S.radiusSm, boxShadow: '0 4px 12px rgba(0,0,0,.12)',
                                                        zIndex: 100, minWidth: 200, maxHeight: 200, overflowY: 'auto',
                                                    }}
                                                >
                                                    <div style={{ padding: '6px 10px', fontSize: 10, fontWeight: 700, color: S.light, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: `1px solid ${S.border}` }}>
                                                        {__( 'Variables', 'lazytasks-project-task-management' )}
                                                    </div>
                                                    {filteredVars.map((v, i) => (
                                                        <button
                                                            key={v}
                                                            onMouseDown={e => { e.preventDefault(); insertVariable(activeChannel, v); }}
                                                            style={{
                                                                display: 'block', width: '100%', textAlign: 'left',
                                                                padding: '6px 10px', border: 'none', cursor: 'pointer',
                                                                background: i === varHighlight ? S.tealLt : 'transparent',
                                                                fontFamily: 'monospace', fontSize: 12,
                                                                color: i === varHighlight ? S.teal : S.text,
                                                                fontWeight: i === varHighlight ? 600 : 400,
                                                            }}
                                                        >
                                                            {v}
                                                        </button>
                                                    ))}
                                                </div>
                                            )}
                                        </div>

                                        {/* Variable quick-insert chips */}
                                        <div>
                                            <Text fz={10} fw={700} c={S.light} tt="uppercase" style={{ letterSpacing: '0.05em', marginBottom: 6 }}>
                                                {__( 'Quick insert', 'lazytasks-project-task-management' )}
                                            </Text>
                                            <Group gap={4} style={{ flexWrap: 'wrap' }}>
                                                {VARIABLES.map(v => (
                                                    <Button key={v} variant="light" color="teal" size="compact-xs"
                                                        onClick={() => {
                                                            const textarea = textareaRefs.current[activeChannel];
                                                            if (!textarea) return;
                                                            const pos = textarea.selectionStart;
                                                            const val = editContent[activeChannel] || '';
                                                            const newVal = val.slice(0, pos) + v + val.slice(pos);
                                                            setEditContent(prev => ({ ...prev, [activeChannel]: newVal }));
                                                            const newPos = pos + v.length;
                                                            setTimeout(() => { textarea.focus(); textarea.setSelectionRange(newPos, newPos); }, 0);
                                                        }}
                                                        styles={{ root: { fontSize: 10, fontFamily: 'monospace' } }}>
                                                        {v}
                                                    </Button>
                                                ))}
                                            </Group>
                                        </div>

                                    </div>
                                )}
                            </div>
                        ) : (
                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: S.muted, fontSize: 13 }}>
                                {__( 'Loading…', 'lazytasks-project-task-management' )}
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
