import React from 'react';
import { User, Users } from 'lucide-react';

interface OrgNode {
  id: string;
  name: string;
  title: string;
  email?: string;
  reports?: OrgNode[];
}

interface OrgChartProps {
  data?: OrgNode;
}

const OrgNodeComponent: React.FC<{ node: OrgNode; level: number }> = ({ node, level }) => {
  const hasReports = node.reports && node.reports.length > 0;

  return (
    <div className="flex flex-col items-center">
      <div className={`bg-white border-2 rounded-lg p-4 shadow-md min-w-[200px] ${
        level === 0 ? 'border-blue-500' : 'border-gray-300'
      }`}>
        <div className="flex items-center gap-2 mb-2">
          <User className="w-5 h-5 text-blue-600" />
          <h3 className="font-bold">{node.name}</h3>
        </div>
        <p className="text-sm text-gray-600 mb-1">{node.title}</p>
        {node.email && (
          <p className="text-xs text-gray-500 truncate">{node.email}</p>
        )}
        {hasReports && (
          <div className="mt-2 flex items-center gap-1 text-xs text-gray-500">
            <Users className="w-4 h-4" />
            <span>{node.reports!.length} direct report{node.reports!.length !== 1 ? 's' : ''}</span>
          </div>
        )}
      </div>

      {hasReports && (
        <div className="relative">
          <div className="h-8 w-0.5 bg-gray-300 mx-auto" />
          <div className="flex gap-8 relative">
            {node.reports!.map((report, idx) => (
              <div key={report.id} className="relative">
                {idx > 0 && (
                  <div className="absolute top-0 left-0 h-0.5 bg-gray-300" style={{ width: '100%' }} />
                )}
                <OrgNodeComponent node={report} level={level + 1} />
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export const OrgChart: React.FC<OrgChartProps> = ({ data }) => {
  if (!data) {
    return (
      <div className="p-6 bg-white rounded-lg shadow text-center">
        <p className="text-gray-500">No organizational chart data available</p>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 rounded-lg shadow overflow-auto">
      <h2 className="text-2xl font-bold mb-6 text-center">Organization Chart</h2>
      <div className="flex justify-center">
        <OrgNodeComponent node={data} level={0} />
      </div>
    </div>
  );
};
