"use client"

import * as React from "react"
import { useState, useEffect } from "react"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from "@/components/ui/tooltip"
import {
    CalendarIcon,
    ClockIcon,
    MapPinIcon,
    FileTextIcon,
    ExternalLinkIcon,
    FileXIcon,
    UploadIcon
} from "lucide-react"
import { BiddingListItem } from "@/db/schema"
import { downloadFile, formatFileSize, getFileInfo } from "@/lib/file-download"
import { getSpecificationMeetingDetailsAction } from "../service"
import { bidClosureAction } from "../actions"
import { formatDate } from "@/lib/utils"
import { toast } from "sonner"

// 타입 정의
interface SpecificationMeetingDetails {
    id: number;
    biddingId: number;
    meetingDate: string;
    meetingTime?: string | null;
    location?: string | null;
    address?: string | null;
    contactPerson?: string | null;
    contactPhone?: string | null;
    contactEmail?: string | null;
    agenda?: string | null;
    materials?: string | null;
    notes?: string | null;
    isRequired: boolean;
    createdAt: string;
    updatedAt: string;
    documents: Array<{
        id: number;
        fileName: string;
        originalFileName: string;
        fileSize: number;
        filePath: string;
        title?: string | null;
        uploadedAt: string;
        uploadedBy?: string | null;
    }>;
}

// PR 관련 타입과 컴포넌트는 bidding-pr-documents-dialog.tsx로 이동됨

// 파일 다운로드 훅
const useFileDownload = () => {
    const [downloadingFiles, setDownloadingFiles] = useState<Set<string>>(new Set());

    const handleDownload = async (filePath: string, fileName: string, options?: { 
        action?: 'download' | 'preview' 
    }) => {
        const fileKey = `${filePath}_${fileName}`;
        if (downloadingFiles.has(fileKey)) return;
        
        setDownloadingFiles(prev => new Set(prev).add(fileKey));
        
        try {
            await downloadFile(filePath, fileName, {
                action: options?.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);
        } finally {
            setDownloadingFiles(prev => {
                const newSet = new Set(prev);
                newSet.delete(fileKey);
                return newSet;
            });
        }
    };

    return { handleDownload, downloadingFiles };
};

// 파일 링크 컴포넌트
interface FileDownloadLinkProps {
    filePath: string;
    fileName: string;
    fileSize?: number;
    title?: string | null;
    className?: string;
}

const FileDownloadLink: React.FC<FileDownloadLinkProps> = ({
    filePath,
    fileName,
    fileSize,
    title,
    className = ""
}) => {
    const { handleDownload, downloadingFiles } = useFileDownload();
    const fileInfo = getFileInfo(fileName);
    const fileKey = `${filePath}_${fileName}`;
    const isDownloading = downloadingFiles.has(fileKey);

    return (
        <TooltipProvider>
            <Tooltip>
                <TooltipTrigger asChild>
                    <button
                        onClick={() => handleDownload(filePath, fileName)}
                        disabled={isDownloading}
                        className={`inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800 hover:underline disabled:opacity-50 disabled:cursor-not-allowed ${className}`}
                    >
                        <span className="text-xs">{fileInfo.icon}</span>
                        <span className="truncate max-w-[150px]">
                            {isDownloading ? "다운로드 중..." : (title || fileName)}
                        </span>
                        <ExternalLinkIcon className="h-3 w-3 opacity-60" />
                    </button>
                </TooltipTrigger>
                <TooltipContent>
                    <div className="text-xs">
                        <div className="font-medium">{fileName}</div>
                        {fileSize && <div className="text-muted-foreground">{formatFileSize(fileSize)}</div>}
                        <div className="text-muted-foreground">클릭하여 다운로드</div>
                    </div>
                </TooltipContent>
            </Tooltip>
        </TooltipProvider>
    );
};

// 사양설명회 다이얼로그
interface SpecificationMeetingDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    bidding: BiddingListItem | null;
}

