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

export interface LogFilterState {
    log_category: string[];
    admin_email: string[];
    method: string[];
    status_group: string[];
}

interface LogFiltersProps {
    onApply: (filters: LogFilterState) => void;
    initialFilters?: LogFilterState;
    adminOptions: string[];
}

const CATEGORIES = (adminOptions: string[]) => [
    { label: "Log Category", key: "log_category", options: ["API", "UI", "SYSTEM"] },
    { label: "Admin User", key: "admin_email", options: adminOptions },
    { label: "Method", key: "method", options: ["GET", "POST", "PUT", "DELETE", "PATCH"] },
    { label: "Status", key: "status_group", options: ["2xx Success", "4xx Client Error", "5xx Server Error"] },
];

const LogFilters: React.FC<LogFiltersProps> = ({ onApply, initialFilters, adminOptions }) => {
    const [opened, setOpened] = useState(false);
    const [activeCategory, setActiveCategory] = useState<string>("log_category");
    const [filters, setFilters] = useState<LogFilterState>(initialFilters || {
        log_category: [],
        admin_email: [],
        method: [],
        status_group: [],
    });

    useEffect(() => {
        if (initialFilters) {
            setFilters(initialFilters);
        }
    }, [initialFilters]);

    const handleCheckboxChange = (categoryKey: keyof LogFilterState, option: string, checked: boolean) => {
        setFilters((prev) => {
            const currentOptions = prev[categoryKey] || [];
            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 || {
            log_category: [],
            admin_email: [],
            method: [],
            status_group: [],
        });
        setOpened(false);
    };

    const categories = CATEGORIES(adminOptions);
    const activeCategoryData = categories.find((c) => c.key === activeCategory);

    const activeFiltersCount = Object.values(filters).flat().length;

    return (
        <Popover
            opened={opened}
            onChange={setOpened}
            width={450}
            position="bottom-start"
            withArrow
            shadow="md"
            offset={12}
        >
            <Popover.Target>
                <Button
                    variant="default"
                    leftSection={<IconFilter size={16} />}
                    onClick={() => setOpened((o) => !o)}
                    size="sm"
                    color={activeFiltersCount > 0 ? "blue" : "gray"}
                >
                    Filter {activeFiltersCount > 0 && `(${activeFiltersCount})`}
                </Button>
            </Popover.Target>

            <Popover.Dropdown p={0} style={{ borderRadius: '8px', overflow: 'hidden' }}>
                <Flex style={{ height: 320 }}>
                    {/* Left Column: Categories */}
                    <div style={{
                        width: 180,
                        borderRight: "1px solid var(--mantine-color-gray-2)",
                        backgroundColor: "var(--mantine-color-gray-0)",
                        padding: "8px 0"
                    }}>
                        <Stack gap={0}>
                            {categories.map((cat) => (
                                <UnstyledButton
                                    key={cat.key}
                                    onClick={() => setActiveCategory(cat.key)}
                                    style={{
                                        padding: "10px 16px",
                                        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: 13,
                                        fontWeight: 600
                                    }}
                                >
                                    {cat.label}
                                    {activeCategory === cat.key && <IconChevronRight size={14} />}
                                </UnstyledButton>
                            ))}
                        </Stack>
                    </div>

                    {/* Right Column: Options */}
                    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                        <ScrollArea p="md" style={{ flex: 1 }}>
                            <Stack gap="xs">
                                {activeCategoryData?.options.map((option) => (
                                    <Checkbox
                                        key={option}
                                        label={option}
                                        checked={(filters[activeCategory as keyof LogFilterState] || []).includes(option)}
                                        onChange={(event) => handleCheckboxChange(activeCategory as keyof LogFilterState, option, event.currentTarget.checked)}
                                        size="xs"
                                        styles={{ label: { fontSize: 13 } }}
                                    />
                                ))}
                            </Stack>
                        </ScrollArea>
                    </div>
                </Flex>

                <Divider />

                <Group justify="flex-end" p="md" gap="xs" bg="var(--mantine-color-gray-0)">
                    <Button variant="subtle" size="sm" onClick={handleCancel} color="gray">
                        Cancel
                    </Button>
                    <Button size="sm" onClick={handleApply} bg="var(--mantine-color-dark-filled)">
                        Apply
                    </Button>
                </Group>
            </Popover.Dropdown>
        </Popover>
    );
};

export default LogFilters;
