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 {
  FileText,
  Plus,
  Search,
  Download,
  Send,
  CheckCircle,
  Clock,
  XCircle,
  Eye,
  Printer,
  User,
  DollarSign,
  ShoppingCart,
  Plane,
  FileSignature,
  ArrowRight,
  ArrowLeft,
  TrendingUp,
  AlertCircle,
  Users
} from "lucide-react";

export function ApprovalManagement() {
  const [activeTab, setActiveTab] = useState("pending");
  const [isNewDocumentOpen, setIsNewDocumentOpen] = useState(false);
  const [documentType, setDocumentType] = useState("");
  const [documentStep, setDocumentStep] = useState(1);
  const [selectedDocument, setSelectedDocument] = useState<any>(null);
  const [isViewDocumentOpen, setIsViewDocumentOpen] = useState(false);
  const [isPrintMode, setIsPrintMode] = useState(false);
  const [approvalComment, setApprovalComment] = useState("");
  const [approvalTemplates, setApprovalTemplates] = useState([
    {
      name: "기본 결재선",
      approvers: [
        { level: 1, name: "박팀장", position: "팀장", status: "대기" },
        { level: 2, name: "김부장", position: "부장", status: "대기" },
        { level: 3, name: "김대표", position: "대표이사", status: "대기" }
      ]
    },
    {
      name: "간단 결재선 (팀장-대표)",
      approvers: [
        { level: 1, name: "박팀장", position: "팀장", status: "대기" },
        { level: 2, name: "김대표", position: "대표이사", status: "대기" }
      ]
    },
    {
      name: "고액 결재선",
      approvers: [
        { level: 1, name: "박팀장", position: "팀장", status: "대기" },
        { level: 2, name: "한차장", position: "차장", status: "대기" },
        { level: 3, name: "김부장", position: "부장", status: "대기" },
        { level: 4, name: "김대표", position: "대표이사", status: "대기" }
      ]
    }
  ]);
  
  // 문서 양식 데이터
  const [formData, setFormData] = useState({
    // 공통 정보
    drafter: "이생산",
    department: "생산부",
    position: "과장",
    draftDate: new Date().toISOString().split('T')[0],
    title: "",
    
    // 지출결의서
    expenseType: "",
    expenseAmount: 0,
    expenseDate: "",
    expenseVendor: "",
    expenseAccount: "",
    expenseReason: "",
    
    // 품의서
    proposalSubject: "",
    proposalBackground: "",
    proposalContent: "",
    proposalExpectedEffect: "",
    proposalBudget: 0,
    
    // 휴가신청서
    leaveType: "",
    leaveStartDate: "",
    leaveEndDate: "",
    leaveDays: 0,
    leaveReason: "",
    leaveEmergencyContact: "",
    
    // 구매요청서
    purchaseItem: "",
    purchaseQuantity: 0,
    purchaseUnitPrice: 0,
    purchaseTotalAmount: 0,
    purchaseVendor: "",
    purchaseDeliveryDate: "",
    purchasePurpose: "",
    
    // 결재선
    approvers: [
      { level: 1, name: "박팀장", position: "팀장", status: "대기" },
      { level: 2, name: "김부장", position: "부장", status: "대기" },
      { level: 3, name: "김대표", position: "대표이사", status: "대기" }
    ]
  });

  // 결재 문서 목록
  const documents = [
    {
      id: "DOC-2024-001",
      type: "지출결의서",
      title: "사무용품 구매 지출",
      drafter: "이생산",
      drafterPosition: "과장",
      department: "생산부",
      draftDate: "2024-10-10",
      amount: 350000,
      status: "승인대기",
      currentApprover: "박팀장",
      approvalLine: [
        { name: "박팀장", position: "팀장", status: "대기", date: "", comment: "" },
        { name: "김부장", position: "부장", status: "대기", date: "", comment: "" },
        { name: "김대표", position: "대표이사", status: "대기", date: "", comment: "" }
      ],
      urgency: "보통",
      details: {
        expenseType: "사무용품",
        expenseDate: "2024-10-09",
        expenseVendor: "ABC문구",
        expenseAccount: "소모품비",
        expenseReason: "프린터 토너 및 복사용지 구매 필요"
      }
    },
    {
      id: "DOC-2024-002",
      type: "휴가신청서",
      title: "연차 사용 신청",
      drafter: "정설비",
      drafterPosition: "사원",
      department: "설비부",
      draftDate: "2024-10-11",
      amount: 0,
      status: "승인완료",
      currentApprover: "-",
      approvalLine: [
        { name: "박팀장", position: "팀장", status: "승인", date: "2024-10-11", comment: "승인합니다" },
        { name: "김대표", position: "대표이사", status: "승인", date: "2024-10-11", comment: "승인" }
      ],
      urgency: "보통",
      details: {
        leaveType: "연차",
        leaveStartDate: "2024-10-15",
        leaveEndDate: "2024-10-16",
        leaveDays: 2,
        leaveReason: "가족 여행",
        leaveEmergencyContact: "010-4444-4444"
      }
    },
    {
      id: "DOC-2024-003",
      type: "품의서",
      title: "신규 설비 도입 건",
      drafter: "박품질",
      drafterPosition: "대리",
      department: "품질부",
      draftDate: "2024-10-09",
      amount: 15000000,
      status: "진행중",
      currentApprover: "김부장",
      approvalLine: [
        { name: "박팀장", position: "팀장", status: "승인", date: "2024-10-09", comment: "품질 향상에 필요" },
        { name: "김부장", position: "부장", status: "대기", date: "", comment: "" },
        { name: "김대표", position: "대표이사", status: "대기", date: "", comment: "" }
      ],
      urgency: "긴급",
      details: {
        proposalSubject: "자동 검사 설비 도입",
        proposalBackground: "현재 수작업 검사로 인한 시간 지연 및 인적 오류 발생",
        proposalContent: "AI 기반 자동 검사 설비를 도입하여 검사 시간을 50% 단축하고 정확도를 99.5%로 향상",
        proposalExpectedEffect: "검사 시간 단축, 불량률 감소, 인건비 절감",
        proposalBudget: 15000000
      }
    },
    {
      id: "DOC-2024-004",
      type: "구매요청서",
      title: "원자재 긴급 구매",
      drafter: "최자재",
      drafterPosition: "주임",
      department: "자재부",
      draftDate: "2024-10-08",
      amount: 2500000,
      status: "반려",
      currentApprover: "-",
      approvalLine: [
        { name: "박팀장", position: "팀장", status: "반려", date: "2024-10-08", comment: "재고 확인 후 재신청 요망" }
      ],
      urgency: "긴급",
      details: {
        purchaseItem: "알루미늄 가이드레일",
        purchaseQuantity: 500,
        purchaseUnitPrice: 5000,
        purchaseTotalAmount: 2500000,
        purchaseVendor: "알텍솔루션",
        purchaseDeliveryDate: "2024-10-15",
        purchasePurpose: "생산 계획 대비 재고 부족"
      }
    },
  ];

  const handleApprove = (docId: string) => {
    console.log("문서 승인:", docId, "의견:", approvalComment);
    alert("문서가 승인되었습니다.");
    setIsViewDocumentOpen(false);
    setApprovalComment("");
  };

  const handleReject = (docId: string) => {
    if (!approvalComment.trim()) {
      alert("반려 사유를 입력해주세요.");
      return;
    }
    console.log("문서 반려:", docId, "사유:", approvalComment);
    alert("문서가 반려되었습니다.");
    setIsViewDocumentOpen(false);
    setApprovalComment("");
  };

  const handlePrint = () => {
    setIsPrintMode(true);
    setTimeout(() => {
      window.print();
      setIsPrintMode(false);
    }, 100);
  };

  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, { className: string }> = {
      "승인대기": { className: "bg-yellow-500 text-white" },
      "진행중": { className: "bg-blue-500 text-white" },
      "승인완료": { className: "bg-green-500 text-white" },
      "반려": { className: "bg-red-500 text-white" },
    };

    const config = statusConfig[status] || { className: "bg-gray-500 text-white" };
    
    return (
      <Badge className={config.className}>
        {status}
      </Badge>
    );
  };

  const getUrgencyBadge = (urgency: string) => {
    const urgencyConfig: Record<string, string> = {
      "긴급": "bg-red-100 text-red-800 border-red-300",
      "보통": "bg-blue-100 text-blue-800 border-blue-300",
      "낮음": "bg-gray-100 text-gray-800 border-gray-300",
    };

    return (
      <Badge variant="outline" className={urgencyConfig[urgency]}>
        {urgency}
      </Badge>
    );
  };

  const documentTypes = [
    { value: "expense", label: "지출결의서", icon: DollarSign },
    { value: "proposal", label: "품의서", icon: FileSignature },
    { value: "leave", label: "휴가신청서", icon: Plane },
    { value: "purchase", label: "구매요청서", icon: ShoppingCart },
  ];

  // 결재 가능한 임직원 목록
  const availableApprovers = [
    { name: "김대표", position: "대표이사", department: "경영진" },
    { name: "김부장", position: "부장", department: "생산부" },
    { name: "박부장", position: "부장", department: "품질부" },
    { name: "이부장", position: "부장", department: "영업부" },
    { name: "최부장", position: "부장", department: "지원부" },
    { name: "박팀장", position: "팀장", department: "생산1팀" },
    { name: "강팀장", position: "팀장", department: "생산2팀" },
    { name: "오팀장", position: "팀장", department: "품질팀" },
    { name: "정팀장", position: "팀장", department: "영업팀" },
    { name: "윤팀장", position: "팀장", department: "인사팀" },
    { name: "한차장", position: "차장", department: "생산부" },
    { name: "송차장", position: "차장", department: "품질부" },
  ];

  const handleNextStep = () => {
    setDocumentStep(prev => Math.min(prev + 1, 3));
  };

  const handlePrevStep = () => {
    setDocumentStep(prev => Math.max(prev - 1, 1));
  };

  const handleSubmit = () => {
    console.log("결재 문서 제출:", formData);
    setIsNewDocumentOpen(false);
    setDocumentStep(1);
    setDocumentType("");
  };

  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" className="border-border/50">
              <Download className="h-4 w-4 mr-2" />
              양식 다운로드
            </Button>
            <Dialog open={isNewDocumentOpen} onOpenChange={setIsNewDocumentOpen}>
              <DialogTrigger asChild>
                <Button className="bg-primary text-primary-foreground">
                  <Plus className="h-4 w-4 mr-2" />
                  새 결재 작성
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-[95vw] sm:max-w-xl md:max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle className="text-2xl flex items-center space-x-3">
                    <FileText className="h-6 w-6 text-primary" />
                    <span>결재 문서 작성</span>
                  </DialogTitle>
                  <DialogDescription>
                    문서 종류를 선택하고 내용을 작성하세요.
                  </DialogDescription>
                </DialogHeader>

                {/* 진행 단계 */}
                <div className="flex items-center justify-between mb-6">
                  <div className={`flex items-center space-x-2 ${documentStep >= 1 ? 'text-primary' : 'text-muted-foreground'}`}>
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center ${documentStep >= 1 ? 'bg-primary text-white' : 'bg-muted'}`}>
                      1
                    </div>
                    <span className="font-medium">문서선택</span>
                  </div>
                  <div className="flex-1 h-0.5 bg-muted mx-4" />
                  <div className={`flex items-center space-x-2 ${documentStep >= 2 ? 'text-primary' : 'text-muted-foreground'}`}>
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center ${documentStep >= 2 ? 'bg-primary text-white' : 'bg-muted'}`}>
                      2
                    </div>
                    <span className="font-medium">내용작성</span>
                  </div>
                  <div className="flex-1 h-0.5 bg-muted mx-4" />
                  <div className={`flex items-center space-x-2 ${documentStep >= 3 ? 'text-primary' : 'text-muted-foreground'}`}>
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center ${documentStep >= 3 ? 'bg-primary text-white' : 'bg-muted'}`}>
                      3
                    </div>
                    <span className="font-medium">결재선</span>
                  </div>
                </div>

                {/* Step 1: 문서 종류 선택 */}
                {documentStep === 1 && (
                  <div className="space-y-4">
                    <h3 className="font-bold text-lg">문서 종류를 선택하세요</h3>
                    <div className="grid grid-cols-2 gap-4">
                      {documentTypes.map((type) => {
                        const Icon = type.icon;
                        return (
                          <div
                            key={type.value}
                            onClick={() => {
                              setDocumentType(type.value);
                              handleNextStep();
                            }}
                            className={`cursor-pointer p-6 border-2 rounded-lg transition-all hover:shadow-lg ${
                              documentType === type.value
                                ? 'border-primary bg-primary/5'
                                : 'border-border hover:border-primary/50'
                            }`}
                          >
                            <Icon className="h-12 w-12 text-primary mb-3" />
                            <h4 className="font-bold text-lg">{type.label}</h4>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* Step 2: 내용 작성 */}
                {documentStep === 2 && (
                  <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>기안자</Label>
                          <Input value={formData.drafter} readOnly className="bg-muted/50" />
                        </div>
                        <div className="space-y-2">
                          <Label>부서</Label>
                          <Input value={formData.department} readOnly className="bg-muted/50" />
                        </div>
                        <div className="space-y-2">
                          <Label>직급</Label>
                          <Input value={formData.position} readOnly className="bg-muted/50" />
                        </div>
                        <div className="space-y-2">
                          <Label>기안일자</Label>
                          <Input value={formData.draftDate} readOnly className="bg-muted/50" />
                        </div>
                      </div>
                    </div>

                    {/* 지출결의서 */}
                    {documentType === "expense" && (
                      <div className="bg-muted/50 p-4 rounded-lg space-y-4">
                        <h3 className="font-bold text-lg">지출 내역</h3>
                        <div className="space-y-2">
                          <Label htmlFor="title">제목 *</Label>
                          <Input
                            id="title"
                            placeholder="예) 사무용품 구매 지출"
                            value={formData.title}
                            onChange={(e) => setFormData({...formData, title: e.target.value})}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="expenseType">지출 항목 *</Label>
                            <Select value={formData.expenseType} onValueChange={(value) => setFormData({...formData, expenseType: value})}>
                              <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="expenseAmount">금액 *</Label>
                            <Input
                              id="expenseAmount"
                              type="number"
                              placeholder="0"
                              value={formData.expenseAmount}
                              onChange={(e) => setFormData({...formData, expenseAmount: parseInt(e.target.value) || 0})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="expenseDate">지출 일자</Label>
                            <Input
                              id="expenseDate"
                              type="date"
                              value={formData.expenseDate}
                              onChange={(e) => setFormData({...formData, expenseDate: e.target.value})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="expenseVendor">거래처</Label>
                            <Input
                              id="expenseVendor"
                              placeholder="예) ABC문구"
                              value={formData.expenseVendor}
                              onChange={(e) => setFormData({...formData, expenseVendor: e.target.value})}
                            />
                          </div>
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="expenseAccount">계정과목</Label>
                          <Select value={formData.expenseAccount} onValueChange={(value) => setFormData({...formData, expenseAccount: value})}>
                            <SelectTrigger>
                              <SelectValue placeholder="선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              <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="expenseReason">지출 사유 *</Label>
                          <Textarea
                            id="expenseReason"
                            placeholder="지출 사유를 상세히 입력하세요"
                            value={formData.expenseReason}
                            onChange={(e) => setFormData({...formData, expenseReason: e.target.value})}
                            rows={4}
                          />
                        </div>
                      </div>
                    )}

                    {/* 품의서 */}
                    {documentType === "proposal" && (
                      <div className="bg-muted/50 p-4 rounded-lg space-y-4">
                        <h3 className="font-bold text-lg">품의 내용</h3>
                        <div className="space-y-2">
                          <Label htmlFor="title">제목 *</Label>
                          <Input
                            id="title"
                            placeholder="예) 신규 설비 도입 건"
                            value={formData.title}
                            onChange={(e) => setFormData({...formData, title: e.target.value})}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="proposalSubject">품의 주제 *</Label>
                          <Input
                            id="proposalSubject"
                            placeholder="품의 주제를 입력하세요"
                            value={formData.proposalSubject}
                            onChange={(e) => setFormData({...formData, proposalSubject: e.target.value})}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="proposalBackground">추진 배경</Label>
                          <Textarea
                            id="proposalBackground"
                            placeholder="추진하게 된 배경을 입력하세요"
                            value={formData.proposalBackground}
                            onChange={(e) => setFormData({...formData, proposalBackground: e.target.value})}
                            rows={3}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="proposalContent">품의 내용 *</Label>
                          <Textarea
                            id="proposalContent"
                            placeholder="품의 내용을 상세히 입력하세요"
                            value={formData.proposalContent}
                            onChange={(e) => setFormData({...formData, proposalContent: e.target.value})}
                            rows={5}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="proposalExpectedEffect">기대 효과</Label>
                          <Textarea
                            id="proposalExpectedEffect"
                            placeholder="기대되는 효과를 입력하세요"
                            value={formData.proposalExpectedEffect}
                            onChange={(e) => setFormData({...formData, proposalExpectedEffect: e.target.value})}
                            rows={3}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="proposalBudget">소요 예산</Label>
                          <Input
                            id="proposalBudget"
                            type="number"
                            placeholder="0"
                            value={formData.proposalBudget}
                            onChange={(e) => setFormData({...formData, proposalBudget: parseInt(e.target.value) || 0})}
                          />
                        </div>
                      </div>
                    )}

                    {/* 휴가신청서 */}
                    {documentType === "leave" && (
                      <div className="bg-muted/50 p-4 rounded-lg space-y-4">
                        <h3 className="font-bold text-lg">휴가 정보</h3>
                        <div className="space-y-2">
                          <Label htmlFor="title">제목 *</Label>
                          <Input
                            id="title"
                            placeholder="예) 연차 사용 신청"
                            value={formData.title}
                            onChange={(e) => setFormData({...formData, title: e.target.value})}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="leaveType">휴가 종류 *</Label>
                            <Select value={formData.leaveType} onValueChange={(value) => setFormData({...formData, leaveType: value})}>
                              <SelectTrigger>
                                <SelectValue placeholder="선택하세요" />
                              </SelectTrigger>
                              <SelectContent>
                                <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="leaveDays">사용 일수</Label>
                            <Input
                              id="leaveDays"
                              type="number"
                              step="0.5"
                              placeholder="1"
                              value={formData.leaveDays}
                              onChange={(e) => setFormData({...formData, leaveDays: parseFloat(e.target.value) || 0})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="leaveStartDate">시작일 *</Label>
                            <Input
                              id="leaveStartDate"
                              type="date"
                              value={formData.leaveStartDate}
                              onChange={(e) => setFormData({...formData, leaveStartDate: e.target.value})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="leaveEndDate">종료일 *</Label>
                            <Input
                              id="leaveEndDate"
                              type="date"
                              value={formData.leaveEndDate}
                              onChange={(e) => setFormData({...formData, leaveEndDate: e.target.value})}
                            />
                          </div>
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="leaveReason">휴가 사유</Label>
                          <Textarea
                            id="leaveReason"
                            placeholder="휴가 사유를 입력하세요"
                            value={formData.leaveReason}
                            onChange={(e) => setFormData({...formData, leaveReason: e.target.value})}
                            rows={3}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="leaveEmergencyContact">긴급 연락처</Label>
                          <Input
                            id="leaveEmergencyContact"
                            placeholder="010-0000-0000"
                            value={formData.leaveEmergencyContact}
                            onChange={(e) => setFormData({...formData, leaveEmergencyContact: e.target.value})}
                          />
                        </div>
                      </div>
                    )}

                    {/* 구매요청서 */}
                    {documentType === "purchase" && (
                      <div className="bg-muted/50 p-4 rounded-lg space-y-4">
                        <h3 className="font-bold text-lg">구매 정보</h3>
                        <div className="space-y-2">
                          <Label htmlFor="title">제목 *</Label>
                          <Input
                            id="title"
                            placeholder="예) 원자재 긴급 구매"
                            value={formData.title}
                            onChange={(e) => setFormData({...formData, title: e.target.value})}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="purchaseItem">구매 품목 *</Label>
                            <Input
                              id="purchaseItem"
                              placeholder="품목명"
                              value={formData.purchaseItem}
                              onChange={(e) => setFormData({...formData, purchaseItem: e.target.value})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="purchaseQuantity">수량 *</Label>
                            <Input
                              id="purchaseQuantity"
                              type="number"
                              placeholder="0"
                              value={formData.purchaseQuantity}
                              onChange={(e) => {
                                const qty = parseInt(e.target.value) || 0;
                                setFormData({
                                  ...formData,
                                  purchaseQuantity: qty,
                                  purchaseTotalAmount: qty * formData.purchaseUnitPrice
                                });
                              }}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="purchaseUnitPrice">단가</Label>
                            <Input
                              id="purchaseUnitPrice"
                              type="number"
                              placeholder="0"
                              value={formData.purchaseUnitPrice}
                              onChange={(e) => {
                                const price = parseInt(e.target.value) || 0;
                                setFormData({
                                  ...formData,
                                  purchaseUnitPrice: price,
                                  purchaseTotalAmount: price * formData.purchaseQuantity
                                });
                              }}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="purchaseTotalAmount">총 금액</Label>
                            <Input
                              id="purchaseTotalAmount"
                              type="number"
                              value={formData.purchaseTotalAmount}
                              readOnly
                              className="bg-muted/50 font-bold"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="purchaseVendor">공급업체</Label>
                            <Input
                              id="purchaseVendor"
                              placeholder="공급업체명"
                              value={formData.purchaseVendor}
                              onChange={(e) => setFormData({...formData, purchaseVendor: e.target.value})}
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="purchaseDeliveryDate">희망 납기일</Label>
                            <Input
                              id="purchaseDeliveryDate"
                              type="date"
                              value={formData.purchaseDeliveryDate}
                              onChange={(e) => setFormData({...formData, purchaseDeliveryDate: e.target.value})}
                            />
                          </div>
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="purchasePurpose">구매 목적 *</Label>
                          <Textarea
                            id="purchasePurpose"
                            placeholder="구매 목적 및 사유를 입력하세요"
                            value={formData.purchasePurpose}
                            onChange={(e) => setFormData({...formData, purchasePurpose: e.target.value})}
                            rows={4}
                          />
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Step 3: 결재선 */}
                {documentStep === 3 && (
                  <div className="space-y-6">
                    <div className="bg-blue-50 dark:bg-blue-950/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
                      <div className="flex items-start justify-between">
                        <div className="flex items-start space-x-3">
                          <Users className="h-5 w-5 text-blue-600 mt-0.5" />
                          <div>
                            <h3 className="font-bold text-blue-900 dark:text-blue-100">결재선 설정</h3>
                            <p className="text-sm text-blue-700 dark:text-blue-300 mt-1">
                              결재자를 추가하고 순서를 설정하세요.
                            </p>
                          </div>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setFormData({
                              ...formData,
                              approvers: [
                                ...formData.approvers,
                                { level: formData.approvers.length + 1, name: "", position: "", status: "대기" }
                              ]
                            });
                          }}
                        >
                          <Plus className="h-4 w-4 mr-2" />
                          결재자 추가
                        </Button>
                      </div>
                    </div>

                    {/* 결재선 템플릿 선택 */}
                    <div className="bg-muted/50 p-4 rounded-lg">
                      <h3 className="font-bold mb-3">결재선 템플릿</h3>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        {approvalTemplates.map((template, idx) => (
                          <div
                            key={idx}
                            className="p-3 border rounded-lg cursor-pointer hover:border-primary hover:bg-primary/5 transition-all"
                            onClick={() => {
                              setFormData({
                                ...formData,
                                approvers: JSON.parse(JSON.stringify(template.approvers))
                              });
                            }}
                          >
                            <p className="font-medium text-sm mb-2">{template.name}</p>
                            <div className="flex items-center space-x-1">
                              {template.approvers.map((approver, aIdx) => (
                                <div key={aIdx} className="flex items-center">
                                  <span className="text-xs text-muted-foreground">{approver.position}</span>
                                  {aIdx < template.approvers.length - 1 && (
                                    <ArrowRight className="h-3 w-3 mx-1 text-muted-foreground" />
                                  )}
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 결재선 편집 */}
                    <div className="bg-muted/50 p-6 rounded-lg">
                      <h3 className="font-bold text-lg mb-4">결재자 목록</h3>
                      <div className="space-y-3">
                        {formData.approvers.map((approver, index) => (
                          <div key={index} className="bg-card p-4 rounded-lg border border-border flex items-center space-x-4">
                            <div className="flex items-center justify-center w-10 h-10 bg-primary/10 rounded-full">
                              <span className="font-bold text-primary">{index + 1}</span>
                            </div>
                            <div className="flex-1 grid grid-cols-2 gap-3">
                              <div className="space-y-1">
                                <Label className="text-xs">결재자</Label>
                                <Select
                                  value={approver.name}
                                  onValueChange={(value) => {
                                    const newApprovers = [...formData.approvers];
                                    const selected = availableApprovers.find(a => a.name === value);
                                    if (selected) {
                                      newApprovers[index] = {
                                        ...newApprovers[index],
                                        name: selected.name,
                                        position: selected.position
                                      };
                                      setFormData({ ...formData, approvers: newApprovers });
                                    }
                                  }}
                                >
                                  <SelectTrigger>
                                    <SelectValue placeholder="선택하세요" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {availableApprovers.map((person) => (
                                      <SelectItem key={person.name} value={person.name}>
                                        {person.name} ({person.position})
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>
                              <div className="space-y-1">
                                <Label className="text-xs">직급</Label>
                                <Input
                                  value={approver.position}
                                  readOnly
                                  className="bg-muted/50"
                                />
                              </div>
                            </div>
                            <div className="flex space-x-2">
                              {index > 0 && (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    const newApprovers = [...formData.approvers];
                                    [newApprovers[index], newApprovers[index - 1]] = [newApprovers[index - 1], newApprovers[index]];
                                    newApprovers.forEach((a, i) => a.level = i + 1);
                                    setFormData({ ...formData, approvers: newApprovers });
                                  }}
                                  title="위로 이동"
                                >
                                  ↑
                                </Button>
                              )}
                              {index < formData.approvers.length - 1 && (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    const newApprovers = [...formData.approvers];
                                    [newApprovers[index], newApprovers[index + 1]] = [newApprovers[index + 1], newApprovers[index]];
                                    newApprovers.forEach((a, i) => a.level = i + 1);
                                    setFormData({ ...formData, approvers: newApprovers });
                                  }}
                                  title="아래로 이동"
                                >
                                  ↓
                                </Button>
                              )}
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => {
                                  const newApprovers = formData.approvers.filter((_, i) => i !== index);
                                  newApprovers.forEach((a, i) => a.level = i + 1);
                                  setFormData({ ...formData, approvers: newApprovers });
                                }}
                                className="text-red-600 hover:text-red-700"
                              >
                                <XCircle className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 결재선 미리보기 */}
                    <div className="bg-muted/50 p-6 rounded-lg">
                      <h3 className="font-bold text-lg mb-4">결재선 미리보기</h3>
                      <div className="flex items-center justify-center flex-wrap gap-4">
                        {formData.approvers.map((approver, index) => (
                          <div key={index} className="flex items-center">
                            <div className="text-center">
                              <div className="w-16 h-16 bg-primary/10 border-2 border-primary rounded-full flex items-center justify-center mb-2">
                                <User className="h-8 w-8 text-primary" />
                              </div>
                              <p className="font-bold">{approver.name || "미정"}</p>
                              <p className="text-sm text-muted-foreground">{approver.position || "-"}</p>
                              <Badge className="mt-2 bg-yellow-500 text-white">
                                {approver.status}
                              </Badge>
                            </div>
                            {index < formData.approvers.length - 1 && (
                              <ArrowRight className="h-6 w-6 text-muted-foreground mx-4" />
                            )}
                          </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-2">
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">문서 종류</span>
                          <span className="font-bold">
                            {documentTypes.find(t => t.value === documentType)?.label}
                          </span>
                        </div>
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">제목</span>
                          <span className="font-bold">{formData.title}</span>
                        </div>
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">기안자</span>
                          <span className="font-bold">{formData.drafter} ({formData.department})</span>
                        </div>
                        <div className="flex justify-between py-2 border-b">
                          <span className="text-muted-foreground">기안일</span>
                          <span className="font-bold">{formData.draftDate}</span>
                        </div>
                        {(formData.expenseAmount > 0 || formData.proposalBudget > 0 || formData.purchaseTotalAmount > 0) && (
                          <div className="flex justify-between py-2 pt-3 border-t-2">
                            <span className="text-lg font-medium">금액</span>
                            <span className="text-2xl font-bold text-primary">
                              {(formData.expenseAmount || formData.proposalBudget || formData.purchaseTotalAmount).toLocaleString()}원
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}

                <DialogFooter className="flex justify-between items-center">
                  <div>
                    {documentStep > 1 && (
                      <Button variant="outline" onClick={handlePrevStep}>
                        <ArrowLeft className="h-4 w-4 mr-2" />
                        이전
                      </Button>
                    )}
                  </div>
                  <div className="flex space-x-2">
                    {documentStep < 3 && documentStep !== 1 && (
                      <Button onClick={handleNextStep}>
                        다음
                        <ArrowRight className="h-4 w-4 ml-2" />
                      </Button>
                    )}
                    {documentStep === 3 && (
                      <Button onClick={handleSubmit} className="bg-primary">
                        <Send className="h-4 w-4 mr-2" />
                        결재 상신
                      </Button>
                    )}
                  </div>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 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-yellow-600">3건</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-blue-600">5건</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">28건</div>
            <p className="text-sm text-green-600 mt-1">
              <TrendingUp className="h-3 w-3 inline mr-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-red-600">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-4 h-auto p-1 bg-muted/50 rounded-xl">
          <TabsTrigger value="pending" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <Clock className="h-4 w-4 mr-2" />
            승인 대기
          </TabsTrigger>
          <TabsTrigger value="approved" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <CheckCircle className="h-4 w-4 mr-2" />
            승인 완료
          </TabsTrigger>
          <TabsTrigger value="rejected" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <XCircle className="h-4 w-4 mr-2" />
            반려
          </TabsTrigger>
          <TabsTrigger value="all" className="py-3 rounded-lg data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
            <FileText className="h-4 w-4 mr-2" />
            전체 문서
          </TabsTrigger>
        </TabsList>

        <TabsContent value="all" 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="expense">지출결의서</SelectItem>
                    <SelectItem value="proposal">품의서</SelectItem>
                    <SelectItem value="leave">휴가신청서</SelectItem>
                    <SelectItem value="purchase">구매요청서</SelectItem>
                  </SelectContent>
                </Select>
                <Select>
                  <SelectTrigger className="w-full md:w-48">
                    <SelectValue placeholder="상태" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">전체</SelectItem>
                    <SelectItem value="pending">승인대기</SelectItem>
                    <SelectItem value="progress">진행중</SelectItem>
                    <SelectItem value="approved">승인완료</SelectItem>
                    <SelectItem value="rejected">반려</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 className="text-right">금액</TableHead>
                    <TableHead>현재 결재자</TableHead>
                    <TableHead>긴급도</TableHead>
                    <TableHead>상태</TableHead>
                    <TableHead className="text-center">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {documents.map((doc) => (
                    <TableRow key={doc.id} className="hover:bg-muted/50">
                      <TableCell className="font-mono text-sm">{doc.id}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{doc.type}</Badge>
                      </TableCell>
                      <TableCell className="font-medium">{doc.title}</TableCell>
                      <TableCell>{doc.drafter}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">{doc.department}</TableCell>
                      <TableCell className="text-sm">{doc.draftDate}</TableCell>
                      <TableCell className="text-right font-bold">
                        {doc.amount > 0 ? `${doc.amount.toLocaleString()}원` : '-'}
                      </TableCell>
                      <TableCell className="text-sm">{doc.currentApprover}</TableCell>
                      <TableCell>{getUrgencyBadge(doc.urgency)}</TableCell>
                      <TableCell>{getStatusBadge(doc.status)}</TableCell>
                      <TableCell>
                        <div className="flex items-center justify-center space-x-2">
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => {
                              setSelectedDocument(doc);
                              setIsViewDocumentOpen(true);
                            }}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => {
                              setSelectedDocument(doc);
                              handlePrint();
                            }}
                          >
                            <Printer className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="pending">
          <Card className="border border-border/20">
            <CardHeader>
              <CardTitle>승인 대기 문서</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground text-center py-8">
                승인 대기 중인 문서가 {documents.filter(d => d.status === "승인대기").length}건 있습니다.
              </p>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="approved">
          <Card className="border border-border/20">
            <CardHeader>
              <CardTitle>승인 완료 문서</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground text-center py-8">
                승인 완료된 문서가 {documents.filter(d => d.status === "승인완료").length}건 있습니다.
              </p>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="rejected">
          <Card className="border border-border/20">
            <CardHeader>
              <CardTitle>반려 문서</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground text-center py-8">
                반려된 문서가 {documents.filter(d => d.status === "반려").length}건 있습니다.
              </p>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 문서 상세보기 및 결재 Dialog */}
      <Dialog open={isViewDocumentOpen} onOpenChange={setIsViewDocumentOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-2xl md:max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-2xl flex items-center justify-between">
              {selectedDocument ? (
                <>
                  <div className="flex items-center space-x-3">
                    <FileText className="h-6 w-6 text-primary" />
                    <span>{selectedDocument.type}</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    {getStatusBadge(selectedDocument.status)}
                    {getUrgencyBadge(selectedDocument.urgency)}
                  </div>
                </>
              ) : (
                "문서 상세보기"
              )}
            </DialogTitle>
            <DialogDescription>
              {selectedDocument ? `문서번호: ${selectedDocument.id} | 기안일: ${selectedDocument.draftDate}` : "결재 문서 상세보기 및 결재 진행"}
            </DialogDescription>
          </DialogHeader>
          {selectedDocument && (
            <>

              <div className="space-y-6" id="printable-document">
                {/* 기본 정보 */}
                <div className="bg-muted/50 p-6 rounded-lg">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div>
                      <p className="text-sm text-muted-foreground">기안자</p>
                      <p className="font-bold">{selectedDocument.drafter}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">부서</p>
                      <p className="font-bold">{selectedDocument.department}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">직급</p>
                      <p className="font-bold">{selectedDocument.drafterPosition}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">기안일</p>
                      <p className="font-bold">{selectedDocument.draftDate}</p>
                    </div>
                  </div>
                  <div className="mt-4 pt-4 border-t">
                    <p className="text-sm text-muted-foreground">제목</p>
                    <p className="font-bold text-lg">{selectedDocument.title}</p>
                  </div>
                </div>

                {/* 지출결의서 상세 */}
                {selectedDocument.type === "지출결의서" && selectedDocument.details && (
                  <div className="bg-muted/50 p-6 rounded-lg space-y-4">
                    <h3 className="font-bold text-lg border-b pb-2">지출 내역</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm text-muted-foreground">지출 항목</p>
                        <p className="font-medium">{selectedDocument.details.expenseType}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">지출 일자</p>
                        <p className="font-medium">{selectedDocument.details.expenseDate}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">거래처</p>
                        <p className="font-medium">{selectedDocument.details.expenseVendor}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">계정과목</p>
                        <p className="font-medium">{selectedDocument.details.expenseAccount}</p>
                      </div>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">지출 사유</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.expenseReason}</p>
                    </div>
                    <div className="bg-primary/10 p-4 rounded-lg">
                      <div className="flex justify-between items-center">
                        <span className="font-medium">지출 금액</span>
                        <span className="text-2xl font-bold text-primary">{selectedDocument.amount.toLocaleString()}원</span>
                      </div>
                    </div>
                  </div>
                )}

                {/* 품의서 상세 */}
                {selectedDocument.type === "품의서" && selectedDocument.details && (
                  <div className="bg-muted/50 p-6 rounded-lg space-y-4">
                    <h3 className="font-bold text-lg border-b pb-2">품의 내용</h3>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">품의 주제</p>
                      <p className="font-medium text-lg">{selectedDocument.details.proposalSubject}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">추진 배경</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.proposalBackground}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">품의 내용</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.proposalContent}</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">기대 효과</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.proposalExpectedEffect}</p>
                    </div>
                    <div className="bg-primary/10 p-4 rounded-lg">
                      <div className="flex justify-between items-center">
                        <span className="font-medium">소요 예산</span>
                        <span className="text-2xl font-bold text-primary">{selectedDocument.amount.toLocaleString()}원</span>
                      </div>
                    </div>
                  </div>
                )}

                {/* 휴가신청서 상세 */}
                {selectedDocument.type === "휴가신청서" && selectedDocument.details && (
                  <div className="bg-muted/50 p-6 rounded-lg space-y-4">
                    <h3 className="font-bold text-lg border-b pb-2">휴가 정보</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm text-muted-foreground">휴가 종류</p>
                        <p className="font-medium">{selectedDocument.details.leaveType}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">사용 일수</p>
                        <p className="font-medium">{selectedDocument.details.leaveDays}일</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">시작일</p>
                        <p className="font-medium">{selectedDocument.details.leaveStartDate}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">종료일</p>
                        <p className="font-medium">{selectedDocument.details.leaveEndDate}</p>
                      </div>
                      <div className="col-span-2">
                        <p className="text-sm text-muted-foreground">긴급 연락처</p>
                        <p className="font-medium">{selectedDocument.details.leaveEmergencyContact}</p>
                      </div>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">휴가 사유</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.leaveReason}</p>
                    </div>
                  </div>
                )}

                {/* 구매요청서 상세 */}
                {selectedDocument.type === "구매요청서" && selectedDocument.details && (
                  <div className="bg-muted/50 p-6 rounded-lg space-y-4">
                    <h3 className="font-bold text-lg border-b pb-2">구매 정보</h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <p className="text-sm text-muted-foreground">구매 품목</p>
                        <p className="font-medium">{selectedDocument.details.purchaseItem}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">수량</p>
                        <p className="font-medium">{selectedDocument.details.purchaseQuantity}</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">단가</p>
                        <p className="font-medium">{selectedDocument.details.purchaseUnitPrice.toLocaleString()}원</p>
                      </div>
                      <div>
                        <p className="text-sm text-muted-foreground">공급업체</p>
                        <p className="font-medium">{selectedDocument.details.purchaseVendor}</p>
                      </div>
                      <div className="col-span-2">
                        <p className="text-sm text-muted-foreground">희망 납기일</p>
                        <p className="font-medium">{selectedDocument.details.purchaseDeliveryDate}</p>
                      </div>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">구매 목적</p>
                      <p className="p-3 bg-card rounded border">{selectedDocument.details.purchasePurpose}</p>
                    </div>
                    <div className="bg-primary/10 p-4 rounded-lg">
                      <div className="flex justify-between items-center">
                        <span className="font-medium">총 구매 금액</span>
                        <span className="text-2xl font-bold text-primary">{selectedDocument.amount.toLocaleString()}원</span>
                      </div>
                    </div>
                  </div>
                )}

                {/* 결재선 */}
                <div className="bg-muted/50 p-6 rounded-lg">
                  <h3 className="font-bold text-lg mb-4 border-b pb-2">결재선</h3>
                  <div className="flex items-center justify-between flex-wrap gap-4">
                    {selectedDocument.approvalLine.map((approver: any, index: number) => (
                      <div key={index} className="flex items-center">
                        <div className="text-center">
                          <div className={`w-20 h-20 rounded-full flex flex-col items-center justify-center mb-2 ${
                            approver.status === "승인" ? "bg-green-100 border-2 border-green-500" :
                            approver.status === "반려" ? "bg-red-100 border-2 border-red-500" :
                            "bg-gray-100 border-2 border-gray-300"
                          }`}>
                            {approver.status === "승인" ? (
                              <CheckCircle className="h-8 w-8 text-green-600" />
                            ) : approver.status === "반려" ? (
                              <XCircle className="h-8 w-8 text-red-600" />
                            ) : (
                              <Clock className="h-8 w-8 text-gray-400" />
                            )}
                          </div>
                          <p className="font-bold">{approver.name}</p>
                          <p className="text-sm text-muted-foreground">{approver.position}</p>
                          <Badge className={`mt-2 ${
                            approver.status === "승인" ? "bg-green-500" :
                            approver.status === "반려" ? "bg-red-500" :
                            "bg-yellow-500"
                          } text-white`}>
                            {approver.status}
                          </Badge>
                          {approver.date && (
                            <p className="text-xs text-muted-foreground mt-1">{approver.date}</p>
                          )}
                          {approver.comment && (
                            <p className="text-xs mt-1 p-2 bg-card rounded max-w-[120px]">{approver.comment}</p>
                          )}
                        </div>
                        {index < selectedDocument.approvalLine.length - 1 && (
                          <ArrowRight className="h-6 w-6 text-muted-foreground mx-4" />
                        )}
                      </div>
                    ))}
                  </div>
                </div>

                {/* 결재 의견 입력 (승인대기/진행중 상태일 때만) */}
                {(selectedDocument.status === "승인대기" || selectedDocument.status === "진행중") && (
                  <div className="bg-blue-50 dark:bg-blue-950/20 p-6 rounded-lg border border-blue-200 dark:border-blue-800">
                    <h3 className="font-bold text-lg mb-4">결재 의견</h3>
                    <Textarea
                      placeholder="결재 의견을 입력하세요"
                      value={approvalComment}
                      onChange={(e) => setApprovalComment(e.target.value)}
                      rows={3}
                      className="mb-4"
                    />
                    <div className="flex space-x-3">
                      <Button
                        className="flex-1 bg-green-600 hover:bg-green-700 text-white"
                        onClick={() => handleApprove(selectedDocument.id)}
                      >
                        <CheckCircle className="h-4 w-4 mr-2" />
                        승인
                      </Button>
                      <Button
                        className="flex-1 bg-red-600 hover:bg-red-700 text-white"
                        onClick={() => handleReject(selectedDocument.id)}
                      >
                        <XCircle className="h-4 w-4 mr-2" />
                        반려
                      </Button>
                    </div>
                  </div>
                )}
              </div>

              <DialogFooter className="flex justify-between items-center">
                <Button variant="outline" onClick={() => setIsViewDocumentOpen(false)}>
                  닫기
                </Button>
                <Button onClick={handlePrint}>
                  <Printer className="h-4 w-4 mr-2" />
                  인쇄
                </Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* 인쇄용 스타일 */}
      <style>
        {`
          @media print {
            body * {
              visibility: hidden;
            }
            #printable-document, #printable-document * {
              visibility: visible;
            }
            #printable-document {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              padding: 20px;
            }
            @page {
              size: A4;
              margin: 20mm;
            }
          }
        `}
      </style>
    </div>
  );
}
