import { useState } from 'react';
import { Link } from 'react-router-dom';
import PageHeader from '../components/PageHeader';

/**
 * 📊 PÁGINA: REPORTES DE TICKETS
 * 
 * Muestra estadísticas, gráficas y métricas del sistema de soporte técnico
 */

export default function TicketsReports() {
    const [dateRange, setDateRange] = useState('30');

    // Mock data simulando estadísticas del último mes
    const ticketsByStatus = [
        { status: 'Abiertos', count: 12, color: '#ef4444', percentage: 24 },
        { status: 'En Progreso', count: 18, color: '#3b82f6', percentage: 36 },
        { status: 'Esperando', count: 8, color: '#f59e0b', percentage: 16 },
        { status: 'Resueltos', count: 12, color: '#10b981', percentage: 24 },
    ];

    const ticketsByPriority = [
        { priority: 'Crítica', count: 5, color: '#dc2626', emoji: '🔴' },
        { priority: 'Alta', count: 12, color: '#ef4444', emoji: '🟠' },
        { priority: 'Media', count: 18, color: '#f59e0b', emoji: '🟡' },
        { priority: 'Baja', count: 15, color: '#64748b', emoji: '🟢' },
    ];

    const topClients = [
        { name: 'Acme Corporation', tickets: 8, resolved: 5 },
        { name: 'Beta Technologies', tickets: 6, resolved: 4 },
        { name: 'Gamma Retail SA', tickets: 5, resolved: 5 },
        { name: 'Delta Industries', tickets: 4, resolved: 2 },
        { name: 'Epsilon Tech', tickets: 3, resolved: 1 },
    ];

    const responseMetrics = {
        avgFirstResponse: '2.4h',
        avgResolution: '18.5h',
        satisfactionRate: '94%',
        slaCompliance: '89%',
    };

    return (
        <div className="animate-fadeIn">
            <PageHeader
                title="📊 Reportes de Tickets"
                subtitle="Estadísticas y métricas del sistema de soporte"
                actions={
                    <>
                        <Link to="/tickets" className="btn btn-secondary">
                            ← Volver a Tickets
                        </Link>
                        <button className="btn btn-primary">
                            📥 Exportar Reporte
                        </button>
                    </>
                }
            />

            {/* Filtro de Rango de Fechas */}
            <div className="card" style={{ marginBottom: '2rem' }}>
                <div style={{ display: 'flex', gap: '1rem', alignItems: 'center', flexWrap: 'wrap' }}>
                    <label style={{ fontWeight: 600, fontSize: '0.95rem' }}>
                        📅 Período:
                    </label>
                    <select
                        className="input"
                        value={dateRange}
                        onChange={(e) => setDateRange(e.target.value)}
                        style={{ maxWidth: '200px' }}
                    >
                        <option value="7">Últimos 7 días</option>
                        <option value="30">Últimos 30 días</option>
                        <option value="90">Últimos 90 días</option>
                        <option value="365">Último año</option>
                    </select>
                    <div style={{ color: 'var(--text-muted)', fontSize: '0.875rem' }}>
                        📆 {new Date(Date.now() - parseInt(dateRange) * 24 * 60 * 60 * 1000).toLocaleDateString()} - {new Date().toLocaleDateString()}
                    </div>
                </div>
            </div>

            {/* Métricas Principales */}
            <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
                gap: '1.5rem',
                marginBottom: '2rem',
            }}>
                {[
                    { label: 'Tiempo Promedio de Primera Respuesta', value: responseMetrics.avgFirstResponse, icon: '⏱️', gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
                    { label: 'Tiempo Promedio de Resolución', value: responseMetrics.avgResolution, icon: '✅', gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
                    { label: 'Tasa de Satisfacción', value: responseMetrics.satisfactionRate, icon: '😊', gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' },
                    { label: 'Cumplimiento de SLA', value: responseMetrics.slaCompliance, icon: '🎯', gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)' },
                ].map((metric, index) => (
                    <div key={index} className="card" style={{
                        padding: '1.5rem',
                        borderLeft: '4px solid transparent',
                        borderImage: metric.gradient,
                        borderImageSlice: 1,
                    }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '0.75rem' }}>
                            <div style={{
                                width: '48px',
                                height: '48px',
                                borderRadius: '12px',
                                background: metric.gradient,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '1.5rem',
                            }}>
                                {metric.icon}
                            </div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>
                                    {metric.label}
                                </div>
                                <div style={{ fontSize: '1.75rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                    {metric.value}
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* Distribución por Estado y Prioridad */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '1.5rem', marginBottom: '2rem' }}>
                {/* Tickets por Estado */}
                <div className="card">
                    <h3 style={{ marginBottom: '1.5rem', fontSize: '1.2rem', fontWeight: 700 }}>
                        📊 Tickets por Estado
                    </h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                        {ticketsByStatus.map((item, index) => (
                            <div key={index}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.5rem' }}>
                                    <span style={{ fontSize: '0.9rem', fontWeight: 600 }}>{item.status}</span>
                                    <span style={{ fontSize: '0.9rem', fontWeight: 700, color: item.color }}>
                                        {item.count} ({item.percentage}%)
                                    </span>
                                </div>
                                <div style={{
                                    height: '8px',
                                    background: 'var(--glass-bg)',
                                    borderRadius: '999px',
                                    overflow: 'hidden',
                                }}>
                                    <div style={{
                                        height: '100%',
                                        width: `${item.percentage}%`,
                                        background: item.color,
                                        transition: 'width 0.3s ease',
                                    }} />
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Tickets por Prioridad */}
                <div className="card">
                    <h3 style={{ marginBottom: '1.5rem', fontSize: '1.2rem', fontWeight: 700 }}>
                        🚦 Tickets por Prioridad
                    </h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                        {ticketsByPriority.map((item, index) => (
                            <div key={index} style={{
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                                padding: '1rem',
                                background: 'var(--glass-bg)',
                                borderRadius: '8px',
                                borderLeft: `4px solid ${item.color}`,
                            }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                                    <span style={{ fontSize: '1.5rem' }}>{item.emoji}</span>
                                    <span style={{ fontSize: '0.95rem', fontWeight: 600 }}>{item.priority}</span>
                                </div>
                                <span style={{ fontSize: '1.5rem', fontWeight: 700, color: item.color }}>
                                    {item.count}
                                </span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Top Clientes por Tickets */}
            <div className="card">
                <h3 style={{ marginBottom: '1.5rem', fontSize: '1.2rem', fontWeight: 700 }}>
                    👥 Clientes con Más Tickets
                </h3>
                <div className="table-container">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Cliente</th>
                                <th>Total Tickets</th>
                                <th>Resueltos</th>
                                <th>Tasa de Resolución</th>
                                <th>Tendencia</th>
                            </tr>
                        </thead>
                        <tbody>
                            {topClients.map((client, index) => {
                                const resolutionRate = (client.resolved / client.tickets) * 100;
                                return (
                                    <tr key={index}>
                                        <td>
                                            <span style={{
                                                display: 'inline-flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                width: '28px',
                                                height: '28px',
                                                borderRadius: '50%',
                                                background: index < 3 ? 'linear-gradient(135deg, #fbbf24, #f59e0b)' : 'var(--glass-bg)',
                                                fontWeight: 700,
                                                fontSize: '0.85rem',
                                            }}>
                                                {index + 1}
                                            </span>
                                        </td>
                                        <td>
                                            <div style={{ fontWeight: 600 }}>{client.name}</div>
                                        </td>
                                        <td>
                                            <span className="badge badge-info">{client.tickets}</span>
                                        </td>
                                        <td>
                                            <span className="badge badge-success">{client.resolved}</span>
                                        </td>
                                        <td>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                                <div style={{
                                                    flex: 1,
                                                    height: '6px',
                                                    background: 'var(--glass-bg)',
                                                    borderRadius: '999px',
                                                    overflow: 'hidden',
                                                    maxWidth: '100px',
                                                }}>
                                                    <div style={{
                                                        height: '100%',
                                                        width: `${resolutionRate}%`,
                                                        background: resolutionRate > 80 ? '#10b981' : resolutionRate > 50 ? '#f59e0b' : '#ef4444',
                                                        transition: 'width 0.3s ease',
                                                    }} />
                                                </div>
                                                <span style={{ fontSize: '0.85rem', fontWeight: 600 }}>
                                                    {resolutionRate.toFixed(0)}%
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <span style={{ fontSize: '1.2rem' }}>
                                                {resolutionRate > 80 ? '📈' : resolutionRate > 50 ? '➡️' : '📉'}
                                            </span>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
}
