import React, { useState, useMemo } from 'react';
import { Building2, ChevronRight, Users, UserCheck, Network, X, Plus, Trash2, Edit, ShieldCheck } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Department } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

export function Organization() {
  const { departments, addDepartment, updateDepartment, deleteDepartment, engineers } = useApp();
  const { hasPermission } = useAuth();
  const [activeTab, setActiveTab] = useState<'hierarchy' | 'roles'>('hierarchy');
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [editingDept, setEditingDept] = useState<Department | null>(null);
  const [deptToDelete, setDeptToDelete] = useState<{ id: string, name: string } | null>(null);
  const [newDept, setNewDept] = useState({ name: '', manager: '', parentId: '' });

  // Build hierarchy tree from flat departments list
  const orgData = useMemo(() => {
    const deptMap = new Map<string, any>();
    const roots: any[] = [];

    // First pass: create all nodes
    departments.forEach(dept => {
      deptMap.set(dept.id, { ...dept, children: [] });
    });

    // Second pass: link children to parents
    departments.forEach(dept => {
      const node = deptMap.get(dept.id);
      if (dept.parentId && deptMap.has(dept.parentId)) {
        deptMap.get(dept.parentId).children.push(node);
      } else {
        roots.push(node);
      }
    });

    // If there are multiple roots, wrap them in a virtual company node if needed
    // or just return the first root (assuming one main company node)
    if (roots.length > 1) {
      return {
        id: 'ROOT',
        name: 'MA IT TECH SERVICES',
        type: 'Company',
        children: roots
      };
    }
    return roots[0] || { id: 'EMPTY', name: 'No Data', type: 'Company', children: [] };
  }, [departments]);

  const handleAddDepartment = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newDept.name || isSubmitting) return;

    setIsSubmitting(true);
    try {
      if (editingDept) {
        await updateDepartment(editingDept.id, newDept);
        toast.success('Department updated successfully');
      } else {
        const newId = `DEP-${Math.random().toString(36).substr(2, 5).toUpperCase()}`;
        await addDepartment({
          ...newDept,
          id: newId,
          teams: 0
        } as Department);
        toast.success('Department added successfully');
      }
      
      setNewDept({ name: '', manager: '', parentId: '' });
      setEditingDept(null);
      setIsAddModalOpen(false);
    } catch (error) {
      console.error('Save department error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleEdit = (dept: Department) => {
    setEditingDept(dept);
    setNewDept({ name: dept.name, manager: dept.manager, parentId: dept.parentId || '' });
    setIsAddModalOpen(true);
  };

  const handleDeleteClick = (id: string, name: string) => {
    if (id === 'ROOT' || id === 'EMPTY') return;
    setDeptToDelete({ id, name });
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (!deptToDelete) return;
    setIsDeleting(true);

    try {
      await deleteDepartment(deptToDelete.id);
      toast.success('Department deleted');
      setIsDeleteModalOpen(false);
      setDeptToDelete(null);
    } catch (error) {
      toast.error('Failed to delete department');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Organization Structure</h1>
          <p className="text-muted-foreground">Visualize and manage the company hierarchy and departments.</p>
        </div>
        <div className="flex gap-2">
          <div className="flex p-1 rounded-lg bg-muted border border-border mr-4">
            <button 
              onClick={() => setActiveTab('hierarchy')}
              className={cn(
                "px-4 py-1.5 text-sm font-medium rounded-md transition-all",
                activeTab === 'hierarchy' ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"
              )}
            >
              Hierarchy
            </button>
            <button 
              onClick={() => setActiveTab('roles')}
              className={cn(
                "px-4 py-1.5 text-sm font-medium rounded-md transition-all",
                activeTab === 'roles' ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"
              )}
            >
              Roles & Permissions
            </button>
          </div>
          {hasPermission('hr.create') && (
            <button 
              onClick={() => setIsAddModalOpen(true)}
              className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
            >
              <Building2 size={18} />
              Add Department
            </button>
          )}
        </div>
      </div>

      {/* Add/Edit Department Modal */}
      {isAddModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-semibold">{editingDept ? 'Edit Department' : 'Add New Department'}</h3>
              <button 
                onClick={() => {
                  setIsAddModalOpen(false);
                  setEditingDept(null);
                }}
                className="rounded-md p-1 hover:bg-accent transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleAddDepartment} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium">Department Name</label>
                <input 
                  type="text" 
                  autoFocus
                  required
                  placeholder="e.g. Product Design"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                  value={newDept.name}
                  onChange={e => setNewDept(prev => ({ ...prev, name: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Department Manager</label>
                <input 
                  type="text" 
                  placeholder="e.g. John Doe"
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                  value={newDept.manager}
                  onChange={e => setNewDept(prev => ({ ...prev, manager: e.target.value }))}
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Parent Department (Optional)</label>
                <select 
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                  value={newDept.parentId}
                  onChange={e => setNewDept(prev => ({ ...prev, parentId: e.target.value }))}
                >
                  <option value="">None (Top Level)</option>
                  {departments.filter(d => d.id !== editingDept?.id).map(d => (
                    <option key={d.id} value={d.id}>{d.name}</option>
                  ))}
                </select>
              </div>
              <div className="flex gap-3 pt-4">
                <button 
                  type="button"
                  onClick={() => {
                    setIsAddModalOpen(false);
                    setEditingDept(null);
                  }}
                  className="flex-1 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  disabled={isSubmitting}
                  className="flex-1 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                      Saving...
                    </>
                  ) : (
                    editingDept ? 'Update' : 'Create'
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-sm rounded-xl border border-border bg-card p-6 shadow-lg animate-in fade-in zoom-in duration-200">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-semibold text-destructive">Confirm Deletion</h3>
              <button 
                onClick={() => setIsDeleteModalOpen(false)}
                className="rounded-md p-1 hover:bg-accent transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            <div className="space-y-4">
              <p className="text-sm text-muted-foreground">
                Are you sure you want to delete the <span className="font-bold text-foreground">"{deptToDelete?.name}"</span> department?
              </p>
              <p className="text-xs text-muted-foreground bg-accent/50 p-3 rounded-lg">
                Note: This will not delete sub-departments, but they will become top-level nodes in the hierarchy.
              </p>
              <div className="flex gap-3 pt-2">
                <button 
                  onClick={() => setIsDeleteModalOpen(false)}
                  disabled={isDeleting}
                  className="flex-1 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors disabled:opacity-50"
                >
                  Cancel
                </button>
                <button 
                  onClick={confirmDelete}
                  disabled={isDeleting}
                  className="flex-1 rounded-lg bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isDeleting ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
                      Deleting...
                    </>
                  ) : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'hierarchy' ? (
        <>
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="rounded-lg bg-blue-500/10 p-3 text-blue-500">
                  <Building2 size={24} />
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Departments</p>
                  <h4 className="text-2xl font-bold">{departments.length}</h4>
                </div>
              </div>
            </div>
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="rounded-lg bg-green-500/10 p-3 text-green-500">
                  <Network size={24} />
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Teams</p>
                  <h4 className="text-2xl font-bold">{departments.reduce((acc, d) => acc + (d.teams || 0), 0)}</h4>
                </div>
              </div>
            </div>
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="rounded-lg bg-purple-500/10 p-3 text-purple-500">
                  <UserCheck size={24} />
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Internal Engineers</p>
                  <h4 className="text-2xl font-bold">{engineers.filter(e => e.type === 'Internal').length}</h4>
                </div>
              </div>
            </div>
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="rounded-lg bg-orange-500/10 p-3 text-orange-500">
                  <Users size={24} />
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">External Engineers</p>
                  <h4 className="text-2xl font-bold">{engineers.filter(e => e.type === 'External').length}</h4>
                </div>
              </div>
            </div>
          </div>

          <div className="rounded-xl border border-border bg-card p-8 shadow-sm overflow-x-auto">
            <h3 className="mb-8 text-lg font-semibold">Hierarchy Tree</h3>
            <div className="min-w-[600px] max-w-4xl mx-auto">
              <TreeNode node={orgData} isRoot onEdit={handleEdit} onDelete={handleDeleteClick} />
            </div>
          </div>
        </>
      ) : (
        <RolesAndPermissions />
      )}
    </div>
  );
}

interface TreeNodeProps {
  node: any;
  isRoot?: boolean;
  onEdit: (dept: Department) => void;
  onDelete: (id: string, name: string) => void;
}

const TreeNode: React.FC<TreeNodeProps> = ({ node, isRoot = false, onEdit, onDelete }) => {
  const { hasPermission } = useAuth();
  const [isOpen, setIsOpen] = React.useState(true);
  const hasChildren = node.children && node.children.length > 0;
  const isVirtual = node.id === 'ROOT' || node.id === 'EMPTY';

  return (
    <div className={cn("relative", !isRoot && "ml-8 mt-4")}>
      {!isRoot && (
        <div className="absolute -left-4 top-4 h-px w-4 bg-border" />
      )}
      <div 
        className={cn(
          "group relative flex items-center gap-4 rounded-xl border border-border p-4 transition-all hover:border-primary/50 hover:shadow-md",
          isRoot ? "bg-primary/5 border-primary/20" : "bg-card"
        )}
      >
        <div className={cn(
          "flex h-10 w-10 items-center justify-center rounded-lg",
          node.type === 'Company' || isRoot ? "bg-primary text-primary-foreground" :
          "bg-blue-500/10 text-blue-500"
        )}>
          {node.type === 'Company' || isRoot ? <Building2 size={20} /> : <Network size={20} />}
        </div>
        <div className="flex-1">
          <p className="text-sm font-bold">{node.name}</p>
          <p className="text-xs text-muted-foreground">
            {node.manager && `Manager: ${node.manager}`}
          </p>
        </div>
        
        <div className="flex items-center gap-1">
          {!isVirtual && (
            <>
              {hasPermission('hr.edit') && (
                <button 
                  onClick={() => onEdit(node)}
                  className="p-2 hover:bg-accent rounded-lg text-muted-foreground transition-colors"
                  title="Edit Department"
                >
                  <Edit size={16} />
                </button>
              )}
              {hasPermission('hr.delete') && (
                <button 
                  onClick={() => onDelete(node.id, node.name)}
                  className="p-2 hover:bg-destructive/10 rounded-lg text-destructive transition-colors"
                  title="Delete Department"
                >
                  <Trash2 size={16} />
                </button>
              )}
            </>
          )}
        </div>

        {hasChildren && (
          <button 
            onClick={() => setIsOpen(!isOpen)}
            className="rounded-md p-1 hover:bg-accent transition-colors"
          >
            <ChevronRight size={18} className={cn("transition-transform", isOpen && "rotate-90")} />
          </button>
        )}
      </div>

      {hasChildren && isOpen && (
        <div className="relative border-l border-border ml-5 mt-2">
          {node.children.map((child: any, idx: number) => (
            <TreeNode key={child.id || idx} node={child} onEdit={onEdit} onDelete={onDelete} />
          ))}
        </div>
      )}
    </div>
  );
}

function RolesAndPermissions() {
  const roles = [
    { name: 'Admin', permissions: ['All Access', 'User Management', 'Financials'] },
    { name: 'Manager', permissions: ['Project Management', 'Team Lead', 'Reports'] },
    { name: 'Engineer', permissions: ['Task Management', 'Time Logging', 'Project View'] },
    { name: 'Sales', permissions: ['Lead Management', 'CRM Access', 'Client View'] },
    { name: 'HR', permissions: ['Recruitment', 'Employee Directory', 'Organization'] }
  ];

  return (
    <div className="grid gap-6 md:grid-cols-2">
      <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
        <h3 className="text-lg font-bold mb-6 flex items-center gap-2">
          <ShieldCheck className="text-primary" />
          Roles Definition
        </h3>
        <div className="space-y-4">
          {roles.map(role => (
            <div key={role.name} className="p-4 rounded-lg border border-border bg-muted/20 hover:bg-muted/30 transition-colors">
              <div className="flex items-center justify-between mb-2">
                <h4 className="font-bold">{role.name}</h4>
                <button className="text-xs text-primary hover:underline">Edit Role</button>
              </div>
              <div className="flex flex-wrap gap-2">
                {role.permissions.map(p => (
                  <span key={p} className="px-2 py-0.5 rounded bg-primary/10 text-primary text-[10px] font-bold uppercase">
                    {p}
                  </span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
        <h3 className="text-lg font-bold mb-6 flex items-center gap-2">
          <UserCheck className="text-green-500" />
          Access Permissions Matrix
        </h3>
        <div className="space-y-4">
          {['Create Project', 'Delete Employee', 'View Financials', 'Approve Time'].map(perm => (
            <div key={perm} className="flex items-center justify-between p-3 rounded-lg border border-border">
              <span className="text-sm font-medium">{perm}</span>
              <div className="flex gap-2">
                <span className="h-2 w-2 rounded-full bg-green-500" title="Admin" />
                <span className="h-2 w-2 rounded-full bg-green-500" title="Manager" />
                <span className="h-2 w-2 rounded-full bg-muted" title="Engineer" />
              </div>
            </div>
          ))}
          <button className="w-full py-2 rounded-lg border border-dashed border-border text-sm text-muted-foreground hover:bg-accent transition-colors">
            Add New Permission
          </button>
        </div>
      </div>
    </div>
  );
}
