import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "./ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Progress } from "./ui/progress";
import {
  Users,
  UserPlus,
  Search,
  Download,
  Building2,
  Award,
  Calendar,
  TrendingUp,
  Target,
  Eye,
  Edit,
  Network,
  User
} from "lucide-react";
import { BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";

export function HRManagement() {
  const [activeTab, setActiveTab] = useState("organization");
  const [isAddEmployeeOpen, setIsAddEmployeeOpen] = useState(false);

  // 직원 데이터
  const employees = [
    {
      id: "EMP001",
      name: "김대표",
      position: "대표이사",
      department: "경영진",
      team: "-",
      joinDate: "2015-01-01",
      email: "ceo@company.com",
      phone: "010-1111-1111",
      address: "서울시 강남구",
      birthDate: "1975-03-15",
      education: "서울대 경영학 석사",
      annualLeave: 0,
      usedLeave: 0,
      salary: "비공개",
      performance: 95,
      status: "재직",
      kpi: [
        { metric: "매출 달성률", target: 100, actual: 112, unit: "%" },
        { metric: "영업이익률", target: 15, actual: 18, unit: "%" }
      ]
    },
    {
      id: "EMP002",
      name: "이생산",
      position: "과장",
      department: "생산부",
      team: "생산1팀",
      joinDate: "2018-03-15",
      email: "lee@company.com",
      phone: "010-2222-2222",
      address: "경기도 안산시",
      birthDate: "1985-07-20",
      education: "한양대 기계공학 학사",
      annualLeave: 15,
      usedLeave: 8,
      salary: "5,500,000",
      performance: 88,
      status: "재직",
      kpi: [
        { metric: "생산 목표 달성률", target: 100, actual: 105, unit: "%" },
        { metric: "불량률", target: 2, actual: 1.2, unit: "%" },
        { metric: "납기준수율", target: 95, actual: 98, unit: "%" }
      ]
    },
    {
      id: "EMP003",
      name: "박품질",
      position: "대리",
      department: "품질부",
      team: "품질관리팀",
      joinDate: "2019-06-01",
      email: "park@company.com",
      phone: "010-3333-3333",
      address: "경기도 시흥시",
      birthDate: "1988-11-10",
      education: "인하대 산업공학 학사",
      annualLeave: 15,
      usedLeave: 5,
      salary: "4,800,000",
      performance: 92,
      status: "재직",
      kpi: [
        { metric: "품질 합격률", target: 98, actual: 99.2, unit: "%" },
        { metric: "검사 처리시간", target: 24, actual: 18, unit: "시간" },
        { metric: "고객 클레임", target: 5, actual: 2, unit: "건" }
      ]
    },
    {
      id: "EMP004",
      name: "정설비",
      position: "사원",
      department: "설비부",
      team: "설비관리팀",
      joinDate: "2021-09-01",
      email: "jung@company.com",
      phone: "010-4444-4444",
      address: "서울시 금천구",
      birthDate: "1993-05-25",
      education: "서울과기대 전기공학 학사",
      annualLeave: 15,
      usedLeave: 3,
      salary: "3,800,000",
      performance: 85,
      status: "재직",
      kpi: [
        { metric: "설비 가동률", target: 90, actual: 93, unit: "%" },
        { metric: "고장 처리시간", target: 4, actual: 3, unit: "시간" },
        { metric: "예방정비 수행률", target: 100, actual: 100, unit: "%" }
      ]
    },
    {
      id: "EMP005",
      name: "최자재",
      position: "주임",
      department: "자재부",
      team: "구매팀",
      joinDate: "2020-02-15",
      email: "choi@company.com",
      phone: "010-5555-5555",
      address: "경기도 광명시",
      birthDate: "1990-08-30",
      education: "중앙대 물류학 학사",
      annualLeave: 15,
      usedLeave: 10,
      salary: "4,200,000",
      performance: 90,
      status: "재직",
      kpi: [
        { metric: "구매 절감률", target: 5, actual: 7, unit: "%" },
        { metric: "납기 준수율", target: 95, actual: 96, unit: "%" },
        { metric: "재고 회전율", target: 12, actual: 14, unit: "회" }
      ]
    }
  ];

  // 조직도 데이터
  const organizationData = {
    name: "김대표",
    position: "대표이사",
    children: [
      {
        name: "생산부",
        position: "부장",
        children: [
          { name: "생산1팀", position: "이생산 (과장)", members: 8 },
          { name: "생산2팀", position: "강생산 (과장)", members: 7 }
        ]
      },
      {
        name: "품질부",
        position: "부장",
        children: [
          { name: "품질관리팀", position: "박품질 (대리)", members: 5 },
          { name: "품질보증팀", position: "오품질 (대리)", members: 4 }
        ]
      },
      {
        name: "영업부",
        position: "부장",
        children: [
          { name: "영업1팀", position: "김영업 (과장)", members: 6 },
          { name: "영업2팀", position: "이영업 (과장)", members: 5 }
        ]
      },
      {
        name: "지원부",
        position: "부장",
        children: [
          { name: "인사팀", position: "박인사 (과장)", members: 3 },
          { name: "총무팀", position: "최총무 (대리)", members: 4 },
          { name: "회계팀", position: "정회계 (과장)", members: 4 }
        ]
      }
    ]
  };

  // 승진 후보 데이터
  const promotionCandidates = [
    {
      id: "EMP002",
      name: "이생산",
      currentPosition: "과장",
      targetPosition: "차장",
      department: "생산부",
      yearsInPosition: 3.5,
      performance: 88,
      evaluationScore: 92,
      status: "후보",
      expectedDate: "2025-01-01"
    },
    {
      id: "EMP003",
      name: "박품질",
      currentPosition: "대리",
      targetPosition: "과장",
      department: "품질부",
      yearsInPosition: 2.8,
      performance: 92,
      evaluationScore: 90,
      status: "후보",
      expectedDate: "2025-01-01"
    },
    {
      id: "EMP005",
      name: "최자재",
      currentPosition: "주임",
      targetPosition: "대리",
      department: "자재부",
      yearsInPosition: 2.2,
      performance: 90,
      evaluationScore: 88,
      status: "검토중",
      expectedDate: "2025-03-01"
    }
  ];

  // 부서별 통계
  const departmentStats = [
    { department: "생산부", count: 15, avgPerformance: 87 },
    { department: "품질부", count: 9, avgPerformance: 90 },
    { department: "영업부", count: 11, avgPerformance: 85 },
    { department: "설비부", count: 6, avgPerformance: 86 },
    { department: "자재부", count: 7, avgPerformance: 88 },
    { department: "지원부", count: 11, avgPerformance: 84 }
  ];

  // 직급별 분포
  const positionDistribution = [
    { position: "임원", count: 1 },
    { position: "부장", count: 4 },
    { position: "차장", count: 6 },
    { position: "과장", count: 12 },
    { position: "대리", count: 15 },
    { position: "주임", count: 10 },
    { position: "사원", count: 11 }
  ];

  const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4'];

  const getPerformanceBadge = (score: number) => {
    if (score >= 90) return <Badge className="bg-green-500 text-white">우수</Badge>;
    if (score >= 80) return <Badge className="bg-blue-500 text-white">양호</Badge>;
    if (score >= 70) return <Badge className="bg-yellow-500 text-white">보통</Badge>;
    return <Badge className="bg-red-500 text-white">미흡</Badge>;
  };

  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, string> = {
      "재직": "bg-green-500 text-white",
      "휴직": "bg-yellow-500 text-white",
      "퇴직": "bg-gray-500 text-white",
    };
    return <Badge className={statusConfig[status] || "bg-gray-500 text-white"}>{status}</Badge>;
  };

  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">조직, 인사, 평가, KPI 관리</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" className="border-border/50">
              <Download className="h-4 w-4 mr-2" />
              인사 데이터 다운로드
            </Button>
            <Dialog open={isAddEmployeeOpen} onOpenChange={setIsAddEmployeeOpen}>
              <DialogTrigger asChild>
                <Button className="bg-primary text-primary-foreground">
                  <UserPlus className="h-4 w-4 mr-2" />
                  직원 등록
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-[95vw] sm:max-w-2xl md:max-w-5xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>신규 직원 등록</DialogTitle>
                  <DialogDescription>새로운 직원의 정보를 입력하세요.</DialogDescription>
                </DialogHeader>
                <div className="space-y-6">
                  <div className="bg-muted/50 p-4 rounded-lg">
                    <h3 className="font-bold text-lg mb-4">기본 정보</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="name">이름 *</Label>
                        <Input id="name" placeholder="홍길동" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="employeeId">사번</Label>
                        <Input id="employeeId" placeholder="EMP006" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="department">부서 *</Label>
                        <Select>
                          <SelectTrigger>
                            <SelectValue placeholder="선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="생산부">생산부</SelectItem>
                            <SelectItem value="품질부">품질부</SelectItem>
                            <SelectItem value="영업부">영업부</SelectItem>
                            <SelectItem value="설비부">설비부</SelectItem>
                            <SelectItem value="자재부">자재부</SelectItem>
                            <SelectItem value="지원부">지원부</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="position">직급 *</Label>
                        <Select>
                          <SelectTrigger>
                            <SelectValue placeholder="선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="사원">사원</SelectItem>
                            <SelectItem value="주임">주임</SelectItem>
                            <SelectItem value="대리">대리</SelectItem>
                            <SelectItem value="과장">과장</SelectItem>
                            <SelectItem value="차장">차장</SelectItem>
                            <SelectItem value="부장">부장</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="joinDate">입사일 *</Label>
                        <Input id="joinDate" type="date" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="birthDate">생년월일</Label>
                        <Input id="birthDate" type="date" />
                      </div>
                    </div>
                  </div>

                  <div className="bg-muted/50 p-4 rounded-lg">
                    <h3 className="font-bold text-lg mb-4">연락처</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="email">이메일 *</Label>
                        <Input id="email" type="email" placeholder="name@company.com" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="phone">전화번호 *</Label>
                        <Input id="phone" placeholder="010-0000-0000" />
                      </div>
                      <div className="space-y-2 col-span-2">
                        <Label htmlFor="address">주소</Label>
                        <Input id="address" placeholder="서울시 강남구..." />
                      </div>
                    </div>
                  </div>

                  <div className="bg-muted/50 p-4 rounded-lg">
                    <h3 className="font-bold text-lg mb-4">학력 및 경력</h3>
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="education">최종학력</Label>
                        <Input id="education" placeholder="예) 서울대 경영학 학사" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="career">경력사항</Label>
                        <Textarea id="career" placeholder="이전 경력을 입력하세요" rows={3} />
                      </div>
                    </div>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsAddEmployeeOpen(false)}>
                    취소
                  </Button>
                  <Button className="bg-primary" onClick={() => setIsAddEmployeeOpen(false)}>
                    등록
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <Card className="border border-border/20">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">총 직원수</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-foreground">59명</div>
            <p className="text-sm text-green-600 mt-1">
              <TrendingUp className="h-3 w-3 inline mr-1" />
              전월 대비 +3명
            </p>
          </CardContent>
        </Card>

        <Card className="border border-border/20">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">평균 근속연수</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-blue-600">4.2년</div>
            <p className="text-sm text-muted-foreground mt-1">안정적 유지</p>
          </CardContent>
        </Card>

        <Card className="border border-border/20">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">평균 성과점수</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-green-600">87점</div>
            <p className="text-sm text-green-600 mt-1">
              목표 대비 +7점
            </p>
          </CardContent>
        </Card>

        <Card className="border border-border/20">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">승진 예정자</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-purple-600">5명</div>
            <p className="text-sm text-muted-foreground mt-1">2025년 1월</p>
          </CardContent>
        </Card>

        <Card className="border border-border/20">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">이직률</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-yellow-600">5.2%</div>
            <p className="text-sm text-muted-foreground mt-1">업계 평균 이하</p>
          </CardContent>
        </Card>
      </div>

      {/* 탭 메뉴 */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-5 h-auto p-1 bg-muted/50 rounded-xl">
          <TabsTrigger value="organization" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Network className="h-4 w-4 mr-2" />
            조직도
          </TabsTrigger>
          <TabsTrigger value="employees" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Users className="h-4 w-4 mr-2" />
            직원 관리
          </TabsTrigger>
          <TabsTrigger value="leave" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Calendar className="h-4 w-4 mr-2" />
            연차 관리
          </TabsTrigger>
          <TabsTrigger value="promotion" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Award className="h-4 w-4 mr-2" />
            승진 관리
          </TabsTrigger>
          <TabsTrigger value="kpi" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Target className="h-4 w-4 mr-2" />
            KPI 관리
          </TabsTrigger>
        </TabsList>

        {/* 조직도 */}
        <TabsContent value="organization" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 조직도 시각화 */}
            <Card className="border border-border/20 md:col-span-2">
              <CardHeader>
                <CardTitle>조직 구조</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* CEO */}
                  <div className="flex justify-center">
                    <div className="bg-primary text-primary-foreground p-4 rounded-lg text-center w-48">
                      <Building2 className="h-6 w-6 mx-auto mb-2" />
                      <p className="font-bold">{organizationData.name}</p>
                      <p className="text-sm">{organizationData.position}</p>
                    </div>
                  </div>

                  {/* 부서 */}
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    {organizationData.children?.map((dept, idx) => (
                      <div key={idx} className="space-y-3">
                        <div className="bg-blue-100 dark:bg-blue-900/30 p-3 rounded-lg text-center">
                          <p className="font-bold text-sm">{dept.name}</p>
                          <p className="text-xs text-muted-foreground">{dept.position}</p>
                        </div>
                        {dept.children?.map((team, tidx) => (
                          <div key={tidx} className="bg-muted/50 p-2 rounded text-center ml-2">
                            <p className="text-sm font-medium">{team.name}</p>
                            <p className="text-xs text-muted-foreground">{team.position}</p>
                            <Badge variant="outline" className="mt-1 text-xs">
                              {team.members}명
                            </Badge>
                          </div>
                        ))}
                      </div>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 부서별 인원 통계 */}
            <Card className="border border-border/20">
              <CardHeader>
                <CardTitle>부서별 인원</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300} minHeight={300}>
                  <PieChart>
                    <Pie
                      data={departmentStats}
                      dataKey="count"
                      nameKey="department"
                      cx="50%"
                      cy="50%"
                      outerRadius={100}
                      label={(entry) => `${entry.department} (${entry.count})`}
                    >
                      {departmentStats.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* 직급별 분포 */}
            <Card className="border border-border/20">
              <CardHeader>
                <CardTitle>직급별 분포</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={positionDistribution}
                      dataKey="count"
                      nameKey="position"
                      cx="50%"
                      cy="50%"
                      outerRadius={100}
                      label={(entry) => `${entry.position} (${entry.count})`}
                    >
                      {positionDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* 직원 관리 */}
        <TabsContent value="employees" className="space-y-4">
          {/* 검색 및 필터 */}
          <Card className="border border-border/20">
            <CardContent className="pt-6">
              <div className="flex flex-col md:flex-row gap-4">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input placeholder="이름, 부서로 검색..." className="pl-10" />
                </div>
                <Select>
                  <SelectTrigger className="w-full md:w-48">
                    <SelectValue placeholder="부서" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">전체</SelectItem>
                    <SelectItem value="생산부">생산부</SelectItem>
                    <SelectItem value="품질부">품질부</SelectItem>
                    <SelectItem value="영업부">영업부</SelectItem>
                  </SelectContent>
                </Select>
                <Select>
                  <SelectTrigger className="w-full md:w-48">
                    <SelectValue placeholder="직급" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">전체</SelectItem>
                    <SelectItem value="부장">부장</SelectItem>
                    <SelectItem value="과장">과장</SelectItem>
                    <SelectItem value="대리">대리</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* 직원 목록 */}
          <Card className="border border-border/20">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead>사번</TableHead>
                    <TableHead>이름</TableHead>
                    <TableHead>부서</TableHead>
                    <TableHead>직급</TableHead>
                    <TableHead>입사일</TableHead>
                    <TableHead>연락처</TableHead>
                    <TableHead>성과</TableHead>
                    <TableHead>상태</TableHead>
                    <TableHead className="text-center">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {employees.map((emp) => (
                    <TableRow key={emp.id} className="hover:bg-muted/50">
                      <TableCell className="font-mono text-sm">{emp.id}</TableCell>
                      <TableCell className="font-medium">{emp.name}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{emp.department}</Badge>
                      </TableCell>
                      <TableCell>{emp.position}</TableCell>
                      <TableCell className="text-sm">{emp.joinDate}</TableCell>
                      <TableCell className="text-sm">{emp.phone}</TableCell>
                      <TableCell>{getPerformanceBadge(emp.performance)}</TableCell>
                      <TableCell>{getStatusBadge(emp.status)}</TableCell>
                      <TableCell>
                        <div className="flex items-center justify-center space-x-2">
                          <Button variant="ghost" size="sm">
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <Edit className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 연차 관리 */}
        <TabsContent value="leave" className="space-y-4">
          <Card className="border border-border/20">
            <CardHeader>
              <CardTitle>직원별 연차 현황</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead>이름</TableHead>
                    <TableHead>부서</TableHead>
                    <TableHead>직급</TableHead>
                    <TableHead className="text-right">총 연차</TableHead>
                    <TableHead className="text-right">사용</TableHead>
                    <TableHead className="text-right">잔여</TableHead>
                    <TableHead>사용률</TableHead>
                    <TableHead className="text-center">상세</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {employees.filter(e => e.annualLeave > 0).map((emp) => {
                    const remaining = emp.annualLeave - emp.usedLeave;
                    const usageRate = (emp.usedLeave / emp.annualLeave) * 100;
                    return (
                      <TableRow key={emp.id} className="hover:bg-muted/50">
                        <TableCell className="font-medium">{emp.name}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{emp.department}</Badge>
                        </TableCell>
                        <TableCell>{emp.position}</TableCell>
                        <TableCell className="text-right font-bold">{emp.annualLeave}일</TableCell>
                        <TableCell className="text-right text-blue-600">{emp.usedLeave}일</TableCell>
                        <TableCell className="text-right text-green-600">{remaining}일</TableCell>
                        <TableCell>
                          <div className="space-y-1">
                            <Progress value={usageRate} className="h-2" />
                            <p className="text-xs text-muted-foreground">{usageRate.toFixed(0)}%</p>
                          </div>
                        </TableCell>
                        <TableCell className="text-center">
                          <Button variant="ghost" size="sm">
                            <Eye className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 승진 관리 */}
        <TabsContent value="promotion" className="space-y-4">
          <Card className="border border-border/20">
            <CardHeader>
              <CardTitle>승진 후보자</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead>이름</TableHead>
                    <TableHead>현재 직급</TableHead>
                    <TableHead>승진 예정 직급</TableHead>
                    <TableHead>부서</TableHead>
                    <TableHead>현 직급 근속</TableHead>
                    <TableHead>성과 점수</TableHead>
                    <TableHead>평가 점수</TableHead>
                    <TableHead>상태</TableHead>
                    <TableHead>예정일</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {promotionCandidates.map((candidate) => (
                    <TableRow key={candidate.id} className="hover:bg-muted/50">
                      <TableCell className="font-medium">{candidate.name}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{candidate.currentPosition}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge className="bg-purple-500 text-white">
                          <Award className="h-3 w-3 mr-1" />
                          {candidate.targetPosition}
                        </Badge>
                      </TableCell>
                      <TableCell>{candidate.department}</TableCell>
                      <TableCell>{candidate.yearsInPosition}년</TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Progress value={candidate.performance} className="h-2 w-16" />
                          <span className="text-sm">{candidate.performance}점</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Progress value={candidate.evaluationScore} className="h-2 w-16" />
                          <span className="text-sm">{candidate.evaluationScore}점</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={candidate.status === "후보" ? "bg-green-500 text-white" : "bg-yellow-500 text-white"}>
                          {candidate.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm">{candidate.expectedDate}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* KPI 관리 */}
        <TabsContent value="kpi" className="space-y-4">
          {employees.slice(0, 3).map((emp) => (
            <Card key={emp.id} className="border border-border/20">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <div className="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center">
                      <User className="h-6 w-6 text-primary" />
                    </div>
                    <div>
                      <CardTitle>{emp.name}</CardTitle>
                      <p className="text-sm text-muted-foreground">
                        {emp.department} · {emp.position}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-muted-foreground">종합 성과</p>
                    <p className="text-2xl font-bold text-primary">{emp.performance}점</p>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {emp.kpi.map((kpi, idx) => {
                    const achievement = (kpi.actual / kpi.target) * 100;
                    const isGood = kpi.metric.includes("불량률") || kpi.metric.includes("처리시간") || kpi.metric.includes("클레임")
                      ? kpi.actual <= kpi.target
                      : kpi.actual >= kpi.target;

                    return (
                      <div key={idx} className="space-y-2">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-2">
                            <Target className="h-4 w-4 text-primary" />
                            <span className="font-medium">{kpi.metric}</span>
                          </div>
                          <div className="text-right">
                            <span className="font-bold text-lg">
                              {kpi.actual}{kpi.unit}
                            </span>
                            <span className="text-sm text-muted-foreground ml-2">
                              / 목표 {kpi.target}{kpi.unit}
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center space-x-3">
                          <Progress value={Math.min(achievement, 100)} className="h-3" />
                          <Badge className={isGood ? "bg-green-500 text-white" : "bg-red-500 text-white"}>
                            {achievement.toFixed(0)}%
                          </Badge>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </CardContent>
            </Card>
          ))}
        </TabsContent>
      </Tabs>
    </div>
  );
}