import { Button, Checkbox, Divider, Group, Paper, Popover, Stack, UnstyledButton } from "@mantine/core";
import { IconChevronRight, IconFilter } from "@tabler/icons-react";
import React, { useEffect, useState } from "react";

export interface FilterState {
    platform: string[];
    status: string[];
}

interface FiltersProps {
    onApply: (filters: FilterState) => void;
    initialFilters?: FilterState;
}

const CHECKBOX_CATEGORIES = [
    { label: "Platform", key: "platform", options: ["iOS", "Android", "Web"] },
    { label: "Status", key: "status", options: ["DRAFT", "SCHEDULED", "SENDING", "SENT", "COMPLETED", "FAILED", "PENDING", "DELETED"] },
];


const Filters: React.FC<FiltersProps> = ({ onApply, initialFilters, }) => {
    const [opened, setOpened] = useState(false);
    const [activeCategory, setActiveCategory] = useState<string>("status"); // Default to Status
    const [filters, setFilters] = useState<FilterState>(initialFilters || {
        platform: [],
        status: [],
    });

    // Keep local checkbox state in sync when parent clears/updates filters externally
    useEffect(() => {
        if (initialFilters) setFilters(initialFilters);
    }, [initialFilters]);

    const handleCheckboxChange = (categoryKey: keyof FilterState, option: string, checked: boolean) => {
        setFilters((prev) => {
            const currentOptions = prev[categoryKey] as string[];
            if (checked) {
                return { ...prev, [categoryKey]: [...currentOptions, option] };
            } else {
                return { ...prev, [categoryKey]: currentOptions.filter((o) => o !== option) };
            }
        });
    };

    const handleApply = () => {
        onApply(filters);
        setOpened(false);
    };

    const handleCancel = () => {
        setFilters(initialFilters || {
            platform: [],
            status: [],
        });
        setOpened(false);
    };

    const activeCategoryData = CHECKBOX_CATEGORIES.find((c) => c.key === activeCategory);

    return (
        <Popover opened={opened} onChange={setOpened} width={300} position="bottom-start" withArrow shadow="md" closeOnClickOutside={false}>
            <Popover.Target>
                <Button
                    variant="default"
                    leftSection={<IconFilter size={16} />}
                    onClick={() => setOpened((o) => !o)}
                >
                    Filter
                </Button>
            </Popover.Target>

            <Popover.Dropdown p={0}>
                <Paper style={{ display: "flex", height: 300 }}>
                    {/* Left Column: Categories */}
                    <div style={{
                        flex: 1,
                        borderRight: "1px solid var(--mantine-color-gray-3)",
                        backgroundColor: "var(--mantine-color-gray-0)",
                        padding: "8px 0"
                    }}>
                        <Stack gap={0}>
                            {CHECKBOX_CATEGORIES.map((cat) => (
                                <UnstyledButton
                                    key={cat.key}
                                    onClick={() => setActiveCategory(cat.key)}
                                    style={{
                                        padding: "8px 12px",
                                        backgroundColor: activeCategory === cat.key ? "var(--mantine-color-dark-filled)" : "transparent",
                                        color: activeCategory === cat.key ? "var(--mantine-color-white)" : "inherit",
                                        display: "flex",
                                        justifyContent: "space-between",
                                        alignItems: "center",
                                        fontSize: 14,
                                        fontWeight: 500
                                    }}
                                >
                                    {cat.label}
                                    {activeCategory === cat.key && <IconChevronRight size={14} />}
                                </UnstyledButton>
                            ))}
                        </Stack>
                    </div>

                {/* Right Column: Options */}
                    <div style={{ flex: 1, padding: "12px", overflowY: "auto" }}>
                        <Stack gap="xs">
                            {activeCategoryData?.options.map((option) => (
                                <Checkbox
                                    key={option}
                                    label={option}
                                    checked={(filters[activeCategory as keyof FilterState] as string[]).includes(option)}
                                    onChange={(event) =>
                                        handleCheckboxChange(
                                            activeCategory as keyof FilterState,
                                            option,
                                            event.currentTarget.checked
                                        )
                                    }
                                />
                            ))}
                        </Stack>
                    </div>
                </Paper>

                <Divider />

                <Group justify="flex-end" p="xs">
                    <Button variant="subtle" size="xs" onClick={handleCancel} c="dimmed">
                        Cancel
                    </Button>
                    <Button size="xs" onClick={handleApply}>
                        Apply
                    </Button>
                </Group>
            </Popover.Dropdown>
        </Popover>
    );
};

export default Filters;
