import { useState, useEffect } from 'react';
import './styles.css';

export default function OrgChart() {
  const [employees, setEmployees] = useState<any[]>([]);
  const [orgTree, setOrgTree] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadOrgData();
  }, []);

  const loadOrgData = async () => {
    try {
      setLoading(true);
      const response = await (window as any).mcp?.callTool('rippling_list_employees', { limit: 500 });
      
      if (response?.employees) {
        setEmployees(response.employees);
        buildOrgTree(response.employees);
      } else {
        const sample = getSampleEmployees();
        setEmployees(sample);
        buildOrgTree(sample);
      }
    } catch (err) {
      console.error('Error loading org data:', err);
      setError(err instanceof Error ? err.message : 'Failed to load data');
      const sample = getSampleEmployees();
      setEmployees(sample);
      buildOrgTree(sample);
    } finally {
      setLoading(false);
    }
  };

  const buildOrgTree = (emps: any[]) => {
    const empMap = new Map(emps.map(e => [e.id, { ...e, reports: [] }]));
    let root = null;

    emps.forEach(emp => {
      const node = empMap.get(emp.id);
      if (emp.managerId && empMap.has(emp.managerId)) {
        empMap.get(emp.managerId).reports.push(node);
      } else if (!root) {
        root = node;
      }
    });

    setOrgTree(root || empMap.values().next().value);
  };

  const getSampleEmployees = () => [
    { id: '1', firstName: 'Sarah', lastName: 'CEO', title: 'Chief Executive Officer', department: 'Executive', managerId: null },
    { id: '2', firstName: 'John', lastName: 'VP Eng', title: 'VP Engineering', department: 'Engineering', managerId: '1' },
    { id: '3', firstName: 'Jane', lastName: 'VP Sales', title: 'VP Sales', department: 'Sales', managerId: '1' },
    { id: '4', firstName: 'Bob', lastName: 'Engineer', title: 'Senior Engineer', department: 'Engineering', managerId: '2' },
  ];

  const renderNode = (node: any, level: number = 0) => {
    if (!node) return null;

    return (
      <div key={node.id} className="org-node" style={{ marginLeft: `${level * 2}rem` }}>
        <div className="node-card">
          <div className="node-avatar">{node.firstName?.[0]}{node.lastName?.[0]}</div>
          <div className="node-info">
            <h3>{node.firstName} {node.lastName}</h3>
            <p className="node-title">{node.title}</p>
            <p className="node-dept">{node.department}</p>
          </div>
          {node.reports?.length > 0 && (
            <span className="reports-badge">{node.reports.length} reports</span>
          )}
        </div>
        {node.reports?.length > 0 && (
          <div className="reports-container">
            {node.reports.map((report: any) => renderNode(report, level + 1))}
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <div className="container">
        <div className="loading">Loading org chart...</div>
      </div>
    );
  }

  return (
    <div className="container">
      <div className="header">
        <h1>Organization Chart</h1>
        <p className="subtitle">{employees.length} employees in org structure</p>
      </div>

      {error && <div className="error">{error}</div>}

      <div className="org-chart">
        {orgTree ? renderNode(orgTree) : <div className="empty-state">No org data available</div>}
      </div>
    </div>
  );
}
