import {
    AlertCircle,
    CalendarX,
    CheckCircle2,
    Clock,
    Eye,
    Pause,
    Play,
    UserCheck,
    UserMinus,
    XCircle,
} from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { TasksMatrixButton } from './TasksMatrixButton';

export interface TaskMatrixData {
    assigned: number;
    orphan: number;
    open_ended: number;
    waiting: number;
    in_progress: number;
    review: number;
    completed: number;
    on_hold: number;
    cancelled: number;
    overdue: number;
}

export interface TasksMatrixProps {
    taskMatrix: TaskMatrixData;
    selectedFilters: string[];
    onToggleFilter: (id: string) => void;
}

const matrixItems = [
    {
        id: 'assigned',
        label: 'Assigned',
        icon: UserCheck,
        color: 'blue',
    },
    {
        id: 'orphan',
        label: 'Orphan',
        icon: UserMinus,
        color: 'red',
    },
    {
        id: 'open_ended',
        label: 'Open Ended',
        icon: CalendarX,
        color: 'amber',
    },
    {
        id: 'waiting',
        label: 'Waiting',
        icon: Clock,
        color: 'neutral',
    },
    {
        id: 'in_progress',
        label: 'In Progress',
        icon: Play,
        color: 'blue',
    },
    {
        id: 'review',
        label: 'Review',
        icon: Eye,
        color: 'purple',
    },
    {
        id: 'completed',
        label: 'Completed',
        icon: CheckCircle2,
        color: 'green',
    },
    {
        id: 'on_hold',
        label: 'On Hold',
        icon: Pause,
        color: 'amber',
    },
    {
        id: 'cancelled',
        label: 'Cancelled',
        icon: XCircle,
        color: 'red',
    },
    {
        id: 'overdue',
        label: 'Overdue',
        icon: AlertCircle,
        color: 'red',
    },
];

export function TasksMatrix({
    taskMatrix,
    selectedFilters,
    onToggleFilter,
}: TasksMatrixProps) {
    const [isMatrixExpanded, setIsMatrixExpanded] = useState(true);

    // Indikator scroll: tampilkan fade di tepi yang masih punya konten
    // tersembunyi agar user tahu daftar filter bisa di-scroll kiri/kanan.
    const scrollRef = useRef<HTMLDivElement>(null);
    const [canScrollLeft, setCanScrollLeft] = useState(false);
    const [canScrollRight, setCanScrollRight] = useState(false);

    const updateScrollIndicators = useCallback(() => {
        const el = scrollRef.current;

        if (!el) {
            return;
        }

        const { scrollLeft, scrollWidth, clientWidth } = el;

        setCanScrollLeft(scrollLeft > 1);
        setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
    }, []);

    useEffect(() => {
        updateScrollIndicators();

        const el = scrollRef.current;

        if (!el) {
            return;
        }

        el.addEventListener('scroll', updateScrollIndicators, {
            passive: true,
        });
        window.addEventListener('resize', updateScrollIndicators);

        return () => {
            el.removeEventListener('scroll', updateScrollIndicators);
            window.removeEventListener('resize', updateScrollIndicators);
        };
    }, [updateScrollIndicators, isMatrixExpanded]);

    return (
        <div
            className={`fixed right-4 bottom-16 z-30 transform transition-all duration-500 ease-in-out ${
                isMatrixExpanded
                    ? 'translate-x-0'
                    : 'translate-x-[calc(100%-3.5rem)]'
            }`}
        >
            <div className="flex flex-row gap-2 rounded-xl border bg-background/95 p-4 pl-2 shadow-xl backdrop-blur-md md:gap-4">
                <div
                    onClick={() => setIsMatrixExpanded(!isMatrixExpanded)}
                    className="grid w-10 flex-none cursor-pointer place-items-center border-r"
                >
                    <p className="rotate-180 text-center text-[10px] font-extrabold tracking-widest whitespace-nowrap text-muted-foreground uppercase [writing-mode:vertical-lr]">
                        Matrix
                    </p>
                </div>
                <div
                    className={`min-w-0 transition-all duration-500 ${isMatrixExpanded ? 'opacity-100' : 'pointer-events-none opacity-0'}`}
                >
                    {/*
                     * Selalu satu baris yang bisa di-scroll horizontal. Lebar
                     * area dibatasi viewport (max-w), dan fade gradient di tepi
                     * kiri/kanan muncul saat masih ada filter tersembunyi ke
                     * arah tersebut sebagai petunjuk bahwa daftar bisa di-scroll.
                     */}
                    <div className="relative">
                        <div
                            ref={scrollRef}
                            className="custom-scrollbar flex max-w-[calc(100vw-6rem)] flex-row gap-2 overflow-x-auto px-0.5 py-1 md:max-w-none md:gap-4"
                        >
                            {matrixItems.map((item) => {
                                const count =
                                    taskMatrix[
                                        item.id as keyof TaskMatrixData
                                    ] || 0;
                                const isActive = selectedFilters.includes(
                                    item.id,
                                );

                                return (
                                    <div
                                        key={item.id}
                                        className="w-28 shrink-0"
                                    >
                                        <TasksMatrixButton
                                            id={item.id}
                                            label={item.label}
                                            count={count}
                                            icon={item.icon}
                                            color={item.color}
                                            isActive={isActive}
                                            onClick={() =>
                                                onToggleFilter(item.id)
                                            }
                                        />
                                    </div>
                                );
                            })}
                        </div>

                        {/* Fade kiri */}
                        <div
                            className={`pointer-events-none absolute inset-y-0 left-0 w-8 bg-linear-to-r from-background to-transparent transition-opacity duration-200 ${
                                canScrollLeft ? 'opacity-100' : 'opacity-0'
                            }`}
                        />

                        {/* Fade kanan */}
                        <div
                            className={`pointer-events-none absolute inset-y-0 right-0 w-8 bg-linear-to-l from-background to-transparent transition-opacity duration-200 ${
                                canScrollRight ? 'opacity-100' : 'opacity-0'
                            }`}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
}
