import React, { useEffect, useMemo, useState } from 'react'
import { __, sprintf } from '@wordpress/i18n'

export interface LanguageDropdownComponentProps {
    languages: Record<string, { name: string; native: string }>
    isOpen: boolean
    appliedCodes: string[]
    onToggle: () => void
    onApply: (codes: string[]) => void
}

const SearchGlyph = () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
        <path
            d="M10.1234 5.77502C9.58344 5.77502 9.14844 6.21002 9.14844 6.75002C9.14844 7.29002 9.58344 7.72502 10.1234 7.72502C11.4434 7.72502 12.5234 8.80502 12.5234 10.125C12.5234 10.665 12.9584 11.1 13.4984 11.1C14.0384 11.1 14.4734 10.665 14.4734 10.125C14.4734 7.72502 12.5234 5.77502 10.1234 5.77502ZM20.5034 16.995L16.7534 13.245C17.2034 12.3 17.4734 11.235 17.4734 10.125C17.4734 6.07502 14.1734 2.77502 10.1234 2.77502C6.07344 2.77502 2.77344 6.07502 2.77344 10.125C2.77344 14.175 6.07344 17.475 10.1234 17.475C11.2484 17.475 12.2984 17.205 13.2434 16.755L16.9934 20.505C17.4584 20.97 18.0884 21.225 18.7484 21.225C19.4084 21.225 20.0234 20.97 20.5034 20.505C20.9684 20.04 21.2234 19.41 21.2234 18.75C21.2234 18.09 20.9684 17.475 20.5034 16.995ZM10.1234 15.525C7.13844 15.525 4.72344 13.11 4.72344 10.125C4.72344 7.14002 7.13844 4.72502 10.1234 4.72502C13.1084 4.72502 15.5234 7.14002 15.5234 10.125C15.5234 13.11 13.1084 15.525 10.1234 15.525Z"
            fill="#A8A8A8"
        />
    </svg>
)

