"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Plus, RefreshCw, Upload, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "@/i18n/client";
import {
  UnifiedDwgReceiptItem,
  DetailDwgReceiptItem,
  FileInfoItem,
  fetchDetailDwgReceiptList,
  fetchFileInfoList,
} from "../actions";
import { DrawingListTable } from "../table/drawing-list-table";
import { createDetailDrawingColumns } from "../table/detail-drawing-columns";
import { createFileListColumns } from "../table/file-list-columns";
import { AddAndModifyDetailDrawingDialog } from "./add-and-modify-detail-drawing-dialog";
import { UploadFilesToDetailDialog } from "./upload-files-to-detail-dialog";

interface DetailDrawingDialogProps {
  drawing: UnifiedDwgReceiptItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vendorCode: string;
  userId: string;
  userName: string;
  userEmail: string;
  drawingKind: "B3" | "B4";
  lng: string;
}

export function DetailDrawingDialog({
  drawing,
  open,
  onOpenChange,
  vendorCode,
  userId,
  userName,
  userEmail,
  drawingKind,
  lng,
}: DetailDrawingDialogProps) {
  const { t } = useTranslation(lng, "dolce");
  const [detailDrawings, setDetailDrawings] = useState<DetailDwgReceiptItem[]>([]);
  const [selectedDetail, setSelectedDetail] = useState<DetailDwgReceiptItem | null>(null);
  const [files, setFiles] = useState<FileInfoItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingFiles, setIsLoadingFiles] = useState(false);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingDetailDrawing, setEditingDetailDrawing] = useState<DetailDwgReceiptItem | null>(null);
  const [uploadFilesDialogOpen, setUploadFilesDialogOpen] = useState(false);
  const [downloadingFileId, setDownloadingFileId] = useState<string | null>(null);

  // 상세도면 목록 로드
  const loadDetailDrawings = useCallback(async () => {
    if (!drawing) return;

    try {
      setIsLoading(true);
      const data = await fetchDetailDwgReceiptList({
        project: drawing.ProjectNo,
        drawingNo: drawing.DrawingNo,
        discipline: drawing.Discipline,
        drawingKind: drawing.DrawingKind,
        userId: "", // 조회 시 모든 사용자의 상세도면을 보기 위해 빈 문자열 전달
      });
      setDetailDrawings(data);
      
      // 첫 번째 상세도면 자동 선택
      if (data.length > 0 && !selectedDetail) {
        setSelectedDetail(data[0]);
      }
    } catch (error) {
      console.error("상세도면 로드 실패:", error);
      toast.error(t("detailDialog.detailLoadError"));
    } finally {
      setIsLoading(false);
    }
  }, [drawing, selectedDetail, t]);

  // 파일 목록 로드
  const loadFiles = useCallback(async () => {
    if (!selectedDetail) {
      setFiles([]);
      return;
    }

    try {
      setIsLoadingFiles(true);
      const data = await fetchFileInfoList(selectedDetail.UploadId);
      setFiles(data);
    } catch (error) {
      console.error("파일 목록 로드 실패:", error);
      toast.error(t("detailDialog.fileLoadError"));
    } finally {
      setIsLoadingFiles(false);
    }
  }, [selectedDetail, t]);

  // 다이얼로그 열릴 때 데이터 로드
  useEffect(() => {
    if (open && drawing) {
      loadDetailDrawings();
    } else {
      setDetailDrawings([]);
      setSelectedDetail(null);
      setFiles([]);
    }
  }, [open, drawing, loadDetailDrawings]);

  // 선택된 상세도면 변경 시 파일 목록 로드
  useEffect(() => {
    if (selectedDetail) {
      loadFiles();
    }
  }, [selectedDetail, loadFiles]);

  const handleDownload = async (file: FileInfoItem) => {
    try {
      setDownloadingFileId(file.FileId);
      toast.info(t("detailDialog.downloadPreparing"));
      
      // 파일 생성자의 userId를 사용하여 다운로드
      const response = await fetch("/api/dolce/download", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          fileId: file.FileId,
          userId: file.CreateUserId, // 파일 생성자의 ID 사용
          fileName: file.FileName,
        }),
      });

      if (!response.ok) {
        throw new Error(t("detailDialog.downloadError"));
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = file.FileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      toast.success(t("detailDialog.downloadSuccess"));
    } catch (error) {
      console.error("파일 다운로드 실패:", error);
      toast.error(t("detailDialog.downloadError"));
    } finally {
      setDownloadingFileId(null);
    }
  };

  const handleRefresh = () => {
    loadDetailDrawings();
  };

  const handleAddComplete = () => {
    setAddDialogOpen(false);
    loadDetailDrawings();
  };

  const handleEditClick = (detailDrawing: DetailDwgReceiptItem) => {
    setEditingDetailDrawing(detailDrawing);
    setEditDialogOpen(true);
  };

  const handleEditComplete = () => {
    setEditDialogOpen(false);
    setEditingDetailDrawing(null);
    loadDetailDrawings();
  };

  const handleUploadComplete = () => {
    setUploadFilesDialogOpen(false);
    loadFiles();
  };

  const fileColumns = createFileListColumns({ onDownload: handleDownload, lng, downloadingFileId });

  // RegisterId + UploadId 조합으로 고유 ID 생성
  const getDetailDrawingId = (detail: DetailDwgReceiptItem) => {
    return `${detail.RegisterId}_${detail.UploadId}`;
  };

  // B4인 경우 "도면입수"인 건만 상세도면 추가 및 파일 첨부 가능
  // B3인 경우 모든 건에 대해 가능
  const canAddDetailDrawing = drawingKind === "B3" || 
    (drawingKind === "B4" && drawing && 'DrawingMoveGbn' in drawing && drawing.DrawingMoveGbn === "도면입수");

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-[95vw] h-[90vh] flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex flex-col gap-1">
              <span>{t("detailDialog.title")}</span>
              {drawing && (
                <span className="text-sm font-normal text-muted-foreground">
                  {t("detailDialog.subtitle", {
                    drawingNo: drawing.DrawingNo,
                    projectNo: drawing.ProjectNo,
                    discipline: drawing.Discipline,
                    drawingKind: drawing.DrawingKind
                  })}
                </span>
              )}
            </DialogTitle>
          </DialogHeader>

          <div className="flex-1 overflow-hidden flex flex-col gap-4">
            {/* 상단: 상세도면 리스트 */}
            <Card className="flex-1 overflow-hidden flex flex-col">
              <CardHeader className="flex-row items-center justify-between py-3">
                <CardTitle className="text-base">{t("detailDialog.detailListTitle")}</CardTitle>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRefresh}
                    disabled={isLoading}
                  >
                    <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
                    {t("detailDialog.refreshButton")}
                  </Button>
                  {canAddDetailDrawing && (
                    <Button
                      variant="default"
                      size="sm"
                      onClick={() => setAddDialogOpen(true)}
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      {t("detailDialog.addDetailButton")}
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="flex-1 overflow-y-auto p-4">
                <DrawingListTable<DetailDwgReceiptItem, unknown>
                  columns={createDetailDrawingColumns(lng, t, handleEditClick)}
                  data={detailDrawings}
                  onRowClick={setSelectedDetail}
                  selectedRow={selectedDetail || undefined}
                  getRowId={(row) => getDetailDrawingId(row)}
                />
              </CardContent>
            </Card>

            {/* 하단: 첨부파일 리스트 */}
            <Card className="flex-1 overflow-hidden flex flex-col">
              <CardHeader className="flex-row items-center justify-between py-3">
                <CardTitle className="text-base">
                  {t("detailDialog.fileListTitle")}
                  {selectedDetail && t("detailDialog.fileListSubtitle", { revNo: selectedDetail.DrawingRevNo })}
                </CardTitle>
                {selectedDetail && canAddDetailDrawing && (
                  <Button
                    variant="default"
                    size="sm"
                    onClick={() => setUploadFilesDialogOpen(true)}
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    {t("detailDialog.uploadFilesButton")}
                  </Button>
                )}
              </CardHeader>
              <CardContent className="flex-1 overflow-y-auto p-4">
                {!selectedDetail ? (
                  <div className="h-full flex items-center justify-center text-muted-foreground">
                    {t("detailDialog.selectDetailDrawing")}
                  </div>
                ) : isLoadingFiles ? (
                  <div className="space-y-4">
                    <div className="flex items-center justify-center gap-2 text-muted-foreground py-8">
                      <Loader2 className="h-5 w-5 animate-spin" />
                      <span>{t("detailDialog.loadingFiles")}</span>
                    </div>
                    <div className="space-y-2">
                      <Skeleton className="h-10 w-full" />
                      <Skeleton className="h-10 w-full" />
                      <Skeleton className="h-10 w-full" />
                    </div>
                  </div>
                ) : (
                  <DrawingListTable
                    columns={fileColumns}
                    data={files}
                  />
                )}
              </CardContent>
            </Card>
          </div>
        </DialogContent>
      </Dialog>

      <AddAndModifyDetailDrawingDialog
        open={addDialogOpen}
        onOpenChange={setAddDialogOpen}
        drawing={drawing}
        vendorCode={vendorCode}
        userId={userId}
        userName={userName}
        userEmail={userEmail}
        onComplete={handleAddComplete}
        drawingKind={drawingKind}
        lng={lng}
        mode="add"
      />

      <AddAndModifyDetailDrawingDialog
        open={editDialogOpen}
        onOpenChange={setEditDialogOpen}
        drawing={drawing}
        vendorCode={vendorCode}
        userId={userId}
        userName={userName}
        userEmail={userEmail}
        onComplete={handleEditComplete}
        drawingKind={drawingKind}
        lng={lng}
        mode="edit"
        detailDrawing={editingDetailDrawing}
      />

      {selectedDetail && (
        <UploadFilesToDetailDialog
          open={uploadFilesDialogOpen}
          onOpenChange={setUploadFilesDialogOpen}
          uploadId={selectedDetail.UploadId}
          drawingNo={selectedDetail.DrawingNo}
          revNo={selectedDetail.DrawingRevNo}
          userId={userId}
          onUploadComplete={handleUploadComplete}
          lng={lng}
        />
      )}
    </>
  );
}