export function SpecificationMeetingDialog({
    open,
    onOpenChange,
    bidding
}: SpecificationMeetingDialogProps) {
    const [data, setData] = useState<SpecificationMeetingDetails | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (open && bidding) {
            fetchSpecificationMeetingData();
        }
    }, [open, bidding]);

    const fetchSpecificationMeetingData = async () => {
        if (!bidding) return;

        setLoading(true);
        setError(null);
        
        try {
            const result = await getSpecificationMeetingDetailsAction(bidding.id);
            
            if (result.success && result.data) {
                setData(result.data);
            } else {
                setError(result.error || "사양설명회 정보를 불러올 수 없습니다.");
            }
        } catch (err) {
            setError("데이터 로딩 중 오류가 발생했습니다.");
            console.error("Failed to fetch specification meeting data:", err);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl max-h-[90vh]">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <CalendarIcon className="h-5 w-5" />
                        사양설명회 정보
                    </DialogTitle>
                    <DialogDescription>
                        {bidding?.title}의 사양설명회 상세 정보입니다.
                    </DialogDescription>
                </DialogHeader>

                <ScrollArea className="max-h-[75vh]">
                    {loading ? (
                        <div className="flex items-center justify-center py-6">
                            <div className="text-center">
                                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto mb-2"></div>
                                <p className="text-sm text-muted-foreground">로딩 중...</p>
                            </div>
                        </div>
                    ) : error ? (
                        <div className="flex items-center justify-center py-6">
                            <div className="text-center">
                                <p className="text-sm text-destructive mb-2">{error}</p>
                                <Button onClick={fetchSpecificationMeetingData} size="sm">
                                    다시 시도
                                </Button>
                            </div>
                        </div>
                    ) : data ? (
                        <div className="space-y-4">
                            {/* 기본 정보 */}
                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-base">기본 정보</CardTitle>
                                </CardHeader>
                                <CardContent className="pt-0">
                                    <div className="text-sm space-y-1">
                                        <div>
                                            <CalendarIcon className="inline h-3 w-3 text-muted-foreground mr-2" />
                                            <span className="font-medium">날짜:</span> {formatDate(data.meetingDate, "kr")}
                                            {data.meetingTime && <span className="ml-4"><ClockIcon className="inline h-3 w-3 text-muted-foreground mr-1" />{data.meetingTime}</span>}
                                        </div>
                                        
                                        {data.location && (
                                            <div>
                                                <MapPinIcon className="inline h-3 w-3 text-muted-foreground mr-2" />
                                                <span className="font-medium">장소:</span> {data.location}
                                                {data.address && <span className="text-muted-foreground ml-2">({data.address})</span>}
                                            </div>
                                        )}
                                        
                                        <div>
                                            <span className="font-medium">참석 필수:</span>
                                            <Badge variant={data.isRequired ? "destructive" : "secondary"} className="text-xs ml-2">
                                                {data.isRequired ? "필수" : "선택"}
                                            </Badge>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* 연락처 정보 */}
                            {(data.contactPerson || data.contactPhone || data.contactEmail) && (
                                <Card>
                                    <CardHeader className="pb-3">
                                        <CardTitle className="text-base">연락처 정보</CardTitle>
                                    </CardHeader>
                                    <CardContent className="pt-0">
                                        <div className="text-sm">
                                            {[
                                                data.contactPerson && `담당자: ${data.contactPerson}`,
                                                data.contactPhone && `전화: ${data.contactPhone}`,
                                                data.contactEmail && `이메일: ${data.contactEmail}`
                                            ].filter(Boolean).join(' • ')}
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* 안건 및 준비물 */}
                            {(data.agenda || data.materials) && (
                                <Card>
                                    <CardHeader className="pb-3">
                                        <CardTitle className="text-base">안건 및 준비물</CardTitle>
                                    </CardHeader>
                                    <CardContent className="pt-0 space-y-3">
                                        {data.agenda && (
                                            <div>
                                                <span className="font-medium text-sm">안건:</span>
                                                <div className="mt-1 p-2 bg-muted rounded text-sm whitespace-pre-wrap">
                                                    {data.agenda}
                                                </div>
                                            </div>
                                        )}
                                        
                                        {data.materials && (
                                            <div>
                                                <span className="font-medium text-sm">준비물:</span>
                                                <div className="mt-1 p-2 bg-muted rounded text-sm whitespace-pre-wrap">
                                                    {data.materials}
                                                </div>
                                            </div>
                                        )}
                                    </CardContent>
                                </Card>
                            )}

                            {/* 비고 */}
                            {data.notes && (
                                <Card>
                                    <CardHeader className="pb-3">
                                        <CardTitle className="text-base">비고</CardTitle>
                                    </CardHeader>
                                    <CardContent className="pt-0">
                                        <div className="p-2 bg-muted rounded text-sm whitespace-pre-wrap">
                                            {data.notes}
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* 관련 문서 */}
                            {data.documents.length > 0 && (
                                <Card>
                                    <CardHeader className="pb-3">
                                        <CardTitle className="text-base flex items-center gap-2">
                                            <FileTextIcon className="h-4 w-4" />
                                            관련 문서 ({data.documents.length}개)
                                        </CardTitle>
                                    </CardHeader>
                                    <CardContent className="pt-0">
                                        <div className="space-y-2">
                                            {data.documents.map((doc) => (
                                                <div key={doc.id} className="flex items-center gap-2">
                                                    <FileDownloadLink
                                                        filePath={doc.filePath}
                                                        fileName={doc.originalFileName}
                                                        fileSize={doc.fileSize}
                                                        title={doc.title}
                                                    />
                                                </div>
                                            ))}
                                        </div>
                                    </CardContent>
                                </Card>
                            )}
                        </div>
                    ) : null}
                </ScrollArea>
            </DialogContent>
        </Dialog>
    );
}

// PR 문서 다이얼로그는 bidding-pr-documents-dialog.tsx로 이동됨
// import { PrDocumentsDialog } from './bidding-pr-documents-dialog'로 사용하세요


// Re-export for backward compatibility
export { PrDocumentsDialog } from './bidding-pr-documents-dialog'