import React, { useState } from 'react';
import { ChevronDown, ChevronRight, Users, Building, Plus, FolderPlus, Edit } from 'lucide-react';
import { User as UserType, Department } from '../../types';
import ContactCard from './ContactCard';
import { useAuth } from '../../context/AuthContext';

interface OrganizationalStructureViewProps {
  users: UserType[];
  departments: Department[];
  units: any[];
  totalContacts?: number;
  onUserClick?: (user: UserType) => void;
  onEditUser?: (user: UserType) => void;
  onAddUser?: (organizationName: string, departmentName: string) => void;
  onAddDepartment?: (organizationName: string, organizationId: number) => void;
  onAddSubDepartment?: (departmentId: number, departmentName: string) => void;
  onEditDepartment?: (departmentId: number) => void;
  onDeleteUser?: (user: UserType) => void;
  onDeleteDepartment?: (departmentId: number, departmentName: string) => void;
  onCreateChild?: (user: UserType) => void;
  showActions?: boolean;
  isAdmin?: boolean;
  isSuperAdmin?: boolean;
}

interface OrganizationData {
  name: string;
  departments: Record<string, DepartmentData>;
  totalUsers: number;
}

interface DepartmentData {
  name: string;
  users: UserType[];
  totalUsers: number;
}

const OrganizationalStructureView: React.FC<OrganizationalStructureViewProps> = ({
  users,
  departments,
  units,
  totalContacts,
  onUserClick,
  onEditUser,
  onAddUser,
  onAddDepartment,
  onAddSubDepartment,
  onEditDepartment,
  onEditUnit,
  onDeleteUser,
  onDeleteDepartment,
  onDeleteUnit,
  onCreateChild,
  showActions = false,
  isAdmin = false,
  isSuperAdmin = false
}) => {
  const { user: currentUser, hasPermission } = useAuth();
  const [expandedOrganizations, setExpandedOrganizations] = useState<Set<string>>(new Set());
  const [expandedDepartments, setExpandedDepartments] = useState<Set<string>>(new Set());
  const [failedLogos, setFailedLogos] = useState<Set<string>>(new Set());

  // Check permissions for Role 16 (navy_admin) - Comprehensive Tree List Permissions
  const canCreateContact = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.create') || hasPermission('directory.contact.create');
  const canEditContact = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.update') || hasPermission('directory.contact.edit');
  const canDeleteContact = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.delete') || hasPermission('directory.contact.delete');
  
  const canCreateDepartment = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('department.create');
  const canEditDepartment = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('department.update');
  const canDeleteDepartment = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('department.delete');
  
  const canCreateDesignation = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('designation.create');
  const canEditDesignation = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('designation.update');
  const canDeleteDesignation = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('designation.delete');

  // Debug logging for Role 16
  console.log('OrganizationalStructureView Debug:', {
    currentUser: currentUser?.name,
    roleId: currentUser?.role_id,
    isAdmin,
    isSuperAdmin,
    canCreateContact,
    canEditContact,
    canDeleteContact,
    canCreateDepartment,
    canEditDepartment,
    canDeleteDepartment,
    showActions,
    permissions: currentUser?.permissions?.slice(0, 5) // Show first 5 permissions
  });

  const baseOrganizations = departments.reduce((acc, dept) => {
    const orgName = (dept as any).organization_name || 'Unknown Organization';
    const departmentName = dept.name;
    if (!acc[orgName]) {
      acc[orgName] = {
        name: orgName,
        departments: {} as Record<string, DepartmentData>,
        totalUsers: 0
      };
    }
    if (!acc[orgName].departments[departmentName]) {
      acc[orgName].departments[departmentName] = {
        name: departmentName,
        users: [],
        totalUsers: 0
      };
    }
    return acc;
  }, {} as Record<string, OrganizationData>);

  const organizationalData = users.reduce((acc, user) => {
    const orgName = user.organization || 'Unknown Organization';
    const departmentName = user.department || 'Unknown Department';
    if (!acc[orgName]) {
      acc[orgName] = {
        name: orgName,
        departments: {} as Record<string, DepartmentData>,
        totalUsers: 0
      };
    }
    if (!acc[orgName].departments[departmentName]) {
      acc[orgName].departments[departmentName] = {
        name: departmentName,
        users: [],
        totalUsers: 0
      };
    }
    if (!user.parent_id) {
      acc[orgName].departments[departmentName].users.push(user);
      acc[orgName].departments[departmentName].totalUsers++;
      acc[orgName].totalUsers++;
    }
    return acc;
  }, baseOrganizations);

  // Sort parent users within each department
  Object.values(organizationalData).forEach(unit => {
    Object.values(unit.departments).forEach(department => {
      // Sort parent users by id
      department.users.sort((a, b) => (a.order_id || 0) - (b.order_id || 0));
    });
  });

  console.log('OrganizationalStructureView - organizationalData keys:', Object.keys(organizationalData));

  const sortedOrganizations = Object.values(organizationalData).sort((a, b) => a.name.localeCompare(b.name));

  console.log('OrganizationalStructureView - sortedOrganizations:', sortedOrganizations.map(u => ({ name: u.name, totalUsers: u.totalUsers })));

  // Function to organize departments hierarchically
  const organizeDepartmentsHierarchically = (unitDepartments: DepartmentData[]) => {
    const departmentMap = new Map<string, DepartmentData & { children: DepartmentData[]; level: number }>();
    const rootDepartments: (DepartmentData & { children: DepartmentData[]; level: number })[] = [];

    // First, create a map of all departments
    unitDepartments.forEach(dept => {
      const deptInfo = departments.find(d => d.name === dept.name);
      departmentMap.set(dept.name, {
        ...dept,
        children: [],
        level: deptInfo?.parent_id ? 1 : 0
      });
    });

    // Then, organize them hierarchically
    unitDepartments.forEach(dept => {
      const deptInfo = departments.find(d => d.name === dept.name);
      const mappedDept = departmentMap.get(dept.name)!;
      
      if (deptInfo?.parent_id) {
        // This is a sub-department, find its parent
        const parentDept = departments.find(d => d.id === deptInfo.parent_id);
        if (parentDept) {
          const parentMappedDept = departmentMap.get(parentDept.name);
          if (parentMappedDept) {
            parentMappedDept.children.push(mappedDept);
            mappedDept.level = parentMappedDept.level + 1;
          }
        }
      } else {
        // This is a root department
        rootDepartments.push(mappedDept);
      }
    });

    return rootDepartments;
  };

  const toggleOrganization = (organizationName: string) => {
    const newExpanded = new Set(expandedOrganizations);
    if (newExpanded.has(organizationName)) {
      newExpanded.delete(organizationName);
    } else {
      newExpanded.add(organizationName);
    }
    setExpandedOrganizations(newExpanded);
  };

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

  // Recursive component to render contact with children
  const renderContactWithChildren = (contact: UserType, level: number = 0) => {
    const hasChildren = contact.children && contact.children.length > 0;
    
    return (
      <div key={contact.id} className="relative">
        {/* Contact Card */}
        <div className={`${level > 0 ? 'ml-8 mt-1' : ''}`}>
          {/* Connection line for child contacts */}
          {level > 0 && (
            <>
              <div className="absolute -left-6 top-2 w-6 h-px bg-gray-300"></div>
              <div className="absolute -left-6 top-2 w-px h-6 bg-gray-300"></div>
            </>
          )}
          
          <ContactCard
            user={contact}
            onClick={() => onUserClick?.(contact)}
            onEdit={onEditUser}
            onCreateChild={onCreateChild}
            onDelete={onDeleteUser}
            viewMode="organizational"
            showActions={showActions}
            isAdmin={isAdmin}
            isSuperAdmin={isSuperAdmin}
            isChild={level > 0}
          />
        </div>
        
        {/* Render children recursively */}
        {hasChildren && (
          <div className="ml-4 space-y-1">
            {contact.children!.map(child => renderContactWithChildren(child, level + 1))}
          </div>
        )}
      </div>
    );
  };

  // Recursive component to render department with sub-departments
  const renderDepartmentWithChildren = (department: DepartmentData & { children: DepartmentData[]; level: number }, organizationName: string) => {
    const departmentKey = `${organizationName}-${department.name}`;
    const isDepartmentExpanded = expandedDepartments.has(departmentKey);
    const hasSubDepartments = department.children.length > 0;
    const deptInfo = departments.find(d => d.name === department.name);
    
    return (
      <div key={departmentKey} className="relative">
        {/* Department Header */}
        <div 
          className={`flex items-center justify-between p-3 cursor-pointer hover:bg-gray-50 transition-colors ${
            department.level > 0 ? 'ml-8 border-l-2 border-gray-200' : ''
          }`}
          onClick={() => toggleDepartment(departmentKey)}
        >
          {/* Connection line for sub-departments */}
          {department.level > 0 && (
            <>
              <div className="absolute -left-6 top-2 w-6 h-px bg-gray-300"></div>
              <div className="absolute -left-6 top-2 w-px h-6 bg-gray-300"></div>
            </>
          )}
          
          <div className="flex items-center space-x-3">
            {hasSubDepartments ? (
              isDepartmentExpanded ? (
                <ChevronDown className="h-4 w-4 text-gray-500" />
              ) : (
                <ChevronRight className="h-4 w-4 text-gray-500" />
              )
            ) : (
              <div className="w-4 h-4"></div> // Spacer for alignment
            )}
            {deptInfo?.logo && !failedLogos.has(departmentKey) ? (
              <img
                src={deptInfo.logo}
                alt={department.name}
                className="h-5 w-5 rounded object-cover border border-gray-200"
                onError={(e) => {
                  setFailedLogos(prev => new Set(prev).add(departmentKey));
                }}
              />
            ) : (
              <Users className={`h-5 w-5 ${department.level > 0 ? 'text-blue-600' : 'text-green-600'}`} />
            )}
            <div>
              <h4 className={`text-md font-medium ${department.level > 0 ? 'text-blue-800' : 'text-gray-800'}`}>
                {department.name}
                {department.level > 0 && <span className="text-xs text-gray-500 ml-2">(Sub-Department)</span>}
              </h4>
              {hasSubDepartments ? (
                <p className="text-xs text-blue-600 font-medium">
                  {department.children.length} sub-department{department.children.length !== 1 ? 's' : ''}
                </p>
              ) : (
                <p className="text-xs text-gray-500">
                  {department.users.length} contact{department.users.length !== 1 ? 's' : ''}
                </p>
              )}
            </div>
          </div>
          <div className="flex items-center space-x-2">
            {showActions && onAddSubDepartment && canCreateDepartment && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  // Find the department ID from the departments prop
                  const dept = departments.find(d => d.name === department.name);
                  if (dept) {
                    onAddSubDepartment(dept.id, department.name);
                  }
                }}
                className="p-1 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                title="Add Sub-Department"
              >
                <FolderPlus className="h-4 w-4" />
              </button>
            )}
            {showActions && canEditDepartment && onEditDepartment && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  // Find the department ID from the departments prop
                  const dept = departments.find(d => d.name === department.name);
                  if (dept) {
                    onEditDepartment(dept.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>
            )}
            {showActions && onAddUser && canCreateContact && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onAddUser(organizationName, department.name);
                }}
                className="p-1 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                title="Add New Contact to Department"
              >
                <Plus className="h-4 w-4" />
              </button>
            )}
            {showActions && onDeleteDepartment && canDeleteDepartment && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  // Find the department ID from the departments prop
                  const dept = departments.find(d => d.name === department.name);
                  if (dept) {
                    onDeleteDepartment(dept.id, department.name);
                  }
                }}
                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>

        {/* Department Contacts */}
        {isDepartmentExpanded && (
          <div className={`bg-gray-50 p-4 ${department.level > 0 ? 'pl-20' : 'pl-16'}`}>
            <div className="space-y-2">
              {department.users.map((user) => renderContactWithChildren(user))}
            </div>
          </div>
        )}

        {/* Render sub-departments recursively */}
        {hasSubDepartments && isDepartmentExpanded && (
          <div className="ml-4 space-y-1">
            {department.children.map(child => renderDepartmentWithChildren(child as DepartmentData & { children: DepartmentData[]; level: number }, organizationName))}
          </div>
        )}
      </div>
    );
  };


  return (
    <div className="space-y-4">
      {/* Summary Stats */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{sortedOrganizations.length}</div>
            <div className="text-sm text-blue-800">Organizations</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{(() => {
              const s = new Set<string>();
              users.forEach(u => { if (u.department) s.add(u.department); });
              departments.forEach(d => { if (d.name) s.add(d.name); });
              return s.size;
            })()}</div>
            <div className="text-sm text-blue-800">Departments</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{typeof totalContacts === 'number' ? totalContacts : users.length}</div>
            <div className="text-sm text-blue-800">Total Contacts</div>
          </div>
        </div>
      </div>

      {/* Organizational Structure */}
      <div className="space-y-4">
        {sortedOrganizations.map((org) => {
          const isOrgExpanded = expandedOrganizations.has(org.name);
          const orgDepartments = Object.values(org.departments);
          const hierarchicalDepartments = organizeDepartmentsHierarchically(orgDepartments);
          
          return (
            <div key={org.name} className="bg-white border border-gray-200 rounded-lg shadow-sm">
              <div 
                className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50 transition-colors"
                onClick={() => toggleOrganization(org.name)}
              >
                <div className="flex items-center space-x-3">
                  {isOrgExpanded ? (
                    <ChevronDown className="h-5 w-5 text-gray-600" />
                  ) : (
                    <ChevronRight className="h-5 w-5 text-gray-600" />
                  )}
                  <Building className="h-6 w-6 text-blue-600" />
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">{org.name}</h3>
                    <p className="text-sm text-gray-500">
                      {hierarchicalDepartments.length} department{hierarchicalDepartments.length !== 1 ? 's' : ''}
                    </p>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  {showActions && onAddDepartment && canCreateDepartment && (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        onAddDepartment(org.name, 0);
                      }}
                      className="p-1 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                      title="Add New Department to Organization"
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  )}
                </div>
              </div>

              {isOrgExpanded && (
                <div className="border-t border-gray-200">
                  {hierarchicalDepartments.map((department) => 
                    renderDepartmentWithChildren(department, org.name)
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Empty State */}
      {sortedOrganizations.length === 0 && (
        <div className="text-center py-12">
          <Building className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No organizational data</h3>
          <p className="text-gray-500">No organizations or contacts found in the system.</p>
        </div>
      )}
    </div>
  );
};

export default OrganizationalStructureView;
