import React from 'react';
import { Avatar, Text, Group, Stack, Badge, Box } from '@mantine/core';
import { IconCalendar, IconUser, IconFlag, IconActivity, IconLink } from '@tabler/icons-react';
import useTwColorByName from "../../../../ui/useTwColorByName";
import acronym from "../../../../ui/acronym";
import { useSelector } from 'react-redux';

export default function CustomTooltip({ task }) {
    if (!task) return null;

    const bgColor = useTwColorByName();
    const { ganttTasks } = useSelector((state) => state.settings.task);
    const start = new Date(task.start || task.start_date);
    const end = new Date(task.end || task.end_date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const durationDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24)); // difference in days

    // Format dates as DD-MMM-YYYY
    const formatDate = (date) =>
        date.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
        });

    const isOverdue = end < today && task.status !== 'COMPLETED';

    return (
        <Stack
            gap={4}
            p="sm"
            bg={'white'}
            style={{
                minWidth: 220,
                border: '1px solid #e9ecef',
                borderRadius: 8,
                boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)'
            }}
        >
            {/* Task title */}
            <Text fw={600} size="sm" lineClamp={2} mb={2}>
                {task.fullName || task.name}
            </Text>

            <Group gap="xs" mb={4}>
                {(task.displayStatus || task.status) && (
                    <Badge
                        size="xs"
                        variant="light"
                        color={task.displayStatusColor || (task.status === 'COMPLETED' ? 'green' : (isOverdue ? 'red' : 'blue'))}
                        style={{ color: task.displayStatusColor }}
                    >
                        {task.displayStatus || task.status}
                    </Badge>
                )}
                {task.priority && task.priority.name && (
                    <Badge
                        size="xs"
                        variant="outline"
                        color={task.priority.color_code || 'gray'}
                        leftSection={<IconFlag size={10} />}
                    >
                        {task.priority.name}
                    </Badge>
                )}
            </Group>

            <Divider my={2} color="#f1f3f5" />

            {/* Assigned user */}
            <Group gap="xs" align="center">
                <IconUser size={14} style={{ opacity: 0.5 }} />
                {task.assigned_to ? (
                    <Group gap={6}>
                        <Avatar
                            color={`${bgColor(task.assigned_to.name)["font-color"]}`}
                            bg={`${bgColor(task.assigned_to.name)["bg-color"]}`}
                            size={18}
                            radius={18}
                            src={task.assigned_to.avatar || null}
                        >
                            {!task.assigned_to.avatar && (
                                <Text style={{ lineHeight: "10px", fontSize: '9px' }}>
                                    {acronym(task.assigned_to.name)}
                                </Text>
                            )}
                        </Avatar>
                        <Text size="xs" c="dimmed">{task.assigned_to.name}</Text>
                    </Group>
                ) : (
                    <Text size="xs" c="dimmed">Unassigned</Text>
                )}
            </Group>

            {/* Duration */}
            <Group gap="xs" mt={2} align="center">
                <IconCalendar size={14} style={{ opacity: 0.5 }} />
                <Text size="xs" c={isOverdue ? 'red' : 'dimmed'}>
                    {formatDate(start)} → {formatDate(end)}
                </Text>
            </Group>

            <Group gap="xs" mt={0} align="center">
                <IconActivity size={14} style={{ opacity: 0.5 }} />
                <Text size="xs" c="dimmed">
                    Duration: {durationDays} {durationDays > 1 ? 'days' : 'day'}
                </Text>
            </Group>

            {/* Parent Tasks (Dependencies) */}
            {task.dependencies && task.dependencies.length > 0 && (() => {
                const parentNames = task.dependencies
                    .map(depId => ganttTasks && ganttTasks.find(t => String(t.id) === String(depId)))
                    .filter(Boolean)
                    .map(t => t.name);
                if (!parentNames.length) return null;
                return (
                    <>
                        <Divider my={2} color="#f1f3f5" />
                        <Group gap="xs" align="flex-start">
                            <IconLink size={14} style={{ opacity: 0.5, marginTop: 2 }} />
                            <Box>
                                <Text size="xs" c="dimmed" mb={2}>Parent Tasks:</Text>
                                {parentNames.map((name, i) => (
                                    <Badge key={i} size="xs" variant="light" color="orange" mb={2} mr={2}>
                                        {name.length > 25 ? name.slice(0, 25) + '…' : name}
                                    </Badge>
                                ))}
                            </Box>
                        </Group>
                    </>
                );
            })()}
        </Stack>
    );
}

const Divider = ({ my, color }) => (
    <div style={{ marginTop: my * 4, marginBottom: my * 4, borderTop: `1px solid ${color}` }} />
);
