"use client"

import * as React from "react"
import { 
  Eye, 
  Building2, 
  User, 
  Calendar, 
  CheckCircle2, 
  Clock, 
  MessageSquare,
  Award,
  FileText,
  Paperclip,
  Download,
  File,
  BarChart3
} from "lucide-react"

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"
import { PeriodicEvaluationView } from "@/db/schema"
import { getEvaluationDetails} from "../service"
import { AttachmentDetail, EvaluationDetailResponse } from "@/types/evaluation-form"
// 파일 다운로드 유틸리티 import
import { downloadFile, formatFileSize, getFileInfo } from "@/lib/file-download"

interface EvaluationDetailsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  evaluation: PeriodicEvaluationView | null
}

// 카테고리별 색상 매핑
const getCategoryBadgeVariant = (category: string) => {
  switch (category) {
    case "quality":
      return "default"
    case "delivery": 
      return "secondary"
    case "price":
      return "outline"
    case "cooperation":
      return "destructive"
    default:
      return "outline"
  }
}

// 카테고리명 매핑
const CATEGORY_LABELS = {
  "customer-service": "CS",
  administrator: "관리자", 
  procurement: "구매",
  design: "설계",
  sourcing: "조달",
  quality: "품질"
} as const

const CATEGORY_LABELS2 = {
    bonus: "가점항목",
    delivery: "납기", 
    management: "경영현황",
    penalty: "감점항목",
    procurement: "구매",
    quality: "품질"
  } as const