const LanguageDropdownComponent = ({ languages, isOpen, appliedCodes, onToggle, onApply }: LanguageDropdownComponentProps) => {
    const [filterText, setFilterText] = useState('')
    const [pending, setPending] = useState<string[]>(appliedCodes)

    const allCodes = useMemo(() => Object.keys(languages), [languages])

    const filteredEntries = useMemo(() => {
        const q = filterText.toLowerCase().trim()
        return Object.entries(languages).filter(([, data]) => {
            if (!q) {
                return true
            }
            return data.name.toLowerCase().includes(q) || data.native.toLowerCase().includes(q)
        })
    }, [languages, filterText])

    const filteredCodes = useMemo(() => filteredEntries.map(([code]) => code), [filteredEntries])

    const prevOpen = React.useRef(false)
    useEffect(() => {
        if (isOpen && !prevOpen.current) {
            setPending([...appliedCodes])
            setFilterText('')
        }
        prevOpen.current = isOpen
    }, [isOpen, appliedCodes])

    const toggleCode = (code: string) => {
        setPending(pending.includes(code) ? pending.filter((c) => c !== code) : [...pending, code])
    }

    const toggleSelectAll = () => {
        if (filterText.trim() === '') {
            setPending(pending.length === allCodes.length ? [] : [...allCodes])
            return
        }
        const allFilteredSelected = filteredCodes.length > 0 && filteredCodes.every((c) => pending.includes(c))
        if (allFilteredSelected) {
            setPending(pending.filter((c) => !filteredCodes.includes(c)))
        } else {
            setPending([...new Set([...pending, ...filteredCodes])])
        }
    }

    const selectedCount = pending.length
    const countLabel =
        selectedCount === 0
            ? __('No languages selected', 'textdomain')
            : sprintf(
                  /* translators: %d: number of languages */
                  __('%d Languages Selected', 'textdomain'),
                  selectedCount
              )

    const selectAllChecked =
        filterText.trim() === ''
            ? pending.length === allCodes.length && allCodes.length > 0
            : filteredCodes.length > 0 && filteredCodes.every((c) => pending.includes(c))

    return (
        <>
            <button
                className={`btn btn-icon drop-down hidden-on-focus language-btn${isOpen ? ' is-active' : ''}`}
                id="languageBtn"
                title={__('Language', 'textdomain')}
                type="button"
                onClick={onToggle}
                aria-expanded={isOpen}
            >
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
                    <path
                        d="M13.73 10.21C14 9.51998 14.15 8.77998 14.15 7.99998C14.15 7.21998 14 6.47998 13.73 5.78998C13.73 5.76998 13.72 5.73998 13.71 5.71998C12.8 3.44998 10.59 1.84998 8.00001 1.84998C5.41001 1.84998 3.20001 3.45998 2.29001 5.71998C2.28001 5.73998 2.27001 5.75998 2.27001 5.78998C2.00001 6.47998 1.85001 7.21998 1.85001 7.99998C1.85001 8.77998 2.00001 9.51998 2.27001 10.21C2.27001 10.23 2.28001 10.26 2.29001 10.28C3.20001 12.55 5.41001 14.15 8.00001 14.15C10.59 14.15 12.8 12.54 13.71 10.28C13.72 10.26 13.73 10.24 13.73 10.21ZM8.00001 12.85C7.74001 12.85 7.23001 12.08 6.92001 10.65H9.08001C8.77001 12.08 8.26001 12.85 8.00001 12.85ZM6.72001 9.34998C6.68001 8.92998 6.65001 8.48998 6.65001 7.99998C6.65001 7.50998 6.68001 7.06998 6.72001 6.64998H9.28001C9.32001 7.06998 9.35001 7.50998 9.35001 7.99998C9.35001 8.48998 9.32001 8.92998 9.28001 9.34998H6.72001ZM3.15001 7.99998C3.15001 7.52998 3.24001 7.07998 3.36001 6.64998H5.41001C5.37001 7.08998 5.35001 7.54998 5.35001 7.99998C5.35001 8.44998 5.37001 8.90998 5.41001 9.34998H3.36001C3.23001 8.91998 3.15001 8.46998 3.15001 7.99998ZM8.00001 3.14998C8.26001 3.14998 8.77001 3.91998 9.08001 5.34998H6.92001C7.23001 3.91998 7.74001 3.14998 8.00001 3.14998ZM10.59 6.64998H12.64C12.77 7.07998 12.85 7.52998 12.85 7.99998C12.85 8.46998 12.76 8.91998 12.64 9.34998H10.59C10.63 8.90998 10.65 8.44998 10.65 7.99998C10.65 7.54998 10.63 7.08998 10.59 6.64998ZM12.05 5.34998H10.41C10.28 4.67998 10.1 4.05998 9.87001 3.52998C10.77 3.90998 11.52 4.54998 12.05 5.34998ZM6.13001 3.52998C5.90001 4.05998 5.72001 4.67998 5.59001 5.34998H3.95001C4.48001 4.54998 5.23001 3.89998 6.13001 3.52998ZM3.95001 10.65H5.59001C5.72001 11.32 5.90001 11.94 6.13001 12.47C5.23001 12.09 4.48001 11.45 3.95001 10.65ZM9.87001 12.47C10.1 11.94 10.28 11.32 10.41 10.65H12.05C11.52 11.45 10.77 12.1 9.87001 12.47Z"
                        fill="#606060"
                    />
                </svg>
            </button>

            {isOpen && (
                <div className="language-panel drop-down-wrapper language-wrapper" id="languagesWrapper">
                    <div className="dropdown-panel__stack">
                        <div className="dropdown-panel__intro">
                            <h6>{__('Languages', 'textdomain')}</h6>
                            <p>{__('Choose the languages you would like to search', 'textdomain')}</p>
                            <p className="dropdown-panel__selection-summary">{countLabel}</p>
                        </div>
                        <div className="dropdown-panel__list-card">
                            <div className="dropdown-panel__filter-row">
                                <input
                                    type="text"
                                    className="dropdown-panel__filter-input"
                                    placeholder={__('Find language', 'textdomain')}
                                    value={filterText}
                                    onChange={(e) => setFilterText(e.target.value)}
                                    aria-label={__('Find language', 'textdomain')}
                                />
                                <span className="dropdown-panel__filter-icon" aria-hidden>
                                    <SearchGlyph />
                                </span>
                            </div>
                            <div className="dropdown-panel__divider" />
                            <div className="dropdown-panel__scroll">
                                <label className="dropdown-panel__row">
                                    <input
                                        type="checkbox"
                                        className="dropdown-panel__checkbox"
                                        checked={selectAllChecked}
                                        onChange={toggleSelectAll}
                                    />
                                    <span className="dropdown-panel__row-label">{__('Select All', 'textdomain')}</span>
                                </label>
                                {filteredEntries.map(([code, data]) => (
                                    <label key={code} className="dropdown-panel__row dropdown-panel__row--indented">
                                        <input
                                            type="checkbox"
                                            className="dropdown-panel__checkbox"
                                            value={code}
                                            checked={pending.includes(code)}
                                            onChange={() => toggleCode(code)}
                                        />
                                        <span className="dropdown-panel__row-label">{data.name}</span>
                                    </label>
                                ))}
                            </div>
                        </div>
                        <button type="button" className="dropdown-panel__apply" onClick={() => onApply(pending)}>
                            {__('Apply', 'textdomain')}
                        </button>
                    </div>
                </div>
            )}
        </>
    )
}

export default LanguageDropdownComponent
