const { useState, useEffect } = React;

function DashboardShell({ title, subtitle, loading, error, children }) {
  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:800, fontSize:24, color:BRAND.text.primary, margin:'0 0 4px' }}>
          {title}
        </h2>
        <p style={{ fontSize:14, color:BRAND.text.muted, margin:0 }}>{subtitle}</p>
      </div>

      {loading ? (
        <Card style={{ padding:24 }}>
          <div style={{ fontSize:13, color:BRAND.text.muted }}>Cargando datos reales del dashboard...</div>
        </Card>
      ) : error ? (
        <Card style={{ padding:24 }}>
          <div style={{ fontSize:13, color:BRAND.red.main }}>{error}</div>
        </Card>
      ) : children}
    </div>
  );
}

function EmptyCard({ title, detail, actionLabel = null, onAction = null }) {
  return (
    <Card style={{ padding:24 }}>
      <div style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, marginBottom:8 }}>
        {title}
      </div>
      <div style={{ fontSize:13, color:BRAND.text.muted, lineHeight:1.6 }}>{detail}</div>
      {actionLabel && onAction && (
        <button onClick={onAction} style={{ marginTop:14, fontSize:12, color:BRAND.green.main, background:'none', border:'none', cursor:'pointer', fontWeight:600 }}>
          {actionLabel}
        </button>
      )}
    </Card>
  );
}

function useDashboardData(role, currentUser) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let active = true;
    const query = role === 'operator' && currentUser?.id
      ? `/api/dashboard?role=OPERATOR&userId=${currentUser.id}`
      : role === 'supervisor'
        ? '/api/dashboard?role=SUPERVISOR'
        : '/api/dashboard?role=ADMIN';

    setLoading(true);
    setError('');

    apiCall(query)
      .then((response) => {
        if (!active) return;
        if (response?.error) {
          setError(response.error);
          setData(null);
          return;
        }
        setData(response);
      })
      .catch((requestError) => {
        if (!active) return;
        console.error('Error cargando dashboard:', requestError);
        setError('No fue posible cargar los datos del dashboard.');
        setData(null);
      })
      .finally(() => {
        if (active) setLoading(false);
      });

    return () => {
      active = false;
    };
  }, [role, currentUser?.id]);

  return { data, loading, error };
}

