import { h, Fragment, useState, useEffect, useCallback, useRef } from '../react';
import { api, errMsg, __, sprintf } from '../api';
import { Button, Pill, Card, Notice, Spinner, SearchBox, Pagination, ConfirmModal } from '../ui';

const FILTERS = [
    ['all', __('All')], ['live', __('Live')], ['upcoming', __('Upcoming')],
    ['awaiting', __('Awaiting payment')], ['sold', __('Sold')], ['nosale', __('No sale')],
];

function BidsPanel({ id, bidsUrl }) {
    const [data, setData] = useState(null);
    const [error, setError] = useState('');
    useEffect(() => { api(`/auctions/${id}/bids`).then(setData).catch((e) => setError(errMsg(e))); }, [id]);

    if (error) return <p className="rt-error">{error}</p>;
    if (!data) return <Spinner />;
    if (!data.bids.length) return <p>{__('No bids yet.')}</p>;
    return (
        <Fragment>
            <table className="rt-table rt-table--inner">
                <thead><tr><th>{__('Bidder')}</th><th>{__('Amount')}</th><th>{__('Max (proxy)')}</th><th>{__('Type')}</th><th>{__('Time')}</th></tr></thead>
                <tbody>
                    {data.bids.map((b) => (
                        <tr key={b.id}>
                            <td>{b.user}<small className="rt-muted">{b.email}</small></td>
                            <td>{b.amount}</td><td>{b.max || '—'}</td><td>{b.type}</td><td>{b.time}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <p className="rt-muted">
                {sprintf(__('Showing %1$d of %2$d bids.'), data.bids.length, data.total)} <a href={bidsUrl}>{__('Manage all bids')}</a>
            </p>
        </Fragment>
    );
}

export default function AuctionList() {
    const [status, setStatus] = useState('all');
    const [search, setSearch] = useState('');
    const [page, setPage] = useState(1);
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [notice, setNotice] = useState(null);
    const [open, setOpen] = useState(null);
    const [confirm, setConfirm] = useState(null);
    const [busy, setBusy] = useState(false);
    const seq = useRef(0);

    const load = useCallback(() => {
        const my = ++seq.current;
        setLoading(true);
        const q = new URLSearchParams({ status, search, page: String(page), per_page: '20' });
        api(`/auctions?${q}`)
            .then((r) => { if (my === seq.current) setData(r); })
            .catch((e) => setNotice({ type: 'error', text: errMsg(e) }))
            .finally(() => { if (my === seq.current) setLoading(false); });
    }, [status, search, page]);

    useEffect(() => {
        const t = setTimeout(load, search ? 300 : 0);
        return () => clearTimeout(t);
    }, [load, search]);

    const run = () => {
        setBusy(true);
        api(`/auctions/${confirm.id}/${confirm.action}`, { method: 'POST' })
            .then(() => {
                const msg = { end: __('Auction ended.'), relist: __('Auction relisted.'), 'second-chance': __('Second-chance offer sent.') };
                setNotice({ type: 'success', text: msg[confirm.action] });
                setConfirm(null); load();
            })
            .catch((e) => { setNotice({ type: 'error', text: errMsg(e) }); setConfirm(null); })
            .finally(() => setBusy(false));
    };

    const items = data ? data.items : [];

    return (
        <div className="rt-screen">
            <div className="rt-title">
                <h1>{__('Auction List')}</h1>
                {data && <Button variant="primary" href={data.new_url}>{__('Add auction')}</Button>}
            </div>
            {notice && <Notice type={notice.type} onDismiss={() => setNotice(null)}>{notice.text}</Notice>}

            <div className="rt-toolbar">
                <div className="rt-tabs" role="tablist">
                    {FILTERS.map(([key, label]) => (
                        <button key={key} role="tab" aria-selected={status === key} className={'rt-tab' + (status === key ? ' is-active' : '')}
                                onClick={() => { setStatus(key); setPage(1); setOpen(null); }}>
                            {label}{data && <span className="rt-count">{data.counts[key]}</span>}
                        </button>
                    ))}
                </div>
                <SearchBox value={search} onChange={(v) => { setSearch(v); setPage(1); }} placeholder={__('Search auctions…')} />
            </div>

            <Card flush>
                <div className="rt-scroll">
                    <table className={'rt-table' + (loading ? ' is-loading' : '')}>
                        <thead>
                            <tr>
                                <th>{__('Auction')}</th><th>{__('Status')}</th><th>{__('Price')}</th><th>{__('Bids')}</th>
                                <th>{__('Leader / winner')}</th><th>{__('Ends')}</th><th>{__('Actions')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {!data && <tr><td colSpan="7"><Spinner /></td></tr>}
                            {data && !items.length && <tr><td colSpan="7" className="rt-empty">{__('No auctions found.')}</td></tr>}
                            {items.map((it) => (
                                <Fragment key={it.id}>
                                    <tr>
                                        <td>
                                            <div className="rt-product">
                                                <img src={it.image} alt="" width="44" height="44" />
                                                <div>
                                                    <a href={it.edit_url}><strong>{it.title}</strong></a>
                                                    <small className="rt-muted">
                                                        #{it.id} · {sprintf(__('Start %s'), it.start_price)}
                                                        {it.type === 'sealed' ? ' · ' + __('Sealed') : ''}
                                                        {it.premium > 0 ? ' · ' + sprintf(__('%s%% premium'), it.premium) : ''}
                                                        {it.relists ? ' · ' + sprintf(__('Relisted %s'), it.relists) : ''}
                                                        {it.watchers ? ' · ' + sprintf(__('%d watching'), it.watchers) : ''}
                                                    </small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <Pill status={it.status}>{it.status_label}</Pill>
                                            {it.reserve !== 'none' && <small className="rt-muted">{it.reserve === 'met' ? __('Reserve met') : __('Reserve not met')}</small>}
                                        </td>
                                        <td>{it.price}</td>
                                        <td>
                                            <Button variant="link" aria-expanded={open === it.id} onClick={() => setOpen(open === it.id ? null : it.id)}>
                                                {it.bid_count} <span aria-hidden="true">{open === it.id ? '▴' : '▾'}</span>
                                            </Button>
                                        </td>
                                        <td>{it.winner || it.leader || '—'}</td>
                                        <td>{it.end || '—'}</td>
                                        <td>
                                            <div className="rt-row-actions">
                                                <Button size="sm" href={it.edit_url}>{__('Edit')}</Button>
                                                <Button size="sm" variant="ghost" href={it.view_url} target="_blank" rel="noopener">{__('View')}</Button>
                                                {it.can_end && <Button size="sm" variant="ghost" danger onClick={() => setConfirm({ id: it.id, action: 'end', title: it.title })}>{__('End now')}</Button>}
                                                {it.can_second_chance && <Button size="sm" variant="ghost" onClick={() => setConfirm({ id: it.id, action: 'second-chance', title: it.title })}>{__('Offer to next bidder')}</Button>}
                                                {it.can_relist && <Button size="sm" variant="ghost" onClick={() => setConfirm({ id: it.id, action: 'relist', title: it.title })}>{__('Relist')}</Button>}
                                            </div>
                                        </td>
                                    </tr>
                                    {open === it.id && <tr className="rt-expand"><td colSpan="7"><BidsPanel id={it.id} bidsUrl={it.bids_url} /></td></tr>}
                                </Fragment>
                            ))}
                        </tbody>
                    </table>
                </div>
            </Card>

            {data && <Pagination page={page} pages={data.total_pages} onChange={setPage} />}

            {confirm && (
                <ConfirmModal
                    busy={busy}
                    danger={confirm.action === 'end'}
                    title={{ end: __('End auction now?'), relist: __('Relist auction?'), 'second-chance': __('Offer to next bidder?') }[confirm.action]}
                    message={{
                        end: sprintf(__('"%s" will close immediately and the winner (if any) will be notified.'), confirm.title),
                        relist: sprintf(__('"%s" will start a new round with the same duration. Existing bids are archived.'), confirm.title),
                        'second-chance': sprintf(__('The current winner of "%s" is dropped and the next-highest bidder is invited to buy at their own bid.'), confirm.title),
                    }[confirm.action]}
                    confirmLabel={{ end: __('End now'), relist: __('Relist'), 'second-chance': __('Send offer') }[confirm.action]}
                    onConfirm={run}
                    onCancel={() => setConfirm(null)}
                />
            )}
        </div>
    );
}
