import { useState, useMemo } from 'react';

interface CalendarEvent {
    id: number;
    title: string;
    date: string;
    type: 'domain' | 'hosting' | 'license' | 'development' | 'support';
    client_name: string;
    client_email: string;
    provider: string;
    price: number;
    status: 'active' | 'expiring_soon' | 'expired';
}

// Mock events - Ready for MariaDB connection
const mockEvents: CalendarEvent[] = [
    { id: 1, title: 'acme-corp.com', date: '2026-01-28', type: 'domain', client_name: 'Acme Corporation', client_email: 'admin@acme.com', provider: 'Namecheap', price: 12.99, status: 'expiring_soon' },
    { id: 2, title: 'Hosting Empresarial Pro', date: '2026-01-30', type: 'hosting', client_name: 'Beta Technologies', client_email: 'info@betatech.com', provider: 'Webuzo VPS', price: 240.00, status: 'active' },
    { id: 3, title: 'gammastore.com', date: '2026-02-05', type: 'domain', client_name: 'Gamma Retail SA', client_email: 'contacto@gamma.com', provider: 'GoDaddy', price: 14.99, status: 'expiring_soon' },
    { id: 4, title: 'Licencia Microsoft 365', date: '2026-02-01', type: 'license', client_name: 'Delta Industries', client_email: 'it@delta.com', provider: 'Microsoft', price: 150.00, status: 'active' },
    { id: 5, title: 'beta-tech.com', date: '2026-02-15', type: 'domain', client_name: 'Beta Technologies', client_email: 'info@betatech.com', provider: 'Cloudflare', price: 9.99, status: 'active' },
    { id: 6, title: 'Soporte Premium', date: '2026-01-31', type: 'support', client_name: 'Sigma Corp', client_email: 'admin@sigma.com', provider: 'Cibertronia Service', price: 199.00, status: 'expiring_soon' },
    { id: 7, title: 'epsilon-tech.net', date: '2026-02-20', type: 'domain', client_name: 'Epsilon Tech', client_email: 'admin@epsilon.net', provider: 'Namecheap', price: 18.99, status: 'active' },
    { id: 8, title: 'VPS Cloud Server', date: '2026-02-28', type: 'hosting', client_name: 'Kappa Systems', client_email: 'tech@kappa.systems', provider: 'DigitalOcean', price: 48.00, status: 'active' },
    { id: 9, title: 'omega-solutions.co', date: '2026-01-25', type: 'domain', client_name: 'Omega Solutions', client_email: 'soporte@omega.co', provider: 'Namecheap', price: 12.99, status: 'expired' },
    { id: 10, title: 'Web Development Project', date: '2026-03-15', type: 'development', client_name: 'Zeta Media', client_email: 'hello@zetamedia.io', provider: 'Cibertronia Service', price: 2500.00, status: 'active' },
];

const typeConfig: Record<string, { label: string; icon: string; color: string }> = {
    domain: { label: 'Dominio', icon: '🌐', color: '#3b82f6' },
    hosting: { label: 'Hosting', icon: '🖥️', color: '#8b5cf6' },
    license: { label: 'Licencia', icon: '📄', color: '#06b6d4' },
    development: { label: 'Desarrollo', icon: '💻', color: '#f59e0b' },
    support: { label: 'Soporte', icon: '🛠️', color: '#10b981' },
};

const statusColors: Record<string, string> = {
    active: '#10b981',
    expiring_soon: '#f59e0b',
    expired: '#ef4444',
};

const statusLabels: Record<string, string> = {
    active: 'Activo',
    expiring_soon: 'Por Vencer',
    expired: 'Vencido',
};

