import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
    ActionIcon,
    Avatar,
    Box,
    Flex,
    Indicator,
    Paper,
    Popover,
    ScrollArea,
    Text,
    TextInput,
    Title,
    Tooltip,
} from '@mantine/core';
import { modals } from '@mantine/modals';
import { IconExchange, IconHelpCircle, IconRobot, IconSend, IconTrash, IconX } from '@tabler/icons-react';
import { createQuickTask, deleteQuickTask } from '../Settings/store/quickTaskSlice';
import { processInput } from './chatCommands';
import AddTaskFromQuickTaskDrawer from '../QuickTask/AddTaskFromQuickTaskDrawer';
import { translate } from '../../utils/i18n';
import dayjs from 'dayjs';

const STORAGE_KEY = (userId) => `lt_quickchat_${userId}`;
const POSITION_KEY = 'lt_quickchat_pos';

const PANEL_W = 360;
const PANEL_H = 500;
const GAP = 8;

const WELCOME_MESSAGE = {
    id: 'welcome',
    from: 'bot',
    type: 'text',
    text: "Hi! 👋 I'm your Quick Task assistant.\n\nType anything to jot it down before you forget, or type `list` to see all your saved quick tasks.\n\nType `help` anytime for more options.",
};

const HELP_COMMANDS = [
    { cmd: 'list', desc: 'Show all your quick tasks' },
    { cmd: 'search [term]', desc: 'Filter by keyword' },
    { cmd: 'count', desc: 'How many tasks you have' },
    { cmd: 'convert [# or name]', desc: 'Convert to a full task' },
    { cmd: 'delete [# or name]', desc: 'Delete a quick task' },
    { cmd: 'done [#]', desc: 'Delete task by position' },
    { cmd: 'clear', desc: 'Clear this chat' },
    { cmd: 'clear tasks', desc: 'Delete all quick tasks' },
    { cmd: 'help', desc: 'Show this reference' },
    { cmd: 'hi / hello', desc: 'Say hi 👋' },
];

// ─── Sub-components ────────────────────────────────────────────────────────────

const BotAvatar = () => (
    <Avatar size={28} radius="xl" style={{ backgroundColor: '#39758D', flexShrink: 0, marginTop: 2 }}>
        <IconRobot size={16} color="white" />
    </Avatar>
);

const MessageBubble = ({ msg, onDelete, onConvert }) => {
    if (msg.from === 'user') {
        return (
            <Flex justify="flex-end" mb={10}>
                <Box style={{ backgroundColor: '#39758D', borderRadius: '12px 4px 12px 12px', padding: '8px 12px', maxWidth: '75%' }}>
                    <Text size="sm" c="white" style={{ whiteSpace: 'pre-line' }}>{msg.text}</Text>
                </Box>
            </Flex>
        );
    }

    if (msg.type === 'task-list') {
        return (
            <Flex gap={8} mb={10} align="flex-start">
                <BotAvatar />
                <Box style={{ maxWidth: '85%' }}>
                    <Box style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '4px 12px 12px 12px', padding: '8px 12px', marginBottom: msg.tasks?.length > 0 ? 6 : 0 }}>
                        <Text size="sm">{msg.text}</Text>
                    </Box>
                    {msg.tasks && msg.tasks.map((task, idx) => (
                        <Flex key={task.id} align="center" justify="space-between" style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, padding: '6px 10px', marginBottom: 4 }}>
                            <Box style={{ flex: 1, marginRight: 8, minWidth: 0 }}>
                                <Text size="xs" c="dimmed" mb={1}>#{idx + 1}</Text>
                                <Text size="xs" lineClamp={2}>{task.name}</Text>
                                {task.created_at && (
                                    <Text size="xs" c="dimmed" mt={2}>{dayjs(task.created_at).format('MMM D, h:mm A')}</Text>
                                )}
                            </Box>
                            <Flex gap={4} style={{ flexShrink: 0 }}>
                                <Tooltip label={translate('Convert to Task')} position="top" withArrow withinPortal>
                                    <ActionIcon size="xs" variant="light" color="orange" onClick={() => onConvert(task)}>
                                        <IconExchange size={12} />
                                    </ActionIcon>
                                </Tooltip>
                                <Tooltip label={translate('Delete')} position="top" withArrow withinPortal>
                                    <ActionIcon size="xs" variant="light" color="red" onClick={() => onDelete(task.id, task.name)}>
                                        <IconTrash size={12} />
                                    </ActionIcon>
                                </Tooltip>
                            </Flex>
                        </Flex>
                    ))}
                </Box>
            </Flex>
        );
    }

    return (
        <Flex gap={8} mb={10} align="flex-start">
            <BotAvatar />
            <Box style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '4px 12px 12px 12px', padding: '8px 12px', maxWidth: '75%' }}>
                <Text size="sm" style={{ whiteSpace: 'pre-line' }}>{msg.text}</Text>
            </Box>
        </Flex>
    );
};

