import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { AriaLiveRegion, createComponent, useUniqueId } from '@workday/canvas-kit-react/common';
import { Flex } from '@workday/canvas-kit-react/layout';
import { FormField } from '@workday/canvas-kit-react/form-field';
import { InputGroup, TextInput } from '@workday/canvas-kit-react/text-input';
import { Popup, usePopupModel, useCloseOnOutsideClick, useCloseOnEscape, useInitialFocus, useReturnFocus, useFocusRedirect, } from '@workday/canvas-kit-react/popup';
import { PrimaryButton, TertiaryButton } from '@workday/canvas-kit-react/button';
import { Table } from '@workday/canvas-kit-react/table';
import { Text } from '@workday/canvas-kit-react/text';
import { SystemIcon } from '@workday/canvas-kit-react/icon';
import { Tooltip } from '@workday/canvas-kit-react/tooltip';
import { createStyles } from '@workday/canvas-kit-styling';
import { system } from '@workday/canvas-tokens-web';
import { filterIcon, searchIcon } from '@workday/canvas-system-icons-web';
const countryData = [
    { country: 'Australia', capital: 'Canberra', population: 25690000 },
    { country: 'Bahamas', capital: 'Nassau', population: 407906 },
    { country: 'Canada', capital: 'Ottawa', population: 38250000 },
    { country: 'Fiji', capital: 'Suva', population: 924610 },
    { country: 'Ghana', capital: 'Accra', population: 32830000 },
    { country: 'Hong Kong', capital: 'City of Victoria', population: 7413000 },
    { country: 'India', capital: 'New Delhi', population: 1408000000 },
    { country: 'Ireland', capital: 'Dublin', population: 5033000 },
    { country: 'Jamaica', capital: 'Kingston', population: 2828000 },
    { country: 'Kenya', capital: 'Nairobi', population: 53010000 },
    { country: 'Micronesia', capital: 'Palikir', population: 113131 },
    { country: 'New Zealand', capital: 'Wellington', population: 5123000 },
    { country: 'Philippines', capital: 'Manila', population: 113900000 },
    { country: 'Puerto Rico', capital: 'San Juan', population: 3264000 },
    { country: 'Samoa', capital: 'Apia', population: 218764 },
    { country: 'Singapore', capital: 'Singapore', population: 5454000 },
    { country: 'Tanzania', capital: 'Dodoma', population: 63590000 },
    { country: 'United Kingdom', capital: 'London', population: 67330000 },
    { country: 'United States', capital: 'Washington, D.C.', population: 331900000 },
    { country: 'Zimbabwe', capital: 'Harare', population: 15990000 },
];
const textStyles = createStyles({
    paddingInlineStart: system.space.x3,
});
const FilterableColumnHeader = createComponent('th')({
    displayName: 'FilterableColumnHeader',
    Component: ({ label, onFilter }, ref) => {
        const [inputVal, setInputVal] = React.useState('');
        const targetId = useUniqueId();
        const popupId = useUniqueId();
        const initialFocusRef = React.useRef(null);
        const filterPopupModel = usePopupModel({
            initialFocusRef,
        });
        useCloseOnOutsideClick(filterPopupModel);
        useCloseOnEscape(filterPopupModel);
        useInitialFocus(filterPopupModel);
        useFocusRedirect(filterPopupModel);
        useReturnFocus(filterPopupModel);
        function handleChange(e) {
            const newVal = e.target.value;
            setInputVal(newVal);
            onFilter({ filterText: newVal, column: label.toLowerCase() });
        }
        return (_jsx(Table.Header, { scope: "col", "aria-owns": targetId + ' ' + popupId, children: _jsxs(Popup, { model: filterPopupModel, children: [_jsx(Tooltip, { title: `Filter${inputVal !== '' ? `ed: "${inputVal}"` : ''}`, type: "description", children: _jsx(Popup.Target, { as: TertiaryButton, id: targetId, icon: inputVal === '' ? searchIcon : filterIcon, iconPosition: "end", children: label }) }), _jsx(Popup.Popper, { children: _jsxs(Popup.Card, { id: popupId, children: [_jsx(Popup.Heading, { children: "Filter" }), _jsx(Popup.Body, { children: _jsxs(FormField, { children: [_jsx(FormField.Label, { children: label }), _jsxs(FormField.Input, { as: InputGroup, children: [_jsx(InputGroup.InnerStart, { children: _jsx(SystemIcon, { icon: searchIcon }) }), _jsx(InputGroup.Input, { as: TextInput, type: "search", ref: initialFocusRef, onChange: handleChange, value: inputVal })] })] }) }), _jsx(Flex, { children: _jsx(Popup.CloseButton, { as: PrimaryButton, children: "Done" }) })] }) })] }) }));
    },
});
function filterTableData(data, filters) {
    return data.filter(item => {
        for (const key in filters) {
            if (filters.hasOwnProperty(key) && filters[key]) {
                const filterText = filters[key].toLowerCase();
                const itemValue = String(item[key]).toLowerCase();
                if (!itemValue.includes(filterText)) {
                    return false;
                }
            }
        }
        return true;
    });
}
export const FilterableColumnHeaders = () => {
    const [filteredData, setFilteredData] = React.useState(countryData);
    const [colFilters, setColFilters] = React.useState({
        country: '',
        capital: '',
        population: '',
    });
    React.useEffect(() => {
        setFilteredData(filterTableData(countryData, colFilters));
    }, [colFilters]);
    let typingDelay;
    function handleColFilters({ filterText, column }) {
        clearTimeout(typingDelay);
        typingDelay = setTimeout(() => {
            setColFilters(prev => {
                const newState = { ...prev, [column]: filterText };
                return newState;
            });
        }, 400);
    }
    return (_jsxs(Table, { maxHeight: "40rem", children: [_jsxs(Table.Caption, { children: ["Population Listed by Country (2021)", _jsxs(AriaLiveRegion, { cs: textStyles, children: [filteredData.length, " of ", countryData.length, " items"] })] }), _jsx(Table.Head, { children: _jsxs(Table.Row, { children: [_jsx(FilterableColumnHeader, { label: "Country", onFilter: handleColFilters }), _jsx(FilterableColumnHeader, { label: "Capital", onFilter: handleColFilters }), _jsx(FilterableColumnHeader, { label: "Population", onFilter: handleColFilters })] }) }), _jsx(Table.Body, { children: filteredData.map(item => {
                    return (_jsxs(Table.Row, { children: [_jsx(Table.Header, { scope: "row", children: _jsx(Text, { cs: textStyles, children: item.country }) }), _jsx(Table.Cell, { children: _jsx(Text, { cs: textStyles, children: item.capital }) }), _jsx(Table.Cell, { children: _jsx(Text, { cs: textStyles, children: item.population.toLocaleString() }) })] }, item.country));
                }) })] }));
};
