import { useState, useEffect } from '@wordpress/element';
import { Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import api from '../api/client';

const PRO_UPGRADE_URL = 'https://appointly.tscholene.com/?ref=plugin-dashboard';

/**
 * Status pill for booking status.
 */
const StatusPill = ({ status }) => {
    const styles = {
        pending:   { bg: 'rgba(245, 158, 11, 0.12)',  color: '#B45309' },
        offered:   { bg: 'rgba(168, 85, 247, 0.12)',  color: '#7C3AED' },
        confirmed: { bg: 'rgba(16, 185, 129, 0.12)',  color: '#047857' },
        declined:  { bg: 'rgba(239, 68, 68, 0.12)',   color: '#B91C1C' },
        cancelled: { bg: 'rgba(148, 163, 184, 0.16)', color: '#475569' },
    };
    const s = styles[status] || styles.pending;
    const label = {
        pending:   __('Pending',   'appointly'),
        offered:   __('Offered',   'appointly'),
        confirmed: __('Confirmed', 'appointly'),
        declined:  __('Declined',  'appointly'),
        cancelled: __('Cancelled', 'appointly'),
    }[status] || status;
    return (
        <span className="appointly-pill" style={{ background: s.bg, color: s.color }}>
            {label}
        </span>
    );
};

/**
 * Stat tile with warm accent.
 */
const StatTile = ({ label, value, accent = 'plum', icon }) => (
    <div className={`appointly-stat-tile appointly-stat-tile--${accent}`}>
        <div className="appointly-stat-tile__icon">
            <span className={`dashicons dashicons-${icon}`}></span>
        </div>
        <div className="appointly-stat-tile__body">
            <div className="appointly-stat-tile__value">{value}</div>
            <div className="appointly-stat-tile__label">{label}</div>
        </div>
    </div>
);

/**
 * Mini calendar — compact month view with dot indicators per status.
 */
const MiniCalendar = ({ calendarData }) => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const today = now.getDate();

    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const monthName = new Date(year, month, 1).toLocaleString('default', { month: 'long', year: 'numeric' });

    const dayMap = {};
    if (calendarData && Array.isArray(calendarData)) {
        calendarData.forEach((entry) => {
            const d = new Date(entry.date);
            if (d.getMonth() === month && d.getFullYear() === year) {
                dayMap[d.getDate()] = entry.status || 'booked';
            }
        });
    }

    const dotColors = {
        booked:    '#A855F7',
        confirmed: '#10B981',
        pending:   '#F59E0B',
        blocked:   '#EF4444',
        free:      'transparent',
    };

    const weekDays = [
        __('Mo', 'appointly'),
        __('Tu', 'appointly'),
        __('We', 'appointly'),
        __('Th', 'appointly'),
        __('Fr', 'appointly'),
        __('Sa', 'appointly'),
        __('Su', 'appointly'),
    ];

    // Convert Sunday-first to Monday-first.
    const mondayFirstFirstDay = (firstDay + 6) % 7;

    const cells = [];
    for (let i = 0; i < mondayFirstFirstDay; i++) {
        cells.push(<div key={`empty-${i}`} className="appointly-mini-cal__cell appointly-mini-cal__cell--empty" />);
    }
    for (let d = 1; d <= daysInMonth; d++) {
        const status = dayMap[d];
        const isToday = d === today;
        const dotColor = status && status !== 'free' ? dotColors[status] : null;
        cells.push(
            <div
                key={d}
                className={`appointly-mini-cal__cell${isToday ? ' appointly-mini-cal__cell--today' : ''}`}
            >
                <span className="appointly-mini-cal__day">{d}</span>
                {dotColor && (
                    <span
                        className="appointly-mini-cal__dot"
                        style={{ backgroundColor: dotColor }}
                    />
                )}
            </div>
        );
    }

    return (
        <div className="appointly-mini-cal">
            <div className="appointly-mini-cal__header">{monthName}</div>
            <div className="appointly-mini-cal__weekdays">
                {weekDays.map((day) => (
                    <div key={day} className="appointly-mini-cal__weekday">{day}</div>
                ))}
            </div>
            <div className="appointly-mini-cal__grid">{cells}</div>
        </div>
    );
};

