import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { 
  Building2, 
  Users, 
  ChevronDown, 
  ChevronRight,
  User,
  Plus,
  Edit,
  Trash2
} from "lucide-react";

interface DepartmentNode {
  id: string;
  name: string;
  manager: string;
  employeeCount: number;
  children?: DepartmentNode[];
}

export function OrganizationChart() {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set(["root", "prod", "quality"]));

  const organizationData: DepartmentNode = {
    id: "root",
    name: "경영진",
    manager: "김대표",
    employeeCount: 1,
    children: [
      {
        id: "prod",
        name: "생산부",
        manager: "이생산",
        employeeCount: 15,
        children: [
          { id: "prod1", name: "생산1팀", manager: "박팀장", employeeCount: 8 },
          { id: "prod2", name: "생산2팀", manager: "최팀장", employeeCount: 7 }
        ]
      },
      {
        id: "quality",
        name: "품질부",
        manager: "박품질",
        employeeCount: 9,
        children: [
          { id: "quality1", name: "품질관리팀", manager: "강팀장", employeeCount: 5 },
          { id: "quality2", name: "품질보증팀", manager: "정팀장", employeeCount: 4 }
        ]
      },
      {
        id: "sales",
        name: "영업부",
        manager: "정영업",
        employeeCount: 11,
        children: [
          { id: "sales1", name: "국내영업팀", manager: "오팀장", employeeCount: 6 },
          { id: "sales2", name: "해외영업팀", manager: "윤팀장", employeeCount: 5 }
        ]
      },
      {
        id: "facility",
        name: "설비부",
        manager: "강설비",
        employeeCount: 6,
        children: [
          { id: "facility1", name: "설비관리팀", manager: "송팀장", employeeCount: 4 },
          { id: "facility2", name: "설비보전팀", manager: "임팀장", employeeCount: 2 }
        ]
      },
      {
        id: "material",
        name: "자재부",
        manager: "최자재",
        employeeCount: 7
      },
      {
        id: "support",
        name: "지원부",
        manager: "한지원",
        employeeCount: 11,
        children: [
          { id: "hr", name: "인사팀", manager: "신팀장", employeeCount: 3 },
          { id: "accounting", name: "회계팀", manager: "조팀장", employeeCount: 4 },
          { id: "admin", name: "총무팀", manager: "배팀장", employeeCount: 4 }
        ]
      }
    ]
  };

  const toggleNode = (nodeId: string) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  const renderNode = (node: DepartmentNode, level: number = 0) => {
    const hasChildren = node.children && node.children.length > 0;
    const isExpanded = expandedNodes.has(node.id);
    
    return (
      <div key={node.id} className={level > 0 ? "ml-8" : ""}>
        <div className="mb-3">
          <Card className={`${level === 0 ? 'border-2 border-primary' : ''} hover:shadow-lg transition-shadow`}>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3 flex-1">
                  {hasChildren && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => toggleNode(node.id)}
                      className="p-0 h-6 w-6"
                    >
                      {isExpanded ? (
                        <ChevronDown className="h-4 w-4" />
                      ) : (
                        <ChevronRight className="h-4 w-4" />
                      )}
                    </Button>
                  )}
                  {!hasChildren && <div className="w-6" />}
                  
                  <div className={`p-2 rounded-lg ${level === 0 ? 'bg-primary/10' : 'bg-blue-50'}`}>
                    {level === 0 ? (
                      <Building2 className={`h-6 w-6 ${level === 0 ? 'text-primary' : 'text-blue-600'}`} />
                    ) : (
                      <Users className="h-5 w-5 text-blue-600" />
                    )}
                  </div>

                  <div className="flex-1">
                    <div className="flex items-center space-x-2">
                      <h3 className={level === 0 ? "text-xl" : ""}>{node.name}</h3>
                      <Badge variant="secondary" className="text-xs">
                        {node.employeeCount}명
                      </Badge>
                    </div>
                    <div className="flex items-center space-x-1 text-sm text-muted-foreground mt-1">
                      <User className="h-3 w-3" />
                      <span>{node.manager}</span>
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-2">
                  <Button variant="ghost" size="sm">
                    <Edit className="h-4 w-4" />
                  </Button>
                  {level > 0 && (
                    <Button variant="ghost" size="sm" className="text-red-600">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {hasChildren && isExpanded && (
          <div className="space-y-2">
            {node.children!.map(child => renderNode(child, level + 1))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="p-4 md:p-6 space-y-6">
      {/* 헤더 */}
      <div className="bg-card border border-border/20 rounded-xl p-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold text-foreground mb-2">조직도 관리</h1>
            <p className="text-muted-foreground">회사 조직 구조를 관리합니다</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline">
              <Plus className="h-4 w-4 mr-2" />
              부서 추가
            </Button>
            <Button>
              <Users className="h-4 w-4 mr-2" />
              직원 배치
            </Button>
          </div>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm">총 부서 수</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl">13개</div>
            <p className="text-xs text-muted-foreground mt-1">본부 6개 • 팀 7개</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm">총 직원 수</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl">60명</div>
            <p className="text-xs text-muted-foreground mt-1">전년대비 +5명</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm">평균 팀 규모</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl">4.6명</div>
            <p className="text-xs text-muted-foreground mt-1">팀당 평균 인원</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm">조직 깊이</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl">3단계</div>
            <p className="text-xs text-muted-foreground mt-1">본부 → 부 → 팀</p>
          </CardContent>
        </Card>
      </div>

      {/* 조직도 */}
      <Card>
        <CardHeader>
          <CardTitle>조직 구조</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {renderNode(organizationData)}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
