'use client'

import { Tree, TreeNode } from 'react-organizational-chart'
import type { Department } from '@/lib/api/employees'
import { Building2, Users } from 'lucide-react'

// Force LTR for org chart - RTL breaks the tree layout and connecting lines
function DeptNode({ dept }: { dept: Department }) {
  const empCount = dept._count?.employees ?? dept.employees?.length ?? 0
  const childCount = dept.children?.length ?? 0
  return (
    <div className="inline-flex flex-col items-center" dir="ltr">
      <div className="px-4 py-3 bg-white border-2 border-blue-200 rounded-lg shadow-md hover:shadow-lg transition-shadow min-w-[180px] max-w-[220px]">
        <div className="flex items-center gap-2 mb-1">
          <Building2 className="h-5 w-5 text-blue-600 flex-shrink-0" />
          <span className="font-semibold text-gray-900 truncate">{dept.nameAr || dept.name}</span>
        </div>
        <p className="text-xs text-gray-500 mb-1">{dept.code}</p>
        <div className="flex gap-2 text-xs text-gray-600">
          <span className="flex items-center gap-1">
            <Users className="h-3 w-3" />
            {empCount} موظف
          </span>
          {childCount > 0 && (
            <span>• {childCount} أقسام فرعية</span>
          )}
        </div>
        {dept.employees && dept.employees.length > 0 && (
          <div className="mt-2 pt-2 border-t border-gray-100 space-y-0.5">
            {dept.employees.slice(0, 3).map((emp: any) => (
              <p key={emp.id} className="text-xs text-gray-600 truncate">
                {emp.firstNameAr || emp.firstName} {emp.lastNameAr || emp.lastName}
                {emp.position && ` - ${emp.position.titleAr || emp.position.title}`}
              </p>
            ))}
            {dept.employees.length > 3 && (
              <p className="text-xs text-gray-500">+{dept.employees.length - 3} أكثر</p>
            )}
          </div>
        )}
      </div>
    </div>
  )
}

export function OrgChartTree({ dept }: { dept: Department }) {
  if (!dept.children?.length) {
    return <TreeNode label={<DeptNode dept={dept} />} />
  }
  return (
    <TreeNode label={<DeptNode dept={dept} />}>
      {dept.children.map((child) => (
        <OrgChartTree key={child.id} dept={child} />
      ))}
    </TreeNode>
  )
}

interface OrgChartProps {
  hierarchy: Department[]
}

export default function OrgChart({ hierarchy }: OrgChartProps) {
  if (hierarchy.length === 0) {
    return (
      <div className="p-12 text-center text-gray-500">
        <Building2 className="h-16 w-16 mx-auto mb-4 text-gray-300" />
        <p>لا توجد أقسام. أضف أقساماً من تبويب الأقسام.</p>
      </div>
    )
  }
  if (hierarchy.length === 1) {
    const root = hierarchy[0]
    return (
      <div className="p-6 overflow-auto min-h-[400px]" dir="ltr" style={{ direction: 'ltr' }}>
        <div className="inline-block">
          <Tree
            label={<DeptNode dept={root} />}
            lineWidth="2px"
            lineColor="#93c5fd"
            lineBorderRadius="4px"
            lineHeight="24px"
            nodePadding="16px"
          >
            {root.children?.map((child) => (
              <OrgChartTree key={child.id} dept={child} />
            ))}
          </Tree>
        </div>
      </div>
    )
  }
  return (
    <div className="p-6 overflow-auto min-h-[400px]" dir="ltr" style={{ direction: 'ltr' }}>
      <div className="inline-block">
        <Tree
          label={
            <div className="px-4 py-3 bg-blue-50 border-2 border-blue-200 rounded-lg min-w-[200px] text-center">
              <p className="font-bold text-gray-900">الشركة</p>
              <p className="text-xs text-gray-500">الجذر التنظيمي</p>
            </div>
          }
          lineWidth="2px"
          lineColor="#93c5fd"
          lineBorderRadius="4px"
          lineHeight="24px"
          nodePadding="16px"
        >
          {hierarchy.map((dept) => (
            <OrgChartTree key={dept.id} dept={dept} />
          ))}
        </Tree>
      </div>
    </div>
  )
}