export function EvaluationDetailsDialog({
  open,
  onOpenChange,
  evaluation,
}: EvaluationDetailsDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [evaluationDetails, setEvaluationDetails] = React.useState<EvaluationDetailResponse | null>(null)

  // 첨부파일 다운로드 핸들러 - downloadFile 사용
  const handleDownloadAttachment = async (attachment: AttachmentDetail) => {
    try {
      await downloadFile(
        attachment.publicPath, 
        attachment.originalFileName,
        {
          action: 'download',
          showToast: true,
          showSuccessToast: true,
          onError: (error) => {
            console.error("파일 다운로드 실패:", error)
          },
          onSuccess: (fileName, fileSize) => {
            console.log("파일 다운로드 성공:", fileName, fileSize ? formatFileSize(fileSize) : '')
          }
        }
      )
    } catch (error) {
      console.error("다운로드 처리 중 오류:", error)
    }
  }

  // 평가 상세 정보 로드
  React.useEffect(() => {
    if (open && evaluation?.id) {
      const loadEvaluationDetails = async () => {
        try {
          setIsLoading(true)
          const details = await getEvaluationDetails(evaluation.id)
          setEvaluationDetails(details)
        } catch (error) {
          console.error("Failed to load evaluation details:", error)
        } finally {
          setIsLoading(false)
        }
      }

      loadEvaluationDetails()
    }
  }, [open, evaluation?.id])

  // 다이얼로그 닫을 때 데이터 리셋
  React.useEffect(() => {
    if (!open) {
      setEvaluationDetails(null)
    }
  }, [open])

  if (!evaluation) return null

  return (
    <TooltipProvider>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-7xl h-[90vh] flex flex-col">
          {/* 고정 헤더 */}
          <DialogHeader className="space-y-4 flex-shrink-0">
            <DialogTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5 text-blue-600" />
              평가 상세
            </DialogTitle>
            
            {/* 평가 기본 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Building2 className="h-5 w-5" />
                  평가 정보
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap items-center gap-6 text-sm mb-4">
                  {/* 협력업체 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">협력업체:</span>
                    <span className="font-medium">{evaluation.vendorName}</span>
                    <span className="text-muted-foreground">({evaluation.vendorCode})</span>
                  </div>

                  {/* 평가년도 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">년도:</span>
                    <span className="font-medium">{evaluation.evaluationYear}년</span>
                  </div>

                  {/* 구분 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">구분:</span>
                    <Badge variant="outline" className="text-xs">
                      {evaluation.division === "PLANT" ? "해양" : "조선"}
                    </Badge>
                  </div>

                  {/* 진행상태 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">상태:</span>
                    <Badge variant="secondary" className="text-xs">{evaluation.status}</Badge>
                  </div>

                  {/* 평가점수/등급 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">평가점수/등급:</span>
                    {evaluation.evaluationScore ? (
                      <div className="flex items-center gap-1">
                        <span className="font-bold text-blue-600">
                          {Number(evaluation.evaluationScore).toFixed(1)}점
                        </span>
                        {evaluation.evaluationGrade && (
                          <Badge variant="default" className="text-xs h-5">
                            {evaluation.evaluationGrade}
                          </Badge>
                        )}
                      </div>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </div>

                  {/* 확정점수/등급 */}
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">확정점수/등급:</span>
                    {evaluation.finalScore ? (
                      <div className="flex items-center gap-1">
                        <span className="font-bold text-green-600">
                          {Number(evaluation.finalScore).toFixed(1)}점
                        </span>
                        {evaluation.finalGrade && (
                          <Badge variant="default" className="bg-green-600 text-xs h-5">
                            {evaluation.finalGrade}
                          </Badge>
                        )}
                      </div>
                    ) : (
                      <span className="text-muted-foreground">미확정</span>
                    )}
                  </div>
                </div>

                {/* 🔄 조선/해양 취합 정보 (동시 평가인 경우) */}
                {evaluationDetails?.consolidatedInfo && (
                  <div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-md">
                    <div className="flex items-center gap-2 mb-3">
                      <BarChart3 className="h-5 w-5 text-blue-600" />
                      <span className="font-semibold text-blue-900">조선/해양 취합 결과</span>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                      {/* 조선 점수 */}
                      <div className="space-y-1">
                        <div className="text-muted-foreground">조선 확정점수/등급</div>
                        <div className="flex items-center gap-1">
                          {evaluationDetails.consolidatedInfo.shipbuildingScore !== null ? (
                            <>
                              <span className="font-bold text-blue-700">
                                {evaluationDetails.consolidatedInfo.shipbuildingScore.toFixed(1)}점
                              </span>
                              {evaluationDetails.consolidatedInfo.shipbuildingGrade && (
                                <Badge variant="outline" className="text-xs h-5">
                                  {evaluationDetails.consolidatedInfo.shipbuildingGrade}
                                </Badge>
                              )}
                            </>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </div>
                      </div>

                      {/* 해양 점수 */}
                      <div className="space-y-1">
                        <div className="text-muted-foreground">해양 확정점수/등급</div>
                        <div className="flex items-center gap-1">
                          {evaluationDetails.consolidatedInfo.offshoreScore !== null ? (
                            <>
                              <span className="font-bold text-blue-700">
                                {evaluationDetails.consolidatedInfo.offshoreScore.toFixed(1)}점
                              </span>
                              {evaluationDetails.consolidatedInfo.offshoreGrade && (
                                <Badge variant="outline" className="text-xs h-5">
                                  {evaluationDetails.consolidatedInfo.offshoreGrade}
                                </Badge>
                              )}
                            </>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </div>
                      </div>

                      {/* 취합 점수 (50% 반영) */}
                      <div className="space-y-1">
                        <div className="text-muted-foreground">취합 점수/등급 (50% 반영)</div>
                        <div className="flex items-center gap-1">
                          {evaluationDetails.consolidatedInfo.consolidatedScore !== null ? (
                            <>
                              <span className="font-bold text-purple-700 text-base">
                                {evaluationDetails.consolidatedInfo.consolidatedScore.toFixed(1)}점
                              </span>
                              {evaluationDetails.consolidatedInfo.consolidatedGrade && (
                                <Badge variant="default" className="bg-purple-600 text-xs h-5">
                                  {evaluationDetails.consolidatedInfo.consolidatedGrade}
                                </Badge>
                              )}
                            </>
                          ) : (
                            <span className="text-muted-foreground">-</span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                </CardContent>
            </Card>
          </DialogHeader>

          {/* 스크롤 가능한 컨텐츠 영역 */}
          <div className="flex-1 overflow-y-auto min-h-0">
            {isLoading ? (
              <div className="space-y-4 p-1">
                <Card>
                  <CardHeader>
                    <Skeleton className="h-6 w-48" />
                  </CardHeader>
                  <CardContent>
                    <Skeleton className="h-64 w-full" />
                  </CardContent>
                </Card>
              </div>
            ) : evaluationDetails ? (
              <div className="space-y-6 p-1">
                {/* 통합 평가 테이블 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <FileText className="h-5 w-5" />
                      평가 상세 내역
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {evaluationDetails.reviewerDetails.some(r => r.evaluationItems.length > 0) ? (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[120px]">담당자</TableHead>
                            <TableHead className="w-[100px]">평가부문</TableHead>
                            <TableHead className="w-[100px]">항목</TableHead>
                            <TableHead className="w-[150px]">구분</TableHead>
                            <TableHead className="w-[200px]">범위</TableHead>
                            <TableHead className="w-[200px]">선택옵션</TableHead>
                            <TableHead className="w-[80px]">점수</TableHead>
                            <TableHead className="w-[150px]">첨부파일</TableHead>
                            <TableHead className="min-w-[200px]">의견</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {evaluationDetails.reviewerDetails.map((reviewer) =>
                            reviewer.evaluationItems.map((item, index) => (
                              <TableRow key={`${reviewer.reviewerEvaluationId}-${item.criteriaId}-${index}`}>
                                <TableCell>
                                  <div className="space-y-1">
                                    <div className="font-medium text-sm">{reviewer.departmentName}</div>
                                    <div className="text-xs text-muted-foreground">
                                      {reviewer.reviewerName}
                                    </div>
                                  </div>
                                </TableCell>
                                <TableCell>
                                  <Badge variant={getCategoryBadgeVariant(item.category)}>
                                    {CATEGORY_LABELS[item.category as keyof typeof CATEGORY_LABELS] || item.category}
                                  </Badge>
                                </TableCell>
                                <TableCell>
                                  {CATEGORY_LABELS2[item.item as keyof typeof CATEGORY_LABELS2] || item.item}
                                </TableCell>
                                <TableCell className="font-medium">
                                  {item.classification}
                                </TableCell>
                                <TableCell className="text-sm">
                                  {item.range || "-"}
                                </TableCell>
                                <TableCell className="text-sm">
                                  {item.scoreType === "variable" ? (
                                    <Badge variant="outline">직접 입력</Badge>
                                  ) : (
                                    item.selectedDetail || "-"
                                  )}
                                </TableCell>
                                <TableCell>
                                  {item.score !== null ? (
                                    <Badge variant="default" className="font-mono">
                                      {item.score.toFixed(1)}
                                    </Badge>
                                  ) : (
                                    <span className="text-muted-foreground">-</span>
                                  )}
                                </TableCell>

                                {/* 📎 첨부파일 컬럼 - 개선된 버전 */}
                                <TableCell>
                                  {item.attachments.length > 0 ? (
                                    <div className="space-y-1">
                                      {item.attachments.map((attachment) => {
                                        const fileInfo = getFileInfo(attachment.originalFileName)
                                        return (
                                          <div key={attachment.id} className="flex items-center gap-1 p-1 bg-muted rounded">
                                            <span className="text-sm">{fileInfo.icon}</span>
                                            <Tooltip>
                                              <TooltipTrigger asChild>
                                                <span className="text-xs truncate max-w-[80px] cursor-help">
                                                  {attachment.originalFileName}
                                                </span>
                                              </TooltipTrigger>
                                              <TooltipContent>
                                                <div className="text-xs space-y-1">
                                                  <div className="font-medium">{attachment.originalFileName}</div>
                                                  <div>크기: {formatFileSize(attachment.fileSize)}</div>
                                                  <div>타입: {fileInfo.type}</div>
                                                  {attachment.description && (
                                                    <div>설명: {attachment.description}</div>
                                                  )}
                                                  <div>업로드: {attachment.uploadedByName}</div>
                                                  <div className="text-muted-foreground">
                                                    {fileInfo.canPreview ? "미리보기 가능" : "다운로드만 가능"}
                                                  </div>
                                                </div>
                                              </TooltipContent>
                                            </Tooltip>
                                            <Button
                                              variant="ghost"
                                              size="sm"
                                              className="h-4 w-4 p-0"
                                              onClick={() => handleDownloadAttachment(attachment)}
                                            >
                                              <Download className="h-3 w-3" />
                                            </Button>
                                          </div>
                                        )
                                      })}
                                      {item.attachments.length > 1 && (
                                        <div className="text-xs text-muted-foreground">
                                          총 {formatFileSize(item.attachmentTotalSize)}
                                        </div>
                                      )}
                                    </div>
                                  ) : (
                                    <div className="text-xs text-muted-foreground">
                                      첨부파일 없음
                                    </div>
                                  )}
                                </TableCell>

                                <TableCell className="text-sm">
                                  {item.comment || (
                                    <span className="text-muted-foreground">의견 없음</span>
                                  )}
                                </TableCell>
                              </TableRow>
                            ))
                          )}
                        </TableBody>
                      </Table>
                    ) : (
                      <div className="text-center text-muted-foreground py-8">
                        <FileText className="h-8 w-8 mx-auto mb-2" />
                        <div>평가 항목이 없습니다</div>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* 리뷰어별 종합 의견 (있는 경우만) */}
                {evaluationDetails.reviewerDetails.some(r => r.reviewerComment) && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <MessageSquare className="h-5 w-5" />
                        종합 의견
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      {evaluationDetails.reviewerDetails
                        .filter(reviewer => reviewer.reviewerComment)
                        .map((reviewer) => (
                          <div key={reviewer.reviewerEvaluationId} className="space-y-2">
                            <div className="flex items-center gap-2">
                              <Badge variant="outline">{reviewer.departmentName}</Badge>
                              <span className="text-sm font-medium">{reviewer.reviewerName}</span>
                              {reviewer.totalAttachments > 0 && (
                                <Badge variant="secondary" className="text-xs">
                                  <Paperclip className="h-3 w-3 mr-1" />
                                  {reviewer.totalAttachments}개 파일
                                </Badge>
                              )}
                            </div>
                            <div className="bg-muted p-3 rounded-md text-sm">
                              {reviewer.reviewerComment}
                            </div>
                          </div>
                        ))}
                    </CardContent>
                  </Card>
                )}

                {/* 📎 첨부파일 요약 (파일이 많은 경우) */}
                {evaluationDetails.attachmentStats.totalFiles > 5 && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <BarChart3 className="h-5 w-5" />
                        첨부파일 요약
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                        <div className="space-y-1">
                          <div className="text-muted-foreground">전체 파일 수</div>
                          <div className="font-bold text-lg">{evaluationDetails.attachmentStats.totalFiles}개</div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-muted-foreground">전체 파일 크기</div>
                          <div className="font-bold text-lg">{formatFileSize(evaluationDetails.attachmentStats.totalSize)}</div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-muted-foreground">첨부 질문 수</div>
                          <div className="font-bold text-lg">{evaluationDetails.attachmentStats.questionsWithAttachments}개</div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-muted-foreground">첨부 담당자 수</div>
                          <div className="font-bold text-lg">{evaluationDetails.attachmentStats.reviewersWithAttachments}명</div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {evaluationDetails.reviewerDetails.length === 0 && (
                  <Card>
                    <CardContent className="py-8">
                      <div className="text-center text-muted-foreground">
                        <User className="h-8 w-8 mx-auto mb-2" />
                        <div>배정된 리뷰어가 없습니다</div>
                      </div>
                    </CardContent>
                  </Card>
                )}
              </div>
            ) : (
              <Card className="m-1">
                <CardContent className="py-8">
                  <div className="text-center text-muted-foreground">
                    평가 상세 정보를 불러올 수 없습니다
                  </div>
                </CardContent>
              </Card>
            )}
          </div>

          {/* 고정 푸터 */}
          <div className="flex justify-end pt-4 border-t flex-shrink-0">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              닫기
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </TooltipProvider>
  )
}