export default function Calendar() {
    const [selectedDate, setSelectedDate] = useState<string | null>(null);
    const [currentMonth, setCurrentMonth] = useState(new Date());
    const [viewMode, setViewMode] = useState<'month' | 'list'>('month');
    const [filterType, setFilterType] = useState<string>('all');

    // Filter events by type
    const filteredEvents = useMemo(() => {
        if (filterType === 'all') return mockEvents;
        return mockEvents.filter(e => e.type === filterType);
    }, [filterType]);

    // Get month range stats
    const monthStats = useMemo(() => {
        const year = currentMonth.getFullYear();
        const month = currentMonth.getMonth();
        const monthEvents = filteredEvents.filter(event => {
            const eventDate = new Date(event.date);
            return eventDate.getFullYear() === year && eventDate.getMonth() === month;
        });
        return {
            total: monthEvents.length,
            expiring: monthEvents.filter(e => e.status === 'expiring_soon' || e.status === 'expired').length,
            revenue: monthEvents.reduce((sum, e) => sum + e.price, 0),
        };
    }, [currentMonth, filteredEvents]);

    // Get days in month
    const getDaysInMonth = (date: Date) => {
        const year = date.getFullYear();
        const month = date.getMonth();
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const daysInMonth = lastDay.getDate();
        const startingDay = firstDay.getDay();

        const days: (number | null)[] = [];

        for (let i = 0; i < startingDay; i++) {
            days.push(null);
        }

        for (let i = 1; i <= daysInMonth; i++) {
            days.push(i);
        }

        return days;
    };

    const formatDate = (day: number) => {
        const year = currentMonth.getFullYear();
        const month = String(currentMonth.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}-${String(day).padStart(2, '0')}`;
    };

    const getEventsForDay = (day: number) => {
        const dateStr = formatDate(day);
        return filteredEvents.filter(event => event.date === dateStr);
    };

    const selectedEvents = selectedDate
        ? filteredEvents.filter(event => event.date === selectedDate)
        : [];

    const monthNames = [
        'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
        'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'
    ];

    const dayNames = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];

    const prevMonth = () => {
        setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1));
        setSelectedDate(null);
    };

    const nextMonth = () => {
        setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1));
        setSelectedDate(null);
    };

    const goToToday = () => {
        setCurrentMonth(new Date());
        const today = new Date().toISOString().split('T')[0];
        setSelectedDate(today);
    };

    const days = getDaysInMonth(currentMonth);
    const today = new Date().toISOString().split('T')[0];

    // Get upcoming events for the list view
    const upcomingEvents = useMemo(() => {
        return [...filteredEvents]
            .filter(e => new Date(e.date) >= new Date(today))
            .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
            .slice(0, 10);
    }, [filteredEvents, today]);

    return (
        <div className="animate-fadeIn">
            {/* Page Header */}
            <div className="page-header">
                <div>
                    <h1 className="page-title">Agenda Visual</h1>
                    <p className="page-subtitle">Calendario de vencimientos y renovaciones</p>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem' }}>
                    <button
                        className={`btn ${viewMode === 'month' ? 'btn-primary' : 'btn-secondary'}`}
                        onClick={() => setViewMode('month')}
                    >
                        📅 Mes
                    </button>
                    <button
                        className={`btn ${viewMode === 'list' ? 'btn-primary' : 'btn-secondary'}`}
                        onClick={() => setViewMode('list')}
                    >
                        📋 Lista
                    </button>
                </div>
            </div>

            {/* Month Stats */}
            <div style={{ display: 'flex', gap: '1rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
                <div className="stat-tag">
                    <span>📅</span>
                    <span>{monthNames[currentMonth.getMonth()]}:</span>
                    <span className="stat-tag-value">{monthStats.total} renovaciones</span>
                </div>
                <div className="stat-tag">
                    <span>⚠️</span>
                    <span>Requieren atención:</span>
                    <span className="stat-tag-value" style={{ color: monthStats.expiring > 0 ? 'var(--color-warning)' : 'inherit' }}>
                        {monthStats.expiring}
                    </span>
                </div>
                <div className="stat-tag">
                    <span>💵</span>
                    <span>Ingresos potenciales:</span>
                    <span className="stat-tag-value" style={{ color: 'var(--color-success)' }}>
                        ${monthStats.revenue.toLocaleString('es-ES', { minimumFractionDigits: 2 })}
                    </span>
                </div>

                {/* Type Filter */}
                <select
                    className="form-select"
                    value={filterType}
                    onChange={(e) => setFilterType(e.target.value)}
                    style={{ marginLeft: 'auto', minWidth: '150px' }}
                >
                    <option value="all">Todos los tipos</option>
                    <option value="domain">🌐 Dominios</option>
                    <option value="hosting">🖥️ Hosting</option>
                    <option value="license">📄 Licencias</option>
                    <option value="development">💻 Desarrollo</option>
                    <option value="support">🛠️ Soporte</option>
                </select>
            </div>

            {viewMode === 'month' ? (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: '1.5rem' }}>
                    {/* Calendar */}
                    <div className="calendar-container">
                        {/* Calendar Header */}
                        <div className="calendar-header">
                            <div className="calendar-nav">
                                <button className="btn btn-secondary btn-sm" onClick={prevMonth}>
                                    ← Anterior
                                </button>
                                <button className="btn btn-ghost btn-sm" onClick={goToToday}>
                                    Hoy
                                </button>
                                <button className="btn btn-secondary btn-sm" onClick={nextMonth}>
                                    Siguiente →
                                </button>
                            </div>
                            <h2 className="calendar-title">
                                {monthNames[currentMonth.getMonth()]} {currentMonth.getFullYear()}
                            </h2>
                        </div>

                        {/* Day Names */}
                        <div className="calendar-grid" style={{ marginBottom: '0.5rem' }}>
                            {dayNames.map(day => (
                                <div key={day} className="calendar-day-name">
                                    {day}
                                </div>
                            ))}
                        </div>

                        {/* Calendar Grid */}
                        <div className="calendar-grid">
                            {days.map((day, index) => {
                                if (day === null) {
                                    return <div key={`empty-${index}`} style={{ minHeight: '90px' }} />;
                                }

                                const dateStr = formatDate(day);
                                const events = getEventsForDay(day);
                                const isSelected = selectedDate === dateStr;
                                const isToday = today === dateStr;

                                return (
                                    <div
                                        key={day}
                                        className={`calendar-day ${isToday ? 'today' : ''} ${isSelected ? 'selected' : ''}`}
                                        onClick={() => setSelectedDate(dateStr)}
                                    >
                                        <div className="calendar-day-number">
                                            {day}
                                        </div>

                                        <div className="calendar-events">
                                            {events.slice(0, 4).map(event => (
                                                <div
                                                    key={event.id}
                                                    className="calendar-event-dot"
                                                    style={{ background: statusColors[event.status] }}
                                                    title={`${event.title} - ${event.client_name}`}
                                                />
                                            ))}
                                            {events.length > 4 && (
                                                <span style={{ fontSize: '0.6rem', color: 'var(--text-muted)' }}>
                                                    +{events.length - 4}
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>

                        {/* Legend */}
                        <div style={{
                            display: 'flex',
                            gap: '1.5rem',
                            marginTop: '1.5rem',
                            paddingTop: '1rem',
                            borderTop: '1px solid var(--border-color)',
                            justifyContent: 'center'
                        }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                                <span style={{ width: '10px', height: '10px', borderRadius: '50%', background: statusColors.active }}></span>
                                Activo
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                                <span style={{ width: '10px', height: '10px', borderRadius: '50%', background: statusColors.expiring_soon }}></span>
                                Por Vencer
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                                <span style={{ width: '10px', height: '10px', borderRadius: '50%', background: statusColors.expired }}></span>
                                Vencido
                            </div>
                        </div>
                    </div>

                    {/* Events Panel */}
                    <div className="event-panel">
                        <h3 className="event-panel-title">
                            {selectedDate
                                ? `📌 Renovaciones del ${new Date(selectedDate + 'T00:00:00').toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' })}`
                                : '📌 Selecciona un día'
                            }
                        </h3>

                        {!selectedDate && (
                            <div className="empty-state" style={{ padding: '2rem 1rem' }}>
                                <div className="empty-state-icon" style={{ fontSize: '2.5rem' }}>👆</div>
                                <div className="empty-state-text">
                                    Haz clic en un día del calendario para ver las renovaciones programadas
                                </div>
                            </div>
                        )}

                        {selectedDate && selectedEvents.length === 0 && (
                            <div className="empty-state" style={{ padding: '2rem 1rem' }}>
                                <div className="empty-state-icon" style={{ fontSize: '2.5rem' }}>✅</div>
                                <div className="empty-state-title">Sin renovaciones</div>
                                <div className="empty-state-text">
                                    No hay servicios que venzan este día
                                </div>
                            </div>
                        )}

                        {selectedEvents.map(event => (
                            <div
                                key={event.id}
                                className="event-item"
                                style={{ borderLeftColor: statusColors[event.status] }}
                            >
                                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '0.5rem' }}>
                                    <div className="event-item-title">{event.title}</div>
                                    <span
                                        className="badge"
                                        style={{
                                            fontSize: '0.65rem',
                                            padding: '0.2rem 0.5rem',
                                            background: `${statusColors[event.status]}15`,
                                            color: statusColors[event.status],
                                        }}
                                    >
                                        {statusLabels[event.status]}
                                    </span>
                                </div>
                                <div className="event-item-client">
                                    👤 {event.client_name}
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '0.5rem' }}>
                                    <span className="event-item-type">
                                        {typeConfig[event.type].icon} {typeConfig[event.type].label} • {event.provider}
                                    </span>
                                    <span style={{ fontWeight: 700, color: 'var(--color-success)', fontSize: '0.85rem' }}>
                                        ${event.price.toLocaleString('es-ES', { minimumFractionDigits: 2 })}
                                    </span>
                                </div>
                                <div style={{ marginTop: '0.75rem', display: 'flex', gap: '0.5rem' }}>
                                    <button className="btn btn-primary btn-sm" style={{ flex: 1 }}>
                                        🔄 Renovar
                                    </button>
                                    <button className="btn btn-secondary btn-sm">
                                        📧
                                    </button>
                                </div>
                            </div>
                        ))}

                        {/* Upcoming summary */}
                        <div style={{
                            marginTop: '1.5rem',
                            paddingTop: '1rem',
                            borderTop: '1px solid var(--border-color)'
                        }}>
                            <h4 style={{
                                fontSize: '0.85rem',
                                fontWeight: 600,
                                marginBottom: '0.75rem',
                                color: 'var(--text-secondary)'
                            }}>
                                ⏰ Próximas 5 renovaciones
                            </h4>
                            {upcomingEvents.slice(0, 5).map(event => (
                                <div
                                    key={event.id}
                                    style={{
                                        display: 'flex',
                                        justifyContent: 'space-between',
                                        alignItems: 'center',
                                        padding: '0.5rem 0',
                                        fontSize: '0.85rem',
                                        cursor: 'pointer',
                                    }}
                                    onClick={() => setSelectedDate(event.date)}
                                >
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                        <span style={{
                                            width: '6px',
                                            height: '6px',
                                            borderRadius: '50%',
                                            background: statusColors[event.status]
                                        }}></span>
                                        <span>{event.title}</span>
                                    </div>
                                    <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}>
                                        {new Date(event.date).toLocaleDateString('es-ES', { day: '2-digit', month: 'short' })}
                                    </span>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            ) : (
                /* List View */
                <div className="table-container">
                    <div className="table-header">
                        <h2 className="table-title">📋 Próximas Renovaciones</h2>
                    </div>
                    <div className="table-wrapper">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Servicio</th>
                                    <th>Cliente</th>
                                    <th>Tipo</th>
                                    <th>Proveedor</th>
                                    <th>Precio</th>
                                    <th>Estado</th>
                                    <th>Acción</th>
                                </tr>
                            </thead>
                            <tbody>
                                {upcomingEvents.map(event => (
                                    <tr key={event.id}>
                                        <td>
                                            <div style={{ fontWeight: 600 }}>
                                                {new Date(event.date).toLocaleDateString('es-ES', {
                                                    weekday: 'short',
                                                    day: '2-digit',
                                                    month: 'short'
                                                })}
                                            </div>
                                        </td>
                                        <td className="cell-main">{event.title}</td>
                                        <td>
                                            <div>{event.client_name}</div>
                                            <div className="cell-secondary">{event.client_email}</div>
                                        </td>
                                        <td>
                                            <span
                                                className="badge"
                                                style={{
                                                    background: `${typeConfig[event.type].color}15`,
                                                    color: typeConfig[event.type].color,
                                                }}
                                            >
                                                {typeConfig[event.type].icon} {typeConfig[event.type].label}
                                            </span>
                                        </td>
                                        <td>{event.provider}</td>
                                        <td style={{ fontWeight: 600 }}>
                                            ${event.price.toLocaleString('es-ES', { minimumFractionDigits: 2 })}
                                        </td>
                                        <td>
                                            <span
                                                className="badge"
                                                style={{
                                                    background: `${statusColors[event.status]}15`,
                                                    color: statusColors[event.status],
                                                }}
                                            >
                                                <span className="badge-dot"></span>
                                                {statusLabels[event.status]}
                                            </span>
                                        </td>
                                        <td>
                                            <button className="btn btn-primary btn-sm">
                                                Renovar
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
        </div>
    );
}
