import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Textarea } from "./ui/textarea";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "./ui/dialog";
import { Alert, AlertDescription } from "./ui/alert";
import { toast } from "sonner@2.0.3";
import {
  CheckCircle2,
  XCircle,
  Clock,
  AlertCircle,
  FileCheck,
  User,
  Calendar,
  MessageSquare
} from "lucide-react";

interface ApprovalStatus {
  id: string;
  status: "pending" | "approved" | "rejected";
  approvedAt?: string;
  comment?: string;
}

interface ApprovalLine {
  id: string;
  position: string;
  name: string;
  userId?: string; // 실제 시스템에서는 사용자 ID
}

interface ApprovalProcessProps {
  documentId: string;
  documentTitle: string;
  submitter: {
    name: string;
    date: string;
  };
  approvalLines: ApprovalLine[];
  currentUserId?: string; // 현재 로그인한 사용자 ID
}

export function ApprovalProcess({ 
  documentId, 
  documentTitle, 
  submitter,
  approvalLines,
  currentUserId = "user1" // 데모용
}: ApprovalProcessProps) {
  
  // 각 결재자의 상태
  const [approvalStatuses, setApprovalStatuses] = useState<Record<string, ApprovalStatus>>(
    approvalLines.reduce((acc, line) => {
      acc[line.id] = {
        id: line.id,
        status: "pending"
      };
      return acc;
    }, {} as Record<string, ApprovalStatus>)
  );

  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [currentAction, setCurrentAction] = useState<"approve" | "reject">("approve");
  const [comment, setComment] = useState("");
  const [selectedApprovalId, setSelectedApprovalId] = useState<string>("");

  // 현재 결재 대기 중인 사람 찾기 (순서대로)
  const getCurrentApprover = () => {
    for (const line of approvalLines) {
      const status = approvalStatuses[line.id];
      if (status.status === "pending") {
        return line;
      }
      if (status.status === "rejected") {
        return null; // 반려되면 더 이상 진행 안 함
      }
    }
    return null; // 모두 승인 완료
  };

  const currentApprover = getCurrentApprover();
  const isMyTurn = currentApprover?.userId === currentUserId || currentApprover?.id === "1"; // 데모용

  // 전체 결재 상태
  const getOverallStatus = () => {
    const hasRejection = Object.values(approvalStatuses).some(s => s.status === "rejected");
    if (hasRejection) return "rejected";
    
    const allApproved = Object.values(approvalStatuses).every(s => s.status === "approved");
    if (allApproved) return "completed";
    
    return "in-progress";
  };

  const overallStatus = getOverallStatus();

  // 승인/반려 처리
  const handleApproval = (lineId: string, action: "approve" | "reject") => {
    setSelectedApprovalId(lineId);
    setCurrentAction(action);
    setShowApprovalDialog(true);
  };

  const confirmApproval = () => {
    const now = new Date().toISOString().split('T')[0];
    
    setApprovalStatuses({
      ...approvalStatuses,
      [selectedApprovalId]: {
        id: selectedApprovalId,
        status: currentAction === "approve" ? "approved" : "rejected",
        approvedAt: now,
        comment: comment || undefined
      }
    });

    // 알림 전송 시뮬레이션
    if (currentAction === "approve") {
      toast.success("승인 완료", {
        description: "다음 결재자에게 알림이 발송되었습니다."
      });
      
      // 다음 결재자 찾기
      const currentIndex = approvalLines.findIndex(l => l.id === selectedApprovalId);
      if (currentIndex < approvalLines.length - 1) {
        const nextApprover = approvalLines[currentIndex + 1];
        // 실제로는 여기서 이메일/푸시 알림 발송
        console.log(`알림 발송: ${nextApprover.name} (${nextApprover.position})`);
      } else {
        toast.success("결재 완료", {
          description: "모든 결재가 완료되었습니다."
        });
      }
    } else {
      toast.error("반려 완료", {
        description: "작성자에게 반려 알림이 발송되었습니다."
      });
    }

    setShowApprovalDialog(false);
    setComment("");
  };

  const getStatusIcon = (status: "pending" | "approved" | "rejected") => {
    switch (status) {
      case "approved":
        return <CheckCircle2 className="h-5 w-5 text-green-600" />;
      case "rejected":
        return <XCircle className="h-5 w-5 text-red-600" />;
      case "pending":
        return <Clock className="h-5 w-5 text-gray-400" />;
    }
  };

  const getStatusBadge = (status: "pending" | "approved" | "rejected") => {
    switch (status) {
      case "approved":
        return <Badge className="bg-green-600">승인</Badge>;
      case "rejected":
        return <Badge className="bg-red-600">반려</Badge>;
      case "pending":
        return <Badge variant="outline">대기</Badge>;
    }
  };

  return (
    <div className="space-y-4">
      {/* 문서 정보 */}
      <Card className="border-0 shadow-lg">
        <CardHeader>
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-3">
              <FileCheck className="h-6 w-6 text-blue-600 mt-1" />
              <div>
                <CardTitle>{documentTitle}</CardTitle>
                <p className="text-sm text-muted-foreground mt-1">
                  작성자: {submitter.name} | 작성일: {submitter.date}
                </p>
              </div>
            </div>
            <div>
              {overallStatus === "completed" && (
                <Badge className="bg-green-600 text-lg px-4 py-2">✓ 결재 완료</Badge>
              )}
              {overallStatus === "rejected" && (
                <Badge className="bg-red-600 text-lg px-4 py-2">✗ 반려됨</Badge>
              )}
              {overallStatus === "in-progress" && (
                <Badge variant="outline" className="text-lg px-4 py-2">
                  <Clock className="h-4 w-4 mr-2" />
                  결재 진행중
                </Badge>
              )}
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* 내 결재 대기 알림 */}
      {isMyTurn && overallStatus === "in-progress" && (
        <Alert className="border-blue-200 bg-blue-50">
          <AlertCircle className="h-4 w-4 text-blue-600" />
          <AlertDescription className="text-blue-900">
            <span className="font-semibold">결재 요청</span>이 도착했습니다. 
            아래에서 승인 또는 반려를 선택해주세요.
          </AlertDescription>
        </Alert>
      )}

      {/* 결재 라인 */}
      <Card className="border-0 shadow-lg">
        <CardHeader>
          <CardTitle>결재 진행 상황</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* 작성자 */}
            <div className="flex items-center gap-4 p-4 bg-blue-50 rounded-lg border-2 border-blue-200">
              <div className="w-12 h-12 bg-blue-600 rounded-full flex items-center justify-center">
                <User className="h-6 w-6 text-white" />
              </div>
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <Badge className="bg-blue-600">작성자</Badge>
                  <span className="font-medium">{submitter.name}</span>
                </div>
                <p className="text-sm text-muted-foreground mt-1">
                  <Calendar className="h-3 w-3 inline mr-1" />
                  {submitter.date}
                </p>
              </div>
              <CheckCircle2 className="h-6 w-6 text-blue-600" />
            </div>

            {/* 결재자들 */}
            {approvalLines.map((line, index) => {
              const status = approvalStatuses[line.id];
              const isCurrentApprover = currentApprover?.id === line.id;
              const isMyApproval = line.id === "1"; // 데모용, 실제로는 line.userId === currentUserId

              return (
                <div key={line.id}>
                  {/* 연결선 */}
                  <div className="flex justify-center">
                    <div className="w-0.5 h-6 bg-gray-300"></div>
                  </div>

                  {/* 결재자 카드 */}
                  <div 
                    className={`flex items-center gap-4 p-4 rounded-lg border-2 transition-all ${
                      isCurrentApprover 
                        ? 'bg-yellow-50 border-yellow-300 shadow-md' 
                        : status.status === 'approved'
                        ? 'bg-green-50 border-green-200'
                        : status.status === 'rejected'
                        ? 'bg-red-50 border-red-200'
                        : 'bg-gray-50 border-gray-200'
                    }`}
                  >
                    <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                      status.status === 'approved' ? 'bg-green-600' :
                      status.status === 'rejected' ? 'bg-red-600' :
                      isCurrentApprover ? 'bg-yellow-500' : 'bg-gray-400'
                    }`}>
                      <User className="h-6 w-6 text-white" />
                    </div>
                    
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <Badge variant="outline" className="text-xs">
                          {index + 1}단계
                        </Badge>
                        <span className="font-medium">{line.position}</span>
                        {line.name && (
                          <span className="text-sm text-muted-foreground">({line.name})</span>
                        )}
                      </div>
                      
                      {status.approvedAt && (
                        <p className="text-xs text-muted-foreground">
                          <Calendar className="h-3 w-3 inline mr-1" />
                          {status.approvedAt}
                        </p>
                      )}
                      
                      {status.comment && (
                        <div className="mt-2 p-2 bg-white rounded border text-sm">
                          <MessageSquare className="h-3 w-3 inline mr-1" />
                          {status.comment}
                        </div>
                      )}
                    </div>

                    <div className="flex flex-col items-end gap-2">
                      {getStatusBadge(status.status)}
                      
                      {isCurrentApprover && isMyApproval && overallStatus === "in-progress" && (
                        <div className="flex gap-2 mt-2">
                          <Button
                            size="sm"
                            onClick={() => handleApproval(line.id, "approve")}
                            className="bg-green-600 hover:bg-green-700"
                          >
                            <CheckCircle2 className="h-4 w-4 mr-1" />
                            승인
                          </Button>
                          <Button
                            size="sm"
                            variant="destructive"
                            onClick={() => handleApproval(line.id, "reject")}
                          >
                            <XCircle className="h-4 w-4 mr-1" />
                            반려
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* 승인/반려 다이얼로그 */}
      <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {currentAction === "approve" ? "승인 확인" : "반려 확인"}
            </DialogTitle>
            <DialogDescription>
              {currentAction === "approve" 
                ? "승인 의견을 입력하고 승인 버튼을 클릭하세요." 
                : "반려 사유를 입력하고 반려 버튼을 클릭하세요."}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4 px-6">
            <Alert className={currentAction === "approve" ? "border-green-200 bg-green-50" : "border-red-200 bg-red-50"}>
              <AlertCircle className={`h-4 w-4 ${currentAction === "approve" ? "text-green-600" : "text-red-600"}`} />
              <AlertDescription className={currentAction === "approve" ? "text-green-900" : "text-red-900"}>
                {currentAction === "approve" 
                  ? "이 문서를 승인하시겠습니까?" 
                  : "이 문서를 반려하시겠습니까?"}
              </AlertDescription>
            </Alert>
            
            <div>
              <Label className="text-sm font-medium mb-2">의견 (선택)</Label>
              <Textarea
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                placeholder={currentAction === "approve" ? "승인 의견을 입력하세요" : "반려 사유를 입력하세요"}
                className="rounded-lg min-h-[100px]"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowApprovalDialog(false)}>
              취소
            </Button>
            <Button
              onClick={confirmApproval}
              className={currentAction === "approve" ? "bg-green-600 hover:bg-green-700" : ""}
              variant={currentAction === "reject" ? "destructive" : "default"}
            >
              {currentAction === "approve" ? "승인" : "반려"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// Label 컴포넌트 추가
function Label({ children, className }: { children: React.ReactNode; className?: string }) {
  return <label className={className}>{children}</label>;
}