const TypingIndicator = () => (
    <Flex gap={8} mb={10} align="flex-start">
        <BotAvatar />
        <Box style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '4px 12px 12px 12px', padding: '8px 14px' }}>
            <Text size="sm" c="dimmed">●&nbsp;●&nbsp;●</Text>
        </Box>
    </Flex>
);

// ─── Main component ────────────────────────────────────────────────────────────

const QuickTaskChatBot = ({ userId }) => {
    const dispatch = useDispatch();
    const { tasks } = useSelector((state) => state.settings.quickTask);
    const { name: userName } = useSelector((state) => state.auth.user);

    const [isOpen, setIsOpen] = useState(false);
    const [panelStyle, setPanelStyle] = useState({});
    const [messages, setMessages] = useState([WELCOME_MESSAGE]);
    const [inputValue, setInputValue] = useState('');
    const [isTyping, setIsTyping] = useState(false);
    const [selectedTask, setSelectedTask] = useState(null);
    const [convertDrawerOpen, setConvertDrawerOpen] = useState(false);
    const [isBouncing, setIsBouncing] = useState(true);

    // Bounce once on first mount to draw attention, then clear so it doesn't repeat
    useEffect(() => {
        const t = setTimeout(() => setIsBouncing(false), 1000);
        return () => clearTimeout(t);
    }, []);


    // Drag state — null means "use CSS default top-right"
    const [position, setPosition] = useState(() => {
        try {
            const saved = localStorage.getItem(POSITION_KEY);
            return saved ? JSON.parse(saved) : null;
        } catch { return null; }
    });

    const containerRef = useRef(null);
    const isDragging = useRef(false);
    const dragOffset = useRef({ x: 0, y: 0 });
    const hasDragged = useRef(false);
    const bottomRef = useRef(null);
    const inputRef = useRef(null);

    useEffect(() => {
        bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages, isTyping]);

    // Global mouse handlers for drag
    useEffect(() => {
        const onMouseMove = (e) => {
            if (!isDragging.current) return;
            hasDragged.current = true;
            setPosition({
                x: Math.max(0, Math.min(e.clientX - dragOffset.current.x, window.innerWidth - 60)),
                y: Math.max(0, Math.min(e.clientY - dragOffset.current.y, window.innerHeight - 60)),
            });
        };
        const onMouseUp = () => {
            if (!isDragging.current) return;
            isDragging.current = false;
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
            if (hasDragged.current) {
                setPosition((prev) => {
                    if (prev) localStorage.setItem(POSITION_KEY, JSON.stringify(prev));
                    return prev;
                });
            }
        };
        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
        return () => {
            window.removeEventListener('mousemove', onMouseMove);
            window.removeEventListener('mouseup', onMouseUp);
        };
    }, []);

    const handleMouseDown = useCallback((e) => {
        isDragging.current = true;
        hasDragged.current = false;
        const rect = containerRef.current.getBoundingClientRect();
        dragOffset.current = { x: e.clientX - rect.left, y: e.clientY - rect.top };
        document.body.style.cursor = 'grabbing';
        document.body.style.userSelect = 'none';
        e.preventDefault();
    }, []);

    // Compute chat panel position with flip logic based on button's screen rect
    const computePanelStyle = useCallback(() => {
        if (!containerRef.current) return;
        const rect = containerRef.current.getBoundingClientRect();
        const vw = window.innerWidth;
        const vh = window.innerHeight;

        // Vertical: prefer below, flip above if not enough room
        let top;
        if (rect.bottom + GAP + PANEL_H <= vh) {
            top = rect.bottom + GAP;
        } else {
            top = Math.max(GAP, rect.top - GAP - PANEL_H);
        }

        // Horizontal: right-align to button edge, flip if panel overflows left
        let left = rect.right - PANEL_W;
        if (left < GAP) left = rect.left;
        left = Math.max(GAP, Math.min(left, vw - PANEL_W - GAP));

        setPanelStyle({ position: 'fixed', top, left, zIndex: 1001 });
    }, []);

    useEffect(() => {
        if (!isOpen) return;
        const handler = () => computePanelStyle();
        window.addEventListener('resize', handler);
        return () => window.removeEventListener('resize', handler);
    }, [isOpen, computePanelStyle]);

    const handleOpen = () => {
        const saved = localStorage.getItem(STORAGE_KEY(userId));
        if (saved) {
            try { setMessages(JSON.parse(saved)); } catch { setMessages([WELCOME_MESSAGE]); }
        } else {
            setMessages([WELCOME_MESSAGE]);
        }
        setIsOpen(true);
        requestAnimationFrame(() => {
            computePanelStyle();
            setTimeout(() => inputRef.current?.focus(), 150);
        });
    };

    const handleClose = () => {
        if (messages.length <= 1) { setIsOpen(false); return; }
        modals.openConfirmModal({
            title: <Title order={5}>{translate('Save conversation?')}</Title>,
            children: <Text size="sm" mb="lg">{translate("Would you like to save this conversation so it's here next time you open it?")}</Text>,
            labels: { confirm: translate('Yes, save it'), cancel: translate('No, clear it') },
            confirmProps: { style: { backgroundColor: '#39758D' } },
            onConfirm: () => { localStorage.setItem(STORAGE_KEY(userId), JSON.stringify(messages)); setIsOpen(false); },
            onCancel: () => { localStorage.removeItem(STORAGE_KEY(userId)); setIsOpen(false); },
        });
    };

    const appendBotMessage = (msg) => {
        setMessages((prev) => [...prev, { id: Date.now() + Math.random(), ...msg }]);
    };

    const handleSend = async () => {
        const input = inputValue.trim();
        if (!input || isTyping) return;

        const userMsg = { id: Date.now(), from: 'user', type: 'text', text: input };
        setMessages((prev) => [...prev, userMsg]);
        setInputValue('');
        setIsTyping(true);

        try {
            const result = await processInput(input, { dispatch, userId, userName, tasks });
            setTimeout(() => {
                setIsTyping(false);
                inputRef.current?.focus();

                if (result.type !== 'action') {
                    appendBotMessage(result);
                    return;
                }

                // ── Action handlers ──────────────────────────────────────────
                if (result.action === 'clear-chat') {
                    modals.openConfirmModal({
                        title: <Title order={5}>{translate('Clear chat?')}</Title>,
                        children: <Text size="sm" mb="lg">{translate('This will remove all messages from this conversation.')}</Text>,
                        labels: { confirm: translate('Clear'), cancel: translate('Cancel') },
                        confirmProps: { color: 'red' },
                        onConfirm: () => { localStorage.removeItem(STORAGE_KEY(userId)); setMessages([WELCOME_MESSAGE]); },
                    });

                } else if (result.action === 'clear-tasks') {
                    if (!tasks || tasks.length === 0) {
                        appendBotMessage({ from: 'bot', type: 'text', text: "You have no quick tasks to delete." });
                        return;
                    }
                    modals.openConfirmModal({
                        title: <Title order={5}>{translate('Delete all quick tasks?')}</Title>,
                        children: <Text size="sm" mb="lg">{translate('This will permanently delete all')} {tasks.length} {translate('quick tasks')}. {translate('This cannot be undone.')}</Text>,
                        labels: { confirm: translate('Delete all'), cancel: translate('Cancel') },
                        confirmProps: { color: 'red' },
                        onConfirm: async () => {
                            await Promise.all(tasks.map((t) => dispatch(deleteQuickTask(t.id))));
                            appendBotMessage({ from: 'bot', type: 'text', text: `All ${tasks.length} quick tasks deleted 🗑️` });
                        },
                    });

                } else if (result.action === 'duplicate-confirm') {
                    modals.openConfirmModal({
                        title: <Title order={5}>{translate('Duplicate task?')}</Title>,
                        children: (
                            <Text size="sm" mb="lg">
                                {translate('Looks like you already have')} "{result.existingName}". {translate('Save anyway?')}
                            </Text>
                        ),
                        labels: { confirm: translate('Yes, save it'), cancel: translate('No, skip') },
                        confirmProps: { style: { backgroundColor: '#39758D' } },
                        onConfirm: async () => {
                            await dispatch(createQuickTask({ name: result.pendingInput, user_id: userId }));
                            appendBotMessage({ from: 'bot', type: 'text', text: `Got it! "${result.pendingInput}" saved ✓` });
                        },
                        onCancel: () => appendBotMessage({ from: 'bot', type: 'text', text: 'OK, skipped.' }),
                    });

                } else if (result.action === 'delete-task') {
                    modals.openConfirmModal({
                        title: <Title order={5}>{translate('Delete quick task?')}</Title>,
                        children: <Text size="sm" mb="lg">{translate('Are you sure you want to delete')} "{result.task.name}"?</Text>,
                        labels: { confirm: translate('Delete'), cancel: translate('Cancel') },
                        confirmProps: { color: 'red' },
                        onConfirm: () => {
                            dispatch(deleteQuickTask(result.task.id)).then(() => {
                                appendBotMessage({ from: 'bot', type: 'text', text: `Deleted "${result.task.name}" 🗑️` });
                            });
                        },
                    });

                } else if (result.action === 'convert-task') {
                    handleConvert(result.task);
                    appendBotMessage({ from: 'bot', type: 'text', text: `Opening "${result.task.name}" for conversion...` });
                }
            }, 450);
        } catch {
            setIsTyping(false);
            appendBotMessage({ from: 'bot', type: 'text', text: 'Oops! Something went wrong. Please try again.' });
        }
    };

    const handleDelete = (taskId, taskName) => {
        modals.openConfirmModal({
            title: <Title order={5}>{translate('Delete quick task?')}</Title>,
            children: <Text size="sm" mb="lg">{translate('Are you sure you want to delete')} "{taskName}"?</Text>,
            labels: { confirm: translate('Delete'), cancel: translate('Cancel') },
            confirmProps: { color: 'red' },
            onConfirm: () => {
                dispatch(deleteQuickTask(taskId)).then(() => {
                    appendBotMessage({ from: 'bot', type: 'text', text: `Deleted "${taskName}" 🗑️` });
                });
            },
        });
    };

    const handleConvert = (task) => { setSelectedTask(task); setConvertDrawerOpen(true); };
    const handleConvertClose = () => { setConvertDrawerOpen(false); setSelectedTask(null); };

    const taskCount = tasks ? tasks.length : 0;

    // Default position: top-right near the task header. Once dragged, uses saved coords.
    const containerStyle = position
        ? { position: 'fixed', left: position.x, top: position.y, zIndex: 1000 }
        : { position: 'fixed', top: 115, right: 30, zIndex: 1000 };

    return (
        <>
            {/* Fixed/draggable container */}
            <div ref={containerRef} style={containerStyle}>
                <Tooltip label={translate('Quick Task Helper')} position="left" withArrow>
                    <Indicator label={taskCount} size={20} disabled={taskCount === 0} color="red" style={{ display: 'block' }}>
                        <ActionIcon
                            onMouseDown={handleMouseDown}
                            onClick={() => {
                                if (hasDragged.current) return;
                                isOpen ? handleClose() : handleOpen();
                            }}
                            size={56}
                            radius="xl"
                            style={{
                                backgroundColor: '#EF4444',
                                boxShadow: '0 4px 20px rgba(239, 68, 68, 0.45)',
                                // Suppress transform transition while bouncing so it doesn't fight the animation
                                transition: isBouncing ? 'box-shadow 0.15s' : 'transform 0.15s, box-shadow 0.15s',
                                cursor: 'grab',
                                animation: isBouncing ? 'lt-bot-bounce 0.9s ease-in-out' : 'none',
                            }}
                            className="hover:scale-105"
                        >
                            <IconRobot size={28} color="white" />
                        </ActionIcon>
                    </Indicator>
                </Tooltip>
            </div>

            {/* Chat panel — portalled via fixed positioning with flip logic */}
            {isOpen && (
                <Paper
                    shadow="xl"
                    radius="lg"
                    style={{
                        ...panelStyle,
                        width: PANEL_W,
                        height: PANEL_H,
                        display: 'flex',
                        flexDirection: 'column',
                        border: '1px solid #e5e7eb',
                    }}
                >
                    {/* Header */}
                    <Flex
                        align="center"
                        justify="space-between"
                        px={16}
                        py={12}
                        style={{ backgroundColor: '#39758D', flexShrink: 0, borderRadius: '12px 12px 0 0' }}
                    >
                        <Flex align="center" gap={10}>
                            <Avatar size={36} radius="xl" style={{ backgroundColor: 'rgba(255,255,255,0.2)', flexShrink: 0 }}>
                                <IconRobot size={22} color="white" />
                            </Avatar>
                            <div>
                                <Text size="sm" fw={600} c="white" lh={1.2}>{translate('Quick Task Helper')}</Text>
                                <Text size="xs" c="rgba(255,255,255,0.75)" lh={1.2}>{translate('Always here to help')}</Text>
                            </div>
                        </Flex>
                        <Flex align="center" gap={4}>
                            {/* Help popover — zIndex must exceed panel's 1001 */}
                            <Popover width={260} position="bottom-end" withArrow shadow="md" withinPortal zIndex={1200}>
                                <Popover.Target>
                                    <ActionIcon
                                        variant="subtle"
                                        size="sm"
                                        style={{ color: 'rgba(255,255,255,0.85)', pointerEvents: 'all' }}
                                    >
                                        <IconHelpCircle size={17} />
                                    </ActionIcon>
                                </Popover.Target>
                                <Popover.Dropdown>
                                    <Text size="xs" fw={700} mb={8} c="#39758D">{translate('Available commands')}</Text>
                                    {HELP_COMMANDS.map(({ cmd, desc }) => (
                                        <Flex key={cmd} gap={6} mb={5} align="baseline">
                                            <Text size="xs" fw={600} style={{ fontFamily: 'monospace', backgroundColor: '#f3f4f6', padding: '1px 6px', borderRadius: 4, flexShrink: 0, whiteSpace: 'nowrap' }}>
                                                {cmd}
                                            </Text>
                                            <Text size="xs" c="dimmed">{desc}</Text>
                                        </Flex>
                                    ))}
                                    <Text size="xs" c="dimmed" mt={8}>Or just type anything to save it as a task.</Text>
                                </Popover.Dropdown>
                            </Popover>
                            <ActionIcon variant="subtle" onClick={handleClose} style={{ color: 'white' }}>
                                <IconX size={18} />
                            </ActionIcon>
                        </Flex>
                    </Flex>

                    {/* Messages */}
                    <ScrollArea style={{ flex: 1, backgroundColor: '#f9fafb' }} p={14} scrollbarSize={4}>
                        {messages.map((msg) => (
                            <MessageBubble key={msg.id} msg={msg} onDelete={handleDelete} onConvert={handleConvert} />
                        ))}
                        {isTyping && <TypingIndicator />}
                        <div ref={bottomRef} />
                    </ScrollArea>

                    {/* Input */}
                    <Box px={12} py={10} style={{ borderTop: '1px solid #e5e7eb', backgroundColor: 'white', flexShrink: 0, borderRadius: '0 0 12px 12px' }}>
                        <TextInput
                            ref={inputRef}
                            value={inputValue}
                            onChange={(e) => setInputValue(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && handleSend()}
                            placeholder={translate("Type a task or command...")}
                            radius="xl"
                            size="sm"
                            disabled={isTyping}
                            rightSectionWidth={40}
                            rightSection={
                                <ActionIcon
                                    onClick={handleSend}
                                    radius="xl"
                                    size={28}
                                    disabled={!inputValue.trim() || isTyping}
                                    style={{ backgroundColor: inputValue.trim() ? '#39758D' : '#e5e7eb', transition: 'background-color 0.15s' }}
                                >
                                    <IconSend size={14} color="white" />
                                </ActionIcon>
                            }
                        />
                    </Box>
                </Paper>
            )}

            {/* Convert to full task drawer */}
            {selectedTask && (
                <AddTaskFromQuickTaskDrawer
                    task={selectedTask}
                    taskEditDrawerOpen={convertDrawerOpen}
                    openTaskEditDrawer={() => setConvertDrawerOpen(true)}
                    closeTaskEditDrawer={handleConvertClose}
                />
            )}
        </>
    );
};

export default QuickTaskChatBot;