/**
 * Pro upgrade card — matches appointly.tscholene.com vibe.
 *
 * Appointly Pro is a separate companion plugin sold on
 * appointly.tscholene.com via Lemon Squeezy. Clicking the CTA opens
 * the pricing page in a new tab where the current Lemon Squeezy
 * checkout variant is wired up. We deliberately do NOT link directly
 * to a Lemon Squeezy checkout URL from this plugin — the marketing
 * site handles variant routing so we can swap LS variant IDs without
 * shipping a plugin release.
 *
 * Feature list below reflects Pro 0.6.0 — the currently-shipped
 * features. Roadmap items are signaled by the trailing "and more" in
 * the lede, not promised by name here.
 */
const ProUpgradeCard = () => (
    <div className="appointly-pro-card">
        <div className="appointly-pro-card__glow" />
        <div className="appointly-pro-card__content">
            <div className="appointly-pro-card__kicker">
                <span className="dashicons dashicons-star-filled"></span>
                {__('Appointly Pro', 'appointly')}
            </div>
            <h3 className="appointly-pro-card__title">
                {__('Booking features that pay for themselves.', 'appointly')}
            </h3>
            <p className="appointly-pro-card__lede">
                {__(
                    'Appointly Pro is a separate companion plugin that extends Appointly with custom branding, a full email template editor, service addons, recurring bookings, and more. €2.99 per month. Regular updates, no lock-in.',
                    'appointly'
                )}
            </p>
            <ul className="appointly-pro-card__features">
                <li>
                    <span className="dashicons dashicons-art"></span>
                    {__('Custom branding — colors + logo across frontend and emails', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-email-alt"></span>
                    {__('Custom email template editor with live preview', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-forms"></span>
                    {__('Custom service fields — text, textarea, number, select, checkbox', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-cart"></span>
                    {__('Service upsells & addons with quantity', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-update"></span>
                    {__('Recurring bookings — weekly, bi-weekly, monthly', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-yes-alt"></span>
                    {__('Direct booking — auto-confirm for fixed-price services', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-lock"></span>
                    {__('Blocked dates — per service or global', 'appointly')}
                </li>
                <li>
                    <span className="dashicons dashicons-admin-users"></span>
                    {__('Customer self-cancel for direct-booking services (secure email link)', 'appointly')}
                </li>
            </ul>
            <div className="appointly-pro-card__actions">
                <a
                    href={PRO_UPGRADE_URL}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="appointly-btn appointly-btn--cta"
                >
                    {__('Get Pro →', 'appointly')}
                </a>
                <a
                    href="https://appointly.tscholene.com/?ref=plugin-dashboard#pricing"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="appointly-btn appointly-btn--ghost"
                >
                    {__('See pricing', 'appointly')}
                </a>
            </div>
        </div>
    </div>
);

/**
 * Dashboard — main admin landing page.
 */
export default function Dashboard() {
    const [bookings, setBookings]       = useState([]);
    const [counts, setCounts]           = useState({ pending: 0, offered: 0, confirmed: 0, total: 0 });
    const [calendarData, setCalendarData] = useState([]);
    const [loading, setLoading]         = useState(true);

    useEffect(() => {
        let cancelled = false;

        const fetchData = async () => {
            try {
                const bookingsRes = await api.getBookings({ per_page: 5 });
                if (cancelled) return;

                const items = bookingsRes?.items || bookingsRes?.bookings || [];
                setBookings(Array.isArray(items) ? items : []);

                if (bookingsRes?.counts) {
                    setCounts(bookingsRes.counts);
                }

                try {
                    const now = new Date();
                    const serviceId = items?.[0]?.service_id || 1;
                    const calRes = await api.getCalendar(serviceId, {
                        year: now.getFullYear(),
                        month: now.getMonth() + 1,
                    });
                    if (!cancelled && calRes) {
                        setCalendarData(Array.isArray(calRes) ? calRes : calRes.dates || []);
                    }
                } catch (e) {
                    // Calendar data is optional.
                }
            } catch (error) {
                if (!cancelled) {
                    // eslint-disable-next-line no-console
                    console.error('Dashboard fetch error:', error);
                }
            } finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        };

        fetchData();
        return () => { cancelled = true; };
    }, []);

    const formatDate = (dateStr) => {
        if (!dateStr) return '—';
        const d = new Date(dateStr);
        return d.toLocaleDateString('default', { year: 'numeric', month: 'short', day: 'numeric' });
    };

    if (loading) {
        return (
            <div className="appointly-dashboard-loading">
                <Spinner />
                <p>{__('Loading dashboard…', 'appointly')}</p>
            </div>
        );
    }

    const onboardingDone = window.appointlyAdmin?.onboardingCompleted;
    const siteName = window.appointlyAdmin?.siteName || __('your site', 'appointly');

    return (
        <div className="appointly-dashboard">
            {/* Hero */}
            <div className="appointly-dashboard__hero">
                <div className="appointly-dashboard__hero-text">
                    <span className="appointly-dashboard__kicker">{__('Appointly', 'appointly')}</span>
                    <h1 className="appointly-dashboard__heading">
                        {__('Every reservation is a conversation.', 'appointly')}
                    </h1>
                    <p className="appointly-dashboard__sub">
                        {
                            /* translators: %s: site name */
                            __('Welcome back to %s — here is what your customers are asking for today.', 'appointly')
                                .replace('%s', siteName)
                        }
                    </p>
                </div>
            </div>

            {/* Onboarding banner (if not done) */}
            {!onboardingDone && (
                <div className="appointly-onboarding-banner">
                    <div className="appointly-onboarding-banner__content">
                        <span className="dashicons dashicons-welcome-learn-more"></span>
                        <div>
                            <strong>{__('Welcome to Appointly', 'appointly')}</strong>
                            <p>{__('Finish the setup wizard to create your first service and start taking bookings.', 'appointly')}</p>
                        </div>
                    </div>
                    <a
                        href={window.appointlyAdmin?.adminUrl + 'admin.php?page=appointly-setup'}
                        className="appointly-btn appointly-btn--cta"
                    >
                        {__('Start Setup →', 'appointly')}
                    </a>
                </div>
            )}

            {/* Stats */}
            <div className="appointly-stats-grid">
                <StatTile
                    label={__('Pending requests', 'appointly')}
                    value={counts.pending || 0}
                    icon="clock"
                    accent="amber"
                />
                <StatTile
                    label={__('Offered', 'appointly')}
                    value={counts.offered || 0}
                    icon="email-alt"
                    accent="plum"
                />
                <StatTile
                    label={__('Confirmed this month', 'appointly')}
                    value={counts.confirmed || 0}
                    icon="yes-alt"
                    accent="emerald"
                />
                <StatTile
                    label={__('All time bookings', 'appointly')}
                    value={counts.total || 0}
                    icon="list-view"
                    accent="slate"
                />
            </div>

            {/* Main content: Recent Bookings + Mini Calendar */}
            <div className="appointly-dashboard__body">
                <div className="appointly-dashboard__recent">
                    <div className="appointly-dashboard__section-header">
                        <h3>{__('Recent bookings', 'appointly')}</h3>
                        <a href="#/bookings" className="appointly-dashboard__view-all">
                            {__('View all →', 'appointly')}
                        </a>
                    </div>

                    {bookings.length === 0 ? (
                        <div className="appointly-dashboard__empty">
                            <span className="dashicons dashicons-calendar-alt"></span>
                            <p>{__('No bookings yet. Add the [appointly_calendar] shortcode to a page to start receiving requests.', 'appointly')}</p>
                        </div>
                    ) : (
                        <table className="appointly-dashboard__table">
                            <thead>
                                <tr>
                                    <th>{__('Date', 'appointly')}</th>
                                    <th>{__('Name', 'appointly')}</th>
                                    <th>{__('Service', 'appointly')}</th>
                                    <th>{__('Status', 'appointly')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {bookings.map((booking) => (
                                    <tr
                                        key={booking.id}
                                        className="appointly-dashboard__table-row"
                                        onClick={() => { window.location.hash = `/bookings/${booking.id}`; }}
                                    >
                                        <td>{formatDate(booking.preferred_date || booking.date)}</td>
                                        <td>{booking.customer_name || booking.name || '—'}</td>
                                        <td>{booking.service_name || booking.service || '—'}</td>
                                        <td><StatusPill status={booking.status} /></td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>

                <div className="appointly-dashboard__calendar">
                    <div className="appointly-dashboard__section-header">
                        <h3>{__('This month', 'appointly')}</h3>
                    </div>
                    <MiniCalendar calendarData={calendarData} />
                </div>
            </div>

            {/* Pro upgrade card — hidden when Pro is active */}
            {!window.appointlyAdmin?.proActive && <ProUpgradeCard />}
        </div>
    );
}
