// @ts-nocheck
import { useEffect, useState, useRef } from 'react';
import dynamic from 'next/dynamic';

export default function TeamPage() {
  const [activeTab, setActiveTab] = useState('network');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const networkRef = useRef(null);
  const matrixRef = useRef(null);

  useEffect(() => {
    // Charger les données équipe
    loadTeamData();
  }, []);

  useEffect(() => {
    // Initialiser les graphiques quand les données sont chargées et l'onglet actif change
    if (data && !loading) {
      if (activeTab === 'network') {
        initNetworkGraph();
      } else if (activeTab === 'congestion') {
        initCongestionMatrix();
      }
    }
  }, [data, loading, activeTab]);

  const loadTeamData = async () => {
    try {
      console.log('🔄 Chargement des données équipe...');
      const response = await fetch('/team-visualization-data.json');
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      const jsonData = await response.json();
      console.log('✅ Données chargées:', Object.keys(jsonData));
      setData(jsonData);
    } catch (err) {
      console.error('❌ Erreur chargement données:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const initNetworkGraph = () => {
    if (!data?.network || !networkRef.current) return;

    console.log('📊 Initialisation graphe réseau...');

    // Import dynamique pour éviter les erreurs SSR
    import('cytoscape').then((cytoscape) => {
      import('cytoscape-cose-bilkent').then(() => {
        const cy = cytoscape.default({
          container: networkRef.current,
          elements: data.network,
          style: [
            {
              selector: 'node[type="technology"]',
              style: {
                'background-color': 'data(color)',
                'label': 'data(label)',
                'width': function (ele) {
                  const coverage = ele.data('coverage') || 0;
                  return Math.max(30, 30 + coverage * 8);
                },
                'height': function (ele) {
                  const coverage = ele.data('coverage') || 0;
                  return Math.max(30, 30 + coverage * 8);
                },
                'font-size': '12px',
                'text-valign': 'center',
                'text-halign': 'center',
                color: '#ffffff',
                'text-outline-color': '#1a4d3a',
                'text-outline-width': '2px',
              },
            },
            {
              selector: 'node[type="member"]',
              style: {
                'background-color': '#88ff88',
                'label': 'data(label)',
                'width': function (ele) {
                  const availability = ele.data('availability') || 0;
                  return Math.max(25, 25 + availability / 3);
                },
                'height': function (ele) {
                  const availability = ele.data('availability') || 0;
                  return Math.max(25, 25 + availability / 3);
                },
                'font-size': '10px',
                'text-valign': 'center',
                'text-halign': 'center',
                color: '#1a4d3a',
                'text-outline-color': '#ffffff',
                'text-outline-width': '1px',
              },
            },
            {
              selector: 'edge',
              style: {
                width: function (ele) {
                  return 1 + (ele.data('weight') || 0.5);
                },
                'line-color': '#4ade80',
                'target-arrow-color': '#4ade80',
                'target-arrow-shape': 'triangle',
                'curve-style': 'bezier',
              },
            },
          ],
          layout: {
            name: 'cose-bilkent',
            animate: true,
            animationDuration: 1000,
            nodeRepulsion: 4500,
            idealEdgeLength: 100,
            edgeElasticity: 0.45,
          },
        });

        // Gestionnaire de clics
        cy.on('tap', 'node', function (evt) {
          const node = evt.target;
          const nodeData = node.data();
          let tooltip = '';

          if (nodeData.type === 'technology') {
            tooltip =
              `${nodeData.label}\n` +
              `Ring: ${nodeData.ring}\n` +
              `Couverture: ${nodeData.coverage} personne(s)\n` +
              `Impact: ${nodeData.businessImpact}\n` +
              `Gap: ${nodeData.skillGap}`;
          } else {
            tooltip =
              `${nodeData.label}\n` +
              `Disponibilité: ${nodeData.availability}%` +
              (nodeData.role ? `\nRôle: ${nodeData.role}` : '');
          }

          alert(tooltip);
        });

        console.log('✅ Graphe réseau initialisé');
      });
    });
  };

  const initCongestionMatrix = () => {
    if (!data?.congestionMatrix || !matrixRef.current) return;

    console.log('📈 Initialisation matrice congestion...');

    // Import dynamique pour éviter les erreurs SSR
    import('echarts-for-react').then(() => {
      import('echarts').then((echarts) => {
        const techs = data.congestionMatrix.map((r) => r.technology);
        const members =
          data.congestionMatrix[0]?.members.map((m) => m.fullName || m.member) || [];

        const scatterData = [];
        data.congestionMatrix.forEach((row, i) => {
          row.members.forEach((member, j) => {
            scatterData.push([j, i, member.availability, member]);
          });
        });

        const chart = echarts.default.init(matrixRef.current);
        const option = {
          title: {
            text: 'Disponibilité des Technologies Core',
            left: 'center',
            textStyle: { color: '#e0e0e0' },
          },
          tooltip: {
            formatter: function (params) {
              if (params.data && params.data[3]) {
                const member = params.data[3];
                return (
                  `${member.fullName || member.member}<br/>` +
                  `Technologie: ${techs[params.data[1]]}<br/>` +
                  `Disponibilité: ${params.data[2]}%`
                );
              }
            },
          },
          grid: {
            left: '10%',
            right: '10%',
            top: '15%',
            bottom: '15%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: members,
            axisLabel: {
              color: '#e0e0e0',
              rotate: 45,
            },
          },
          yAxis: {
            type: 'category',
            data: techs,
            axisLabel: { color: '#e0e0e0' },
          },
          visualMap: {
            min: 0,
            max: 100,
            dimension: 2,
            orient: 'horizontal',
            left: 'center',
            top: 'top',
            text: ['Élevé', 'Faible'],
            textStyle: { color: '#e0e0e0' },
            inRange: {
              color: ['#ff4444', '#ff8800', '#4488ff', '#88ff88'],
            },
            outOfRange: {
              color: '#444444',
            },
          },
          series: [
            {
              name: 'Disponibilité',
              type: 'scatter',
              data: scatterData,
              symbolSize: function (data) {
                return 15 + (data[2] || 0) / 2;
              },
            },
          ],
        };

        chart.setOption(option);
        console.log('✅ Matrice congestion initialisée');
      });
    });
  };

  const renderGenesisTeam = () => {
    if (!data?.genesisTeam) return <div>Données équipe non disponibles</div>;

    const genesis = data.genesisTeam;
    return (
      <div>
        <h2 style={{ marginBottom: '20px' }}>Équipe de Genèse MVP</h2>
        <div
          style={{
            background: 'rgba(74, 222, 128, 0.1)',
            padding: '20px',
            borderRadius: '8px',
            marginBottom: '20px',
          }}
        >
          <h3 style={{ color: '#4ade80', marginBottom: '10px' }}>Critères de Sélection</h3>
          <ul style={{ marginLeft: '20px' }}>
            <li>Disponibilité ≥ {genesis.minAvailability}%</li>
            <li>Couverture technologique ≥ {genesis.minCoverage} technologies</li>
            <li>Taille équipe optimale: {genesis.targetTeamSize} membres</li>
          </ul>
        </div>

        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
            gap: '20px',
            marginTop: '20px',
          }}
        >
          {genesis.selectedMembers.map((member) => (
            <div
              key={member.member}
              style={{
                background: 'rgba(26, 77, 58, 0.5)',
                borderRadius: '8px',
                padding: '20px',
                border: '1px solid rgba(74, 222, 128, 0.3)',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  marginBottom: '10px',
                }}
              >
                <div>
                  <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#4ade80' }}>
                    {member.fullName || member.member}
                  </div>
                  <div style={{ fontSize: '12px', color: '#a0a0a0', marginTop: '4px' }}>
                    {member.role || ''} • {member.seniority} • {member.coverage} technologie(s)
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '24px', color: '#4ade80', fontWeight: 'bold' }}>
                    {member.availability}%
                  </div>
                  <div style={{ fontSize: '12px', color: '#a0a0a0' }}>Disponibilité</div>
                </div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginTop: '10px' }}>
                {member.skills.slice(0, 8).map((skill) => (
                  <span
                    key={skill}
                    style={{
                      background: 'rgba(74, 222, 128, 0.2)',
                      color: '#4ade80',
                      padding: '4px 8px',
                      borderRadius: '4px',
                      fontSize: '12px',
                    }}
                  >
                    {skill}
                  </span>
                ))}
                {member.skills.length > 8 && (
                  <span
                    style={{
                      background: 'rgba(74, 222, 128, 0.2)',
                      color: '#4ade80',
                      padding: '4px 8px',
                      borderRadius: '4px',
                      fontSize: '12px',
                    }}
                  >
                    +{member.skills.length - 8}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div
        style={{
          width: '100vw',
          height: '100vh',
          background: '#1a4d3a',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          position: 'fixed',
          top: 0,
          left: 0,
          zIndex: 9999,
        }}
      >
        <div style={{ color: 'white', fontSize: '18px' }}>
          Chargement des visualisations équipe...
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        style={{
          width: '100vw',
          height: '100vh',
          background: '#1a4d3a',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          position: 'fixed',
          top: 0,
          left: 0,
          zIndex: 9999,
        }}
      >
        <div style={{ color: 'white', fontSize: '18px' }}>
          Erreur: {error}
        </div>
      </div>
    );
  }

  return (
    <div
      style={{
        width: '100vw',
        minHeight: '100vh',
        background: '#1a4d3a',
        fontFamily:
          '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif',
        color: '#e0e0e0',
        padding: '20px',
      }}
    >
      <div style={{ maxWidth: '1400px', margin: '0 auto' }}>
        <header
          style={{
            textAlign: 'center',
            marginBottom: '30px',
            padding: '20px',
            background: 'rgba(26, 77, 58, 0.5)',
            borderRadius: '8px',
          }}
        >
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '10px',
            }}
          >
            <a
              href="/"
              style={{
                color: '#4ade80',
                textDecoration: 'none',
                fontSize: '18px',
                fontWeight: 'bold',
              }}
            >
              ← Retour au Radar
            </a>
            <div></div>
          </div>
          <h1 style={{ color: '#4ade80', marginBottom: '10px' }}>👥 Équipe & Technologies</h1>
          <p>Visualisation des compétences et identification de l'équipe de genèse MVP</p>
        </header>

        <div style={{ display: 'flex', gap: '10px', marginBottom: '20px', flexWrap: 'wrap' }}>
          <button
            onClick={() => setActiveTab('network')}
            style={{
              padding: '12px 24px',
              background: activeTab === 'network' ? '#4ade80' : 'rgba(74, 222, 128, 0.2)',
              border: '1px solid #4ade80',
              borderRadius: '6px',
              color: activeTab === 'network' ? '#1a4d3a' : '#4ade80',
              cursor: 'pointer',
              fontSize: '14px',
              transition: 'all 0.3s ease',
              fontWeight: activeTab === 'network' ? 'bold' : 'normal',
            }}
          >
            Graphe Réseau
          </button>
          <button
            onClick={() => setActiveTab('congestion')}
            style={{
              padding: '12px 24px',
              background: activeTab === 'congestion' ? '#4ade80' : 'rgba(74, 222, 128, 0.2)',
              border: '1px solid #4ade80',
              borderRadius: '6px',
              color: activeTab === 'congestion' ? '#1a4d3a' : '#4ade80',
              cursor: 'pointer',
              fontSize: '14px',
              transition: 'all 0.3s ease',
              fontWeight: activeTab === 'congestion' ? 'bold' : 'normal',
            }}
          >
            Matrice Congestion
          </button>
          <button
            onClick={() => setActiveTab('genesis')}
            style={{
              padding: '12px 24px',
              background: activeTab === 'genesis' ? '#4ade80' : 'rgba(74, 222, 128, 0.2)',
              border: '1px solid #4ade80',
              borderRadius: '6px',
              color: activeTab === 'genesis' ? '#1a4d3a' : '#4ade80',
              cursor: 'pointer',
              fontSize: '14px',
              transition: 'all 0.3s ease',
              fontWeight: activeTab === 'genesis' ? 'bold' : 'normal',
            }}
          >
            Équipe Genèse MVP
          </button>
        </div>

        {activeTab === 'network' && (
          <div
            style={{
              background: 'rgba(26, 77, 58, 0.3)',
              padding: '20px',
              borderRadius: '8px',
              marginBottom: '20px',
            }}
          >
            <h2 style={{ marginBottom: '20px' }}>Graphe Réseau - Technologies et Compétences</h2>
            <div
              style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: '15px',
                marginBottom: '20px',
                padding: '15px',
                background: 'rgba(0, 0, 0, 0.2)',
                borderRadius: '6px',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '14px' }}>
                <div style={{ width: '16px', height: '16px', borderRadius: '50%', background: '#ff4444' }}></div>
                <span>Technologies Core</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '14px' }}>
                <div style={{ width: '16px', height: '16px', borderRadius: '50%', background: '#ff8800' }}></div>
                <span>Technologies Avancées</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '14px' }}>
                <div style={{ width: '16px', height: '16px', borderRadius: '50%', background: '#4488ff' }}></div>
                <span>Technologies Utilitaires</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '14px' }}>
                <div style={{ width: '16px', height: '16px', borderRadius: '50%', background: '#88ff88' }}></div>
                <span>Membres Équipe</span>
              </div>
            </div>
            <div
              ref={networkRef}
              style={{
                width: '100%',
                height: '600px',
                border: '1px solid rgba(74, 222, 128, 0.3)',
                borderRadius: '8px',
              }}
            ></div>
          </div>
        )}

        {activeTab === 'congestion' && (
          <div
            style={{
              background: 'rgba(26, 77, 58, 0.3)',
              padding: '20px',
              borderRadius: '8px',
              marginBottom: '20px',
            }}
          >
            <h2 style={{ marginBottom: '20px' }}>Matrice de Congestion - Technologies Core</h2>
            <div
              ref={matrixRef}
              style={{
                width: '100%',
                height: '600px',
                border: '1px solid rgba(74, 222, 128, 0.3)',
                borderRadius: '8px',
              }}
            ></div>
          </div>
        )}

        {activeTab === 'genesis' && (
          <div
            style={{
              background: 'rgba(26, 77, 58, 0.3)',
              padding: '20px',
              borderRadius: '8px',
              marginBottom: '20px',
            }}
          >
            {renderGenesisTeam()}
          </div>
        )}
      </div>
    </div>
  );
}