function OperatorDashboard({ onNavigate, currentUser }) {
  const isStacked = useViewportMatch(1100);
  const isCompact = useViewportMatch(720);
  const { data, loading, error } = useDashboardData('operator', currentUser);
  const firstName = currentUser?.name ? currentUser.name.split(' ')[0] : 'Usuario';
  const enrollments = data?.enrollments || [];
  const certificates = data?.certificates || [];
  const completed = enrollments.filter((item) => item.status === 'COMPLETED').length;
  const inProgress = enrollments.filter((item) => item.status === 'IN_PROGRESS').length;
  const totalHours = enrollments.reduce((sum, item) => sum + Number(item.course?.durationHours || 0), 0);
  const averageGrade = enrollments.filter((item) => item.grade !== null);
  const averageValue = averageGrade.length
    ? Math.round(averageGrade.reduce((sum, item) => sum + Number(item.grade || 0), 0) / averageGrade.length)
    : 0;
  const recentCourses = enrollments.slice(0, 4);

  return (
    <DashboardShell
      title={`Bienvenido, ${firstName}`}
      subtitle="Este panel refleja cursos, progreso y certificaciones almacenados en la plataforma."
      loading={loading}
      error={error}
    >
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:20 }}>
        <StatCard label="Cursos completados" value={completed} sub={`${enrollments.length} inscripciones registradas`} color={BRAND.green.main} icon="check"/>
        <StatCard label="En progreso" value={inProgress} sub="avance real de tu cuenta" color={BRAND.amber.main} icon="play"/>
        <StatCard label="Horas completadas" value={`${totalHours}h`} sub="según cursos inscritos" color={BRAND.blue.main} icon="clock"/>
        <StatCard label="Promedio" value={averageValue} sub="evaluaciones registradas" color={BRAND.red.main} icon="star"/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:isStacked ? '1fr' : 'minmax(0, 1fr) 340px', gap:20 }}>
        <Card style={{ padding:24 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, margin:0 }}>Mis cursos</h3>
            <button onClick={() => onNavigate('courses')} style={{ fontSize:12, color:BRAND.green.main, background:'none', border:'none', cursor:'pointer', fontWeight:600 }}>Ver catálogo →</button>
          </div>
          {recentCourses.length === 0 ? (
            <div style={{ fontSize:13, color:BRAND.text.muted }}>Aún no tienes cursos inscritos o progreso registrado.</div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
              {recentCourses.map((item) => (
                <div key={item.id} style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'12px 14px' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', gap:12, marginBottom:6 }}>
                    <div>
                      <div style={{ fontSize:13, fontWeight:700, color:BRAND.text.primary }}>{item.course?.title || `Curso ${item.courseId}`}</div>
                      <div style={{ fontSize:11, color:BRAND.text.light }}>{item.course?.code || 'Sin código'} · {item.status}</div>
                    </div>
                    <div style={{ fontSize:12, fontWeight:700, color:BRAND.green.main }}>{item.progress}%</div>
                  </div>
                  <ProgressBar value={item.progress} color={BRAND.green.main} height={6}/>
                </div>
              ))}
            </div>
          )}
        </Card>

        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <EmptyCard
            title="Certificados"
            detail={certificates.length === 0 ? 'Todavía no hay certificados emitidos para esta cuenta.' : `${certificates.length} certificados emitidos.`}
          />
          <EmptyCard
            title="Actividad"
            detail={enrollments.length === 0 ? 'Cuando uses la plataforma y se registren avances, aparecerán aquí.' : 'La plataforma ya está mostrando tu actividad real actual.'}
          />
        </div>
      </div>
    </DashboardShell>
  );
}

