import React, {useState, useEffect} from "react";
import {Row, Col, InputGroup} from "react-bootstrap";
import Tippy from "@tippyjs/react";

declare global
{
    interface Window
    {
        $: any;  // or we can be more specific and use 'JQuery' type if available
    }
}

interface TableFiltersProps
{
    handleSearch: (e: React.KeyboardEvent<HTMLInputElement> | null) => void;
    handleReset: () => void;
    handleDateRangeFilter: () => void;
    handleShowMyRecords: (value: number) => void;
    searchTerm: string;
    setSearchTerm: (value: string) => void;
    setStart: (value: string) => void;
    setEnd: (value: string) => void;
    start: string;
    end: string,
    isShowOnlyMyRecords: number
}

const TableFilters = ({
    handleSearch,
    handleReset,
    handleDateRangeFilter,
    handleShowMyRecords,
    searchTerm,
    setSearchTerm,
    setStart,
    setEnd,
    start,
    end,
    isShowOnlyMyRecords
}: TableFiltersProps) => {
    const [visible, setVisible] = useState(false);
    const [errorStartDate, setErrorStartDate] = useState('');
    const [errorEndDate, setErrorEndDate] = useState('');

    // Initialize DatePicker and set up event listeners
    useEffect(() => {
        if (window && window?.$) {
            // Initialize DatePicker for the start-date input
            window.$(".start-date").datepicker({
                dateFormat: "dd-M-yy", // You can adjust the format
                changeMonth: true,
                changeYear: true,
                onSelect: function (date: string) {
                    setStart(date); // Set the selected start date in React state
                },
            });

            // Initialize DatePicker for the end-date input
            window.$(".end-date").datepicker({
                dateFormat: "dd-M-yy", // You can adjust the format
                changeMonth: true,
                changeYear: true,
                onSelect: function (date: string) {
                    setEnd(date); // Set the selected end date in React state
                },
            });
        }

        // Cleanup DatePicker on unmount
        return () => {
            if (window && window?.$) {
                window.$(".start-date").datepicker("destroy");
                window.$(".end-date").datepicker("destroy");
            }
        };
    }, [visible]); // Dependency on visibility to initialize when the tooltip is shown

    const validateDateRangeFilter = () => {
        setErrorStartDate('');
        setErrorEndDate('')
        if(!start) {
            setErrorStartDate('\'From\' date is required');
        }

        if(!end) {
            setErrorEndDate('\'To\' date is required');
        }

        if(start && end) {
            handleDateRangeFilter();
            setVisible(false);
        }
    }

    return (
        <div className="filters-wrapper">
            <Row>
                <Col className="mt-2 mb-2" xs={12} sm={3}>
                    <label className="d-flex align-items-center ms-1">
                        <input type="checkbox" className="ops_form_element_checkbox"
                               value={isShowOnlyMyRecords}
                               checked={isShowOnlyMyRecords == 1}
                               onChange={(e) => handleShowMyRecords(parseInt(e.target.value))}/>
                        Show only my records
                    </label>
                </Col>
                <Col className="search d-flex justify-content-around justify-content-sm-end flex-wrap flex-sm-nowrap" xs={12} sm={9}>
                    <InputGroup className="input-group-custom justify-content-sm-end flex-nowrap mt-2 mb-2">
                        <input
                            type="text"
                            className="ops_page_search"
                            placeholder="Type your search here..."
                            aria-label="Search"
                            onChange={(e) => setSearchTerm(e.target.value)}
                            onKeyUp={(e) => handleSearch(e)}
                            value={searchTerm}
                            maxLength={25}
                        />
                        <button
                            type="button"
                            className="action export_csv btn-search"
                            onClick={() => handleSearch(null)}
                        >
                            🔎︎
                        </button>
                    </InputGroup>

                    <Tippy
                        visible={visible}
                        content={
                            <div className="tippy-wrapper">
                                <p className="tippy-header flex-nowrap">
                                    Set a date range to filter by Start, End and Created On
                                </p>
                                <div className="tippy-body">
                                    <div className="form-container">
                                        <div className="mb-2">
                                            <Col className="mb-2" sm={12}>
                                                <label className="form-label">From</label>
                                                <input type="text" className="form-control start-date"
                                                       placeholder="dd-mm-yyyy"
                                                       onChange={(e) => setStart(e.target.value)}
                                                       value={start}/>
                                                {errorStartDate && <span className="text-danger">{errorStartDate}</span>}
                                            </Col>
                                            <Col sm={12}>
                                                <label className="form-label">To</label>
                                                <input type="text" className="form-control end-date"
                                                       placeholder="dd-mm-yyyy"
                                                       onChange={(e) => setEnd(e.target.value)}
                                                       value={end}/>
                                                {errorEndDate && <span className="text-danger">{errorEndDate}</span>}
                                            </Col>
                                        </div>
                                        <div className="d-flex justify-content-center">
                                            <button className="btn btn-sm btn-outline-success"
                                                    onClick={() => setVisible(false)}>
                                                Cancel
                                            </button>
                                            <button
                                                className="btn btn-sm btn-outline-success ms-2"
                                                onClick={() => validateDateRangeFilter()}
                                            >
                                                Apply
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        }
                        interactive={true}
                        arrow
                        allowHTML={true}
                    >
                        <button
                            className="action ms-2 btn-dateRange mt-2 mb-2"
                            type="button"
                            onClick={() => setVisible(!visible)}
                        >
                            <i className="ui-icon-calendar"></i> Select Date
                        </button>
                    </Tippy>

                    <button
                        className="action ms-2 btn-reset mt-2 mb-2"
                        type="button"
                        onKeyUp={(e) => {
                            e.key === "Enter" && e.preventDefault();
                        }}
                        onClick={handleReset}
                    >
                        Reset
                    </button>
                </Col>
            </Row>
        </div>
    );
};

export default TableFilters;