import {Tooltip} from "react-tooltip";
import ReactSelect from "react-select";
import {DateRangePicker} from "react-date-range";
import ProofingContext from "../../contexts/ProofingContext";
import "react-date-range/dist/styles.css"; // Main style file
import "react-date-range/dist/theme/default.css";
import Pagination from "../../includes/Pagination/Pagination";
import ProModal from "../../includes/ProModal";
import {loadAvatar, md5} from "../../includes/functions";

const {useContext, useState, useEffect} = React;

const {Button, SelectControl, CheckboxControl,} = wp.components;

export default function List() {

    const {
        selections,
        filterModule,
        setFilterModule,
        setSubmission,
        deleteSubmissions,
        exportSubmissions,
    } = useContext(ProofingContext);

    const moduleOptions = igd.shortcodes?.filter(item => ['review', 'gallery'].includes(item.type)).map(item => {
        return {
            value: item.id,
            label: item.title,
            image: `${igd.pluginUrl}/assets/images/shortcode-builder/types/${item.type || 'shortcodes'}.svg`,
        }
    });

    const userOptions = Array.from(
        new Map(
            selections.map(({user}) => [
                user.email,
                {
                    value: user.email,
                    label: user.name
                        ? `${user.name} (${user.email})`
                        : user.email,
                }
            ])
        ).values()
    );


    const [page, setPage] = useState(1);
    const [perPage, setPerPage] = useState(localStorage.getItem('igd_submissions_list_per_page') || 20);

    const [filteredSubmissions, setFilteredSubmissions] = useState([]);
    const [filteredTotal, setFilteredTotal] = useState(0);
    const [filterUser, setFilterUser] = useState(null);
    const [selectedSubmissions, setSelectedSubmissions] = useState([]);
    const [lastCheckedIndex, setLastCheckedIndex] = useState(null);

    const [startDate, setStartDate] = useState(null);
    const [endDate, setEndDate] = useState(null);

    const [dateRange, setDateRange] = useState([
        {
            startDate: null,
            endDate: null,
            key: "selection",
        },
    ]);

    const handleDateChange = (ranges) => {
        const {startDate, endDate} = ranges.selection;

        setDateRange([ranges.selection]);

        if (startDate && endDate) {
            // Normalize start of day
            const start = new Date(startDate);
            start.setHours(0, 0, 0, 0);

            // Normalize end of day
            const end = new Date(endDate);
            end.setHours(23, 59, 59, 999);

            setStartDate(start);
            setEndDate(end);
        }
    };

    useEffect(() => {

        let data = [...selections];

        // Filter by module
        if (filterModule) {
            data = data.filter(item => item?.module?.id === filterModule);
        }

        // Filter by user
        if (filterUser) {
            data = data.filter(item => item?.user?.email === filterUser);
        }

        // Filter by date range
        if (startDate && endDate) {
            data = data.filter(item => {
                const itemDate = new Date(item.created_at);
                return itemDate >= startDate && itemDate <= endDate;
            });
        }

        const totalItems = data.length;

        // 3. Pagination
        const start = (page - 1) * perPage;
        const end = start + perPage;
        const paginated = data.slice(start, end);

        setFilteredSubmissions(paginated);
        setFilteredTotal(totalItems);
        setSelectedSubmissions([]);

    }, [selections, page, perPage, filterModule, filterUser, startDate, endDate]);

    // Handle filter tooltip
    const [isTooltipOpen, setTooltipOpen] = useState(false);

    return (
        <div className="igd-proof-selections-list">

            <div className="filters-wrap">

                <div className="list-title-wrap">
                    <h3 className="list-title">
                        {wp.i18n.__('All Submissions', 'integrate-google-drive')}

                        <span
                            className="list-count">({filteredTotal === 0 ? 0 : (page - 1) * perPage + 1}–{Math.min(page * perPage, filteredTotal)} / {filteredTotal})</span>
                    </h3>

                    {/*----- Bulk Actions -----*/}
                    {!!selectedSubmissions.length && (
                        <div className="selection-actions-wrap">
                            <div className="selection-left">
                                <span className="selection-badge">
                                    {selectedSubmissions.length}
                                </span>

                                <span className="selection-text">
                                    {wp.i18n.__('selected', 'integrate-google-drive')}
                                </span>

                                <Button
                                    className="igd-clear-btn"
                                    onClick={() => setSelectedSubmissions([])}
                                    text={wp.i18n.__('Clear', 'integrate-google-drive')}
                                    label={wp.i18n.__('Clear Selection', 'integrate-google-drive')}
                                />
                            </div>

                            <div className="selection-right">
                                <Button
                                    className="igd-btn btn-info"
                                    onClick={() => exportSubmissions(selectedSubmissions)}
                                    text={wp.i18n.__('Export', 'integrate-google-drive')}
                                    label={wp.i18n.__('Export Selected as CSV', 'integrate-google-drive')}
                                    icon={`download`}
                                />

                                <Button
                                    className="igd-btn btn-danger"
                                    onClick={() => deleteSubmissions(selectedSubmissions)}
                                    text={wp.i18n.__('Delete', 'integrate-google-drive')}
                                    label={wp.i18n.__('Delete Selected', 'integrate-google-drive')}
                                    icon={`trash`}
                                />
                            </div>
                        </div>
                    )}

                </div>

                {/*--- Filter Module ---*/}
                <div className="filter-item filter-module">
                    <h4>{wp.i18n.__('Filter Module', 'integrate-google-drive')}</h4>

                    <ReactSelect
                        value={filterModule ? moduleOptions.find(option => option.value == filterModule) : null}
                        className="igd-select"
                        classNamePrefix={"igd-select"}
                        options={moduleOptions}
                        placeholder={wp.i18n.__('Select Module', 'integrate-google-drive')}
                        isClearable={true}
                        onChange={(selectedOption) => {
                            setFilterModule(selectedOption ? selectedOption.value : null);
                        }}
                        components={(components) => ({
                            Option: (props) => {
                                const {data, innerRef, innerProps, isFocused, isSelected} = props;

                                return (
                                    <div
                                        ref={innerRef}
                                        {...innerProps}
                                        className={`igd-select__option igd-select__option${isFocused ? ' igd-select__option--is-focused' : ''} ${isSelected ? ' igd-select__option--is-selected' : ''}`}
                                    >
                                        <img src={data.image} alt={data.label}/>
                                        <span className={`shortcode-id`}>#{data.value} - </span>
                                        <span className={`shortcode-title`}>{data.label}</span>
                                    </div>
                                );
                            },
                            SingleValue: (props) => {
                                const {data} = props;
                                return (
                                    <components.SingleValue {...props}>
                                        <img src={data.image} alt={data.label} width="20" height="20"
                                             style={{marginRight: 8}}/>
                                        {data.label}
                                    </components.SingleValue>
                                );
                            },
                        })}
                    />
                </div>

                {/*--- Filter User ---*/}
                <div className="filter-item filter-user">
                    <h4>{wp.i18n.__('Filter User', 'integrate-google-drive')}</h4>
                    <ReactSelect
                        value={filterUser ? userOptions.find(option => option.value === filterUser) : null}
                        className="igd-select"
                        classNamePrefix={"igd-select"}
                        options={userOptions}
                        placeholder={wp.i18n.__('Select User', 'integrate-google-drive')}
                        isClearable={true}
                        onChange={(selectedOption) => {
                            setFilterUser(selectedOption ? selectedOption.value : null);
                        }}
                    />
                </div>

                {/*--- Items Per Page ---*/}
                <div className="filter-item filter-user filter-per-page">
                    <h4>{wp.i18n.__('Items Per Page', 'integrate-google-drive')}</h4>

                    <SelectControl
                        value={perPage}
                        options={[
                            {label: '10', value: 10},
                            {label: '20', value: 20},
                            {label: '50', value: 50},
                            {label: '100', value: 100},
                        ]}
                        onChange={value => {
                            setPerPage(value);
                            setPage(1);
                            localStorage.setItem('igd_submissions_list_per_page', value);
                        }}
                    />
                </div>

                <Button
                    className="igd-btn btn-primary filter-date"
                    onClick={() => setTooltipOpen(!isTooltipOpen)}
                    label={wp.i18n.__('Filter by Date', 'integrate-google-drive')}
                    icon="calendar"
                >
                    {wp.i18n.__('Filter Date', 'integrate-google-drive')}
                    <i className={'dashicons dashicons-arrow-down-alt2'}></i>
                </Button>

                <Tooltip
                    anchorSelect={'.filter-date'}
                    place={'bottom'}
                    isOpen={isTooltipOpen}
                    setIsOpen={setTooltipOpen}
                    openEvents={['click']}
                    variant="light"
                    clickable={true}
                    border={`1px solid #ddd`}
                    resizeHide={false}
                    className="statistics-tooltip-wrap igd-tooltip"
                >
                    <div className="statistics-filter">
                        <div className="filter-options">

                            <DateRangePicker
                                editableDateInputs={true}
                                onChange={handleDateChange}
                                showSelectionPreview={true}
                                moveRangeOnFirstSelection={false}
                                ranges={dateRange}
                                showMonthAndYearPickers={true}
                                maxDate={new Date()}
                                months={2}
                                direction="horizontal"
                                rangeColors={["#3d91ff"]} // Custom color
                            />

                        </div>
                    </div>
                </Tooltip>

            </div>

            {/*--- List Table ---*/}
            <table className="igd-proof-selections-table">
                <thead>
                <tr>
                    <th className={`col-selection`}>
                        <CheckboxControl
                            checked={selectedSubmissions.length && selectedSubmissions.length === filteredSubmissions.length}
                            onChange={() => {
                                if (selectedSubmissions.length === filteredSubmissions.length) {
                                    setSelectedSubmissions([]);
                                } else {
                                    setSelectedSubmissions(filteredSubmissions.map(item => item.id));
                                }
                            }}
                        />
                    </th>
                    <th className={`col-id`}>{wp.i18n.__('ID', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('Module', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('User', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('Status', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('Page', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('Created at', 'integrate-google-drive')}</th>
                    <th>{wp.i18n.__('Action', 'integrate-google-drive')}</th>
                </tr>
                </thead>

                <tbody>

                {filteredTotal === 0 && (
                    <tr>
                        <td colSpan="8">
                            {selections.length > 0 &&
                                <>
                                    {wp.i18n.__('No submissions found.', 'integrate-google-drive')}
                                </>
                            }


                            {/*--- Empty State ---*/}
                            {!selections.length &&
                                <div className="empty-submissions">

                                    <img src={`${igd.pluginUrl}/assets/images/empty-submissions.png`}
                                         alt={wp.i18n.__('No Submissions', 'integrate-google-drive')}/>


                                    <h5>{wp.i18n.__('No submissions found.', 'integrate-google-drive')}</h5>

                                    <p>{wp.i18n.__('Once users start submitting their proofs, they will appear here.', 'integrate-google-drive')}</p>


                                </div>
                            }

                        </td>
                    </tr>
                )}

                {filteredSubmissions.map(selection => {

                    const {id, module, user, status, page, created_at,} = selection;

                    return (
                        <tr key={id}>

                            <td className={`col-selection`}>
                                <CheckboxControl
                                    checked={selectedSubmissions.includes(id)}
                                    onChange={(isChecked) => {
                                        const currentIndex = shortcodes.findIndex(s => s.id === id);

                                        // Shift key pressed and a previous index exists
                                        if (window.event.shiftKey && lastCheckedIndex !== null) {
                                            const [start, end] = [lastCheckedIndex, currentIndex].sort((a, b) => a - b);
                                            const rangeIds = shortcodes.slice(start, end + 1).map(s => s.id);

                                            const newSelected = isChecked
                                                ? [...new Set([...selectedSubmissions, ...rangeIds])]
                                                : selectedSubmissions.filter(id => !rangeIds.includes(id));

                                            setSelectedSubmissions(newSelected);
                                        } else {
                                            // Normal single toggle
                                            setSelectedSubmissions(prev => {
                                                return isChecked
                                                    ? [...prev, id]
                                                    : prev.filter(item => item !== id);
                                            });
                                        }

                                        setLastCheckedIndex(currentIndex);
                                    }}
                                />

                            </td>

                            {/*--- ID ---*/}
                            <td className={`col-id`}>
                                <Button
                                    className={`module-id`}
                                    text={`#${id}`}
                                    label={wp.i18n.__('View Submission', 'integrate-google-drive')}
                                    onClick={() => {
                                        setSubmission(selection);
                                    }}
                                />
                            </td>

                            {/* Module */}
                            <td>

                                <Button
                                    className={`module-title-text`}
                                    href={`${igd.adminUrl}admin.php?page=integrate-google-drive-shortcode-builder&id=${module.id}`}
                                    label={wp.i18n.__('Edit Module', 'integrate-google-drive')}
                                    text={`${module.title}`}
                                />

                            </td>

                            {/* User */}
                            <td>

                                <Button
                                    className={`user-text`}
                                    href={user.id ? `${igd.adminUrl}/user-edit.php&user_id=${user.id}` : false}
                                    label={wp.i18n.__('View User', 'integrate-google-drive')}
                                    text={`${user.name} (${user.email})`}
                                    icon={
                                        <img
                                            referrerPolicy={`no-referrer`}
                                            className={`user-image`}
                                            src={'https://www.gravatar.com/avatar/' + md5(user.email) + '?s=200&d=mm'}
                                            onError={({currentTarget}) => loadAvatar(currentTarget, user.email)}
                                        />
                                    }
                                />

                            </td>

                            {/* Status */}
                            <td>
                                <span className={`status-label ${parseInt(status) ? 'status-read' : 'status-unread'}`}>
                                    {parseInt(status) ? wp.i18n.__('Read', 'integrate-google-drive') : wp.i18n.__('Unread', 'integrate-google-drive')}
                                </span>
                            </td>

                            {/* Page */}
                            <td>
                                <Button
                                    className={`page-text`}
                                    href={page}
                                    label={wp.i18n.__('View Page', 'integrate-google-drive')}
                                    text={page}
                                    target="_blank"
                                />
                            </td>

                            {/* Created At */}
                            <td>{new Date(created_at).toLocaleString()}</td>

                            {/* Action */}
                            <td>
                                <Button
                                    onClick={() => {
                                        setSubmission(selection);
                                    }}
                                    label={wp.i18n.__('View Details', 'integrate-google-drive')}
                                    text={wp.i18n.__('View', 'integrate-google-drive')}
                                    icon="visibility"
                                    className={`igd-btn btn-primary btn-view-submission`}
                                />
                            </td>
                        </tr>
                    )
                })}

                </tbody>
            </table>

            {/* Pagination */}
            <div className="igd-proof-selections-pagination">
                <Pagination
                    className={"igd-pagination"}
                    pageCount={Math.ceil(filteredTotal / perPage)}
                    currentPage={page}
                    onPageChange={page => setPage(page)}
                />
            </div>

            {!igd.isPro &&
                <ProModal
                    text={wp.i18n.__('Upgrade to PRO to enable file and photo proofing.', 'integrate-google-drive')}
                    isDismissable={false}
                    watchVideo={{
                        id: 'BzJL5LXUbCc',
                        title: wp.i18n.__('How to enable & use Google Drive Photo and File Proofing', 'integrate-google-drive'),
                    }}
                />
            }

        </div>
    )
}