function AdminDashboard({ onNavigate, currentUser }) {
  const isStacked = useViewportMatch(1100);
  const isCompact = useViewportMatch(720);
  const { data, loading, error } = useDashboardData('admin', currentUser);
  const summary = data?.summary || { totalUsers: 0, totalCourses: 0, totalCertificates: 0, activeEnrollments: 0 };
  const recentUsers = data?.recentUsers || [];

  return (
    <DashboardShell
      title="Panel de Administración"
      subtitle="Estas métricas ya salen de usuarios, cursos, inscripciones y certificados reales."
      loading={loading}
      error={error}
    >
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:20 }}>
        <StatCard label="Usuarios activos" value={summary.totalUsers} sub="usuarios registrados" color={BRAND.green.main} icon="user"/>
        <StatCard label="Cursos publicados" value={summary.totalCourses} sub="catálogo en base de datos" color={BRAND.blue.main} icon="book"/>
        <StatCard label="Certificados emitidos" value={summary.totalCertificates} sub="datos reales" color={BRAND.amber.main} icon="award"/>
        <StatCard label="Inscripciones activas" value={summary.activeEnrollments} sub="sin completar" color={BRAND.red.main} icon="bar-chart"/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:isStacked ? '1fr' : '300px minmax(0, 1fr)', gap:20, marginBottom:20 }}>
        <EmptyCard
          title="Cumplimiento"
          detail="Las métricas agregadas pueden crecer en cuanto existan inscripciones y progreso real."
        />

        <Card style={{ padding:24 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, margin:0 }}>Usuarios recientes</h3>
            <button onClick={() => onNavigate('users')} style={{ fontSize:12, color:BRAND.green.main, background:'none', border:'none', cursor:'pointer', fontWeight:600 }}>Gestionar usuarios →</button>
          </div>
          {recentUsers.length === 0 ? (
            <div style={{ fontSize:13, color:BRAND.text.muted }}>No hay usuarios recientes para mostrar.</div>
          ) : (
            <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', minWidth:520, borderCollapse:'collapse' }}>
              <thead>
                <tr style={{ borderBottom:`1.5px solid ${BRAND.border}` }}>
                  {['Nombre','Correo','Rol','Nivel'].map((header) => (
                    <th key={header} style={{ textAlign:'left', fontSize:11, fontWeight:500, color:BRAND.text.light, padding:'0 8px 10px', letterSpacing:'0.04em', textTransform:'uppercase' }}>{header}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {recentUsers.map((user) => (
                  <tr key={user.id} style={{ borderBottom:`1px solid ${BRAND.border}` }}>
                    <td style={{ padding:'10px 8px', fontSize:13, fontWeight:600, color:BRAND.text.primary }}>{user.name}</td>
                    <td style={{ padding:'10px 8px', fontSize:12, color:BRAND.text.muted }}>{user.email}</td>
                    <td style={{ padding:'10px 8px', fontSize:12, color:BRAND.text.muted }}>{user.role}</td>
                    <td style={{ padding:'10px 8px', fontSize:12, color:BRAND.text.muted }}>{user.level ?? '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
          )}
        </Card>
      </div>
    </DashboardShell>
  );
}

function SupervisorDashboard({ onNavigate, currentUser }) {
  const isStacked = useViewportMatch(1100);
  const isCompact = useViewportMatch(720);
  const { data, loading, error } = useDashboardData('supervisor', currentUser);
  const summary = data?.summary || { totalUsers: 0, totalCourses: 0, totalCertificates: 0, activeEnrollments: 0 };
  const team = data?.team || [];

  return (
    <DashboardShell
      title="Dashboard de Supervisión"
      subtitle="El seguimiento del equipo se alimenta desde usuarios e inscripciones reales."
      loading={loading}
      error={error}
    >
      <div style={{ display:'grid', gridTemplateColumns:isCompact ? '1fr' : 'repeat(auto-fit, minmax(190px, 1fr))', gap:16, marginBottom:20 }}>
        <StatCard label="Operadores" value={team.length} sub="equipo registrado" color={BRAND.green.main} icon="user"/>
        <StatCard label="Cursos publicados" value={summary.totalCourses} sub="catálogo vigente" color={BRAND.blue.main} icon="book"/>
        <StatCard label="Inscripciones activas" value={summary.activeEnrollments} sub="seguimiento en curso" color={BRAND.amber.main} icon="trending-up"/>
        <StatCard label="Certificados" value={summary.totalCertificates} sub="emitidos en plataforma" color={BRAND.red.main} icon="award"/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:isStacked ? '1fr' : '320px minmax(0, 1fr)', gap:20 }}>
        <EmptyCard
          title="Cumplimiento del equipo"
          detail="Las métricas de cumplimiento se irán poblando cuando cada operador tenga inscripciones y progreso real."
        />

        <Card style={{ padding:24 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ fontFamily:'Space Grotesk,sans-serif', fontWeight:700, fontSize:15, color:BRAND.text.primary, margin:0 }}>Equipo registrado</h3>
            <button onClick={() => onNavigate('compliance')} style={{ fontSize:12, color:BRAND.green.main, background:'none', border:'none', cursor:'pointer', fontWeight:600 }}>Ver cumplimiento →</button>
          </div>
          {team.length === 0 ? (
            <div style={{ fontSize:13, color:BRAND.text.muted }}>No hay operadores asignados todavía.</div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {team.map((member) => (
                <div key={member.id} style={{ border:`1.5px solid ${BRAND.border}`, borderRadius:10, padding:'12px 14px', display:'flex', justifyContent:'space-between', alignItems:'center', gap:12 }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:700, color:BRAND.text.primary }}>{member.name}</div>
                    <div style={{ fontSize:11, color:BRAND.text.light }}>{member.email}</div>
                  </div>
                  <div style={{ fontSize:12, color:BRAND.text.muted }}>
                    {member.level ? `Nivel ${member.level}` : 'Sin nivel'}
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
    </DashboardShell>
  );
}

Object.assign(window, { OperatorDashboard, AdminDashboard, SupervisorDashboard });
