import { useEffect, useState } from 'react';
import { BrandMark } from '../../../shared/components/BrandMark';
import { useViewport } from '../../../shared/hooks/useViewport';
import { getCurrentUser, getCurrentUserDisplay } from '../../auth/services/sessionService';
import { listContactProfiles } from '../../chat/services/contactProfileService';
import { MassMessagePanel } from '../../management/components/MassMessagePanel';
import { getAccessOptions } from '../../management/services/adminAccessService';
import { HomeSidebar } from '../components/HomeSidebar';
import { sidebarItems } from '../services/homeMocks';

function getUserSpecialties(user) {
  const normalize = (area) => {
    if (!area) return null;
    if (typeof area === 'string') return area;
    return area.nome || area.name || null;
  };

  const areas = Array.isArray(user?.areas) ? user.areas.map(normalize).filter(Boolean) : [];
  const primary = normalize(user?.areaPrincipal);
  return primary && !areas.includes(primary) ? [primary, ...areas] : areas;
}

export function AgentMassMessagePage() {
  const { isDesktop, isMobile } = useViewport();
  const userDisplay = getCurrentUserDisplay();
  const currentUser = getCurrentUser();
  const specialties = getUserSpecialties(currentUser);
  const [areas, setAreas] = useState([]);
  const [contactCount, setContactCount] = useState(0);

  useEffect(() => {
    let isMounted = true;

    getAccessOptions()
      .then((options) => {
        if (isMounted) setAreas(options.areas || []);
      })
      .catch(() => {
        if (isMounted) setAreas([]);
      });

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    listContactProfiles()
      .then((items) => {
        if (isMounted) setContactCount(Array.isArray(items) ? items.length : 0);
      })
      .catch(() => {
        if (isMounted) setContactCount(0);
      });

    return () => {
      isMounted = false;
    };
  }, []);

  const sidebarWithContactCount = sidebarItems.map((item) =>
    item.id === 'contacts' ? { ...item, count: contactCount } : item,
  );

  return (
    <main style={{ minHeight: '100vh', padding: '1.5rem' }}>
      <section
        style={{
          width: 'min(1680px, calc(100vw - 3rem))',
          margin: '0 auto',
          background: 'var(--color-surface-strong)',
          borderRadius: '24px',
          boxShadow: 'var(--shadow-lg)',
          padding: '1.5rem',
          display: 'grid',
          gap: '1.5rem',
        }}
      >
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: isDesktop ? 'minmax(340px, 380px) minmax(0, 1fr)' : '1fr',
            gap: '1.5rem',
            alignItems: 'start',
          }}
        >
          <div style={{ display: 'grid', gap: '1.25rem' }}>
            <div
              style={{
                background: '#fff',
                border: '1px solid var(--color-border)',
                borderRadius: '20px',
                padding: '1.5rem',
              }}
            >
              <BrandMark size="lg" />
            </div>
            <HomeSidebar items={sidebarWithContactCount} activeItem="mass-message" isMobile={!isDesktop} />
          </div>

          <div style={{ display: 'grid', gap: '1.25rem', minWidth: 0 }}>
            <header
              style={{
                display: 'grid',
                gridTemplateColumns: isMobile ? '1fr' : 'minmax(0, 1fr) auto',
                gap: '1rem',
                alignItems: 'center',
              }}
            >
              <div
                style={{
                  padding: '1.1rem 1.25rem',
                  borderRadius: '16px',
                  background: '#fff',
                  border: '1px solid var(--color-border)',
                }}
              >
                <h1 style={{ margin: 0, fontSize: '1.65rem' }}>Disparo em massa</h1>
                <p style={{ margin: '0.45rem 0 0', color: 'var(--color-text-soft)' }}>
                  Envie templates aprovados para contatos da agenda ou numeros informados manualmente.
                </p>
              </div>

              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.9rem',
                  justifySelf: isMobile ? 'stretch' : 'end',
                  justifyContent: isMobile ? 'space-between' : 'flex-end',
                  padding: '0.85rem 1rem',
                  borderRadius: '16px',
                  background: '#fff',
                  border: '1px solid var(--color-border)',
                }}
              >
                <div style={{ textAlign: 'right' }}>
                  <strong style={{ display: 'block' }}>{userDisplay.name}</strong>
                  <span style={{ color: 'var(--color-text-soft)', fontSize: '0.92rem' }}>
                    Atendimento omnichannel
                  </span>
                </div>
                <div
                  aria-hidden="true"
                  style={{
                    width: 48,
                    height: 48,
                    borderRadius: '12px',
                    display: 'grid',
                    placeItems: 'center',
                    background: 'linear-gradient(135deg, var(--color-accent), var(--color-primary))',
                    color: '#fff',
                    fontWeight: 800,
                  }}
                >
                  {userDisplay.initials}
                </div>
              </div>
            </header>

            <MassMessagePanel
              areas={areas}
              mode="agent"
              managedAreaNames={specialties}
              isMobile={isMobile}
            />
          </div>
        </div>
      </section>
    </main>
  );
}
