import React, { useState, useMemo } from 'react';
import { ChevronDown, ChevronRight, Users, Building, User as UserIcon, Plus, Trash2, Edit } from 'lucide-react';
import { User, USER_ROLES } from '../../types';
import { useApp } from '../../context/AppContext';
import { useAuth } from '../../context/AuthContext';
import ContactCard from './ContactCard';

interface OrganizationalTreeProps {
  onUserClick: (user: any) => void;
  onAddDepartment?: (unitId: number) => void;
  onAddUser?: (departmentId: number) => void;
  onDeleteDepartment?: (departmentId: number) => void;
  onEditUser?: (user: User) => void;
  onDeleteUser?: (user: User) => void;
  filteredUsers?: User[]; // Optional prop for filtered users
}

interface OrganizationalUnit {
  id: number;
  name: string;
  code: string;
  departments: OrganizationalDepartment[];
}

interface OrganizationalDepartment {
  id: number;
  name: string;
  description: string;
  total_users: number;
  users: User[];
}

const OrganizationalTree: React.FC<OrganizationalTreeProps> = ({
  onUserClick,
  onAddDepartment,
  onAddUser,
  onDeleteDepartment,
  onEditUser,
  onDeleteUser,
  filteredUsers
}) => {
  const { departments, users, units } = useApp();
  const { hasRole } = useAuth();
  const [expandedUnits, setExpandedUnits] = useState<Set<number>>(new Set());
  const [expandedDepartments, setExpandedDepartments] = useState<Set<number>>(new Set());

  // Use filteredUsers if provided, otherwise use all users
  const usersToDisplay = filteredUsers || users;

  // Group data into organizational structure without department-unit linkage
  const organizationalData = useMemo(() => {
    const unitMap = new Map<number, OrganizationalUnit>();

    // Initialize units
    units.forEach(u => {
      unitMap.set(u.id, {
        id: u.id,
        name: u.name,
        code: u.code,
        departments: []
      });
    });

    // Helper to get or create a department entry under a unit
    const ensureDepartment = (unit: OrganizationalUnit, deptId: number, deptName: string) => {
      let d = unit.departments.find(dd => dd.id === deptId);
      if (!d) {
        const original = departments.find(x => x.id === deptId);
        unit.departments.push({
          id: deptId,
          name: deptName,
          description: original?.description || '',
          total_users: 0,
          users: []
        });
        d = unit.departments[unit.departments.length - 1];
      }
      return d;
    };

    // Add users into units and departments based on their string names
    usersToDisplay.forEach(user => {
      const unit = units.find(u => u.name === user.unit);
      if (!unit) return;
      const unitEntry = unitMap.get(unit.id)!;

      // Find department by name from master list
      const dept = departments.find(d => d.name === user.department);
      if (!dept) return;

      const deptEntry = ensureDepartment(unitEntry, dept.id, dept.name);
      deptEntry.users.push(user);
      deptEntry.total_users += 1;
    });

    // Sort departments within each unit by department order_id from master list
    unitMap.forEach(unit => {
      unit.departments.sort((a, b) => {
        const da = departments.find(d => d.id === a.id)?.order_id ?? 0;
        const db = departments.find(d => d.id === b.id)?.order_id ?? 0;
        return da - db;
      });
    });

    // Sort units by their order_id
    const sortedUnits = Array.from(unitMap.values()).sort((a, b) => {
      const unitA = units.find(u => u.name === a.name);
      const unitB = units.find(u => u.name === b.name);
      if (unitA && unitB) return unitA.order_id - unitB.order_id;
      if (unitA) return -1;
      if (unitB) return 1;
      return a.name.localeCompare(b.name);
    });

    return sortedUnits;
  }, [departments, usersToDisplay, units]);

  const toggleUnit = (unitId: number) => {
    const newExpanded = new Set(expandedUnits);
    if (newExpanded.has(unitId)) {
      newExpanded.delete(unitId);
    } else {
      newExpanded.add(unitId);
    }
    setExpandedUnits(newExpanded);
  };

  const toggleDepartment = (departmentId: number) => {
    const newExpanded = new Set(expandedDepartments);
    if (newExpanded.has(departmentId)) {
      newExpanded.delete(departmentId);
    } else {
      newExpanded.add(departmentId);
    }
    setExpandedDepartments(newExpanded);
  };


  return (
    <div className="space-y-4">
      {organizationalData.map(unit => (
        <div key={unit.id} className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          {/* Unit Header */}
          <div 
            className="flex items-center justify-between p-3 bg-gray-50 hover:bg-gray-100 cursor-pointer border-b"
            onClick={() => toggleUnit(unit.id)}
          >
            <div className="flex items-center space-x-3">
              {expandedUnits.has(unit.id) ? (
                <ChevronDown className="h-5 w-5 text-gray-500" />
              ) : (
                <ChevronRight className="h-5 w-5 text-gray-500" />
              )}
              <Building className="h-5 w-5 text-blue-600" />
              <div>
                <h3 className="font-semibold text-gray-900">{unit.name}</h3>
                <p className="text-sm text-gray-500">{unit.code}</p>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              {hasRole(USER_ROLES.ADMIN) && onAddDepartment && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onAddDepartment(unit.id);
                  }}
                  className="p-1 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                  title="Add New Department"
                >
                  <Plus className="h-4 w-4" />
                </button>
              )}
            </div>
          </div>

          {/* Departments */}
          {expandedUnits.has(unit.id) && (
            <div className="divide-y divide-gray-100">
              {unit.departments.map(department => (
                <div key={department.id}>
                  {/* Department Header */}
                  <div 
                    className="flex items-center justify-between p-2 hover:bg-gray-50 cursor-pointer"
                    onClick={() => toggleDepartment(department.id)}
                  >
                    <div className="flex items-center space-x-3">
                      <div className="ml-6">
                        {expandedDepartments.has(department.id) ? (
                          <ChevronDown className="h-4 w-4 text-gray-400" />
                        ) : (
                          <ChevronRight className="h-4 w-4 text-gray-400" />
                        )}
                      </div>
                      <Users className="h-4 w-4 text-green-600" />
                      <div>
                        <h4 className="font-medium text-gray-800">{department.name}</h4>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      {hasRole(USER_ROLES.ADMIN) && onAddUser && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onAddUser(department.id);
                          }}
                          className="p-1 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                          title="Add New User"
                        >
                          <Plus className="h-4 w-4" />
                        </button>
                      )}
                      {hasRole(USER_ROLES.ADMIN) && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            // TODO: Implement edit department functionality
                            console.log('Edit department:', department.id);
                          }}
                          className="p-1 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                          title="Edit Department"
                        >
                          <Edit className="h-4 w-4" />
                        </button>
                      )}
                      {hasRole(USER_ROLES.ADMIN) && onDeleteDepartment && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onDeleteDepartment(department.id);
                          }}
                          className="p-1 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                          title="Delete Department"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      )}
                    </div>
                  </div>

                  {/* Users */}
                  {expandedDepartments.has(department.id) && (
                    <div className="bg-gray-50">
                      {department.users.length === 0 ? (
                        <div className="p-4 text-center text-gray-500">
                          <UserIcon className="h-8 w-8 mx-auto mb-2 text-gray-300" />
                          <p>No contacts in this department</p>
                        </div>
                      ) : (
                         <div className="pl-14 pr-3 py-2">
                           <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2">
                             {department.users.map(user => (
                               <ContactCard
                                 key={user.id}
                                 user={user}
                                 onClick={() => onUserClick(user)}
                                 onCreateChild={onEditUser}
                                 onDelete={onDeleteUser}
                                 viewMode="organizational"
                                 showActions={true}
                                 isAdmin={hasRole(USER_ROLES.ADMIN)}
                                 isSuperAdmin={hasRole(USER_ROLES.SUPER_ADMIN)}
                               />
                             ))}
                           </div>
                         </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      ))}

      {organizationalData.length === 0 && (
        <div className="text-center py-12">
          <Building className="h-12 w-12 mx-auto text-gray-300 mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No organizational data</h3>
          <p className="text-gray-500">No units or departments found.</p>
        </div>
      )}
    </div>
  );
};

export default OrganizationalTree;
