// import-from-dolce-button.tsx - 최적화된 버전
"use client"

import * as React from "react"
import { RefreshCw, Download, Loader2, CheckCircle, AlertTriangle } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Separator } from "@/components/ui/separator"
import { SimplifiedDocumentsView } from "@/db/schema"
import { ImportStatus } from "../import-service"
import { useSession } from "next-auth/react"
import { getProjectIdsByVendor } from "../service"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"

// 🔥 API 응답 캐시 (컴포넌트 외부에 선언하여 인스턴스 간 공유)
const statusCache = new Map<string, { data: ImportStatus; timestamp: number }>()
const CACHE_TTL = 2 * 60 * 1000 // 2분 캐시

interface ImportFromDOLCEButtonProps {
  allDocuments: SimplifiedDocumentsView[]
  projectIds?: number[] // 🔥 미리 계산된 projectIds를 props로 받음
  onImportComplete?: () => void
}

// 🔥 디바운스 훅
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = React.useState(value)

  React.useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

export function ImportFromDOLCEButton({ 
  allDocuments, 
  projectIds: propProjectIds,
  onImportComplete 
}: ImportFromDOLCEButtonProps) {
  const [isDialogOpen, setIsDialogOpen] = React.useState(false)
  const [importProgress, setImportProgress] = React.useState(0)
  const [isImporting, setIsImporting] = React.useState(false)
  const [importStatusMap, setImportStatusMap] = React.useState<Map<number, ImportStatus>>(new Map())
  const [statusLoading, setStatusLoading] = React.useState(false)
  const [vendorProjectIds, setVendorProjectIds] = React.useState<number[]>([])
  const [loadingVendorProjects, setLoadingVendorProjects] = React.useState(false)
  
  const { data: session } = useSession()
  const vendorId = session?.user.companyId

  const params = useParams()
  const lng = (params?.lng as string) || "ko"
  const { t } = useTranslation(lng, "engineering")

  // 🔥 allDocuments에서 projectIds 추출 (props로 전달받은 경우 사용)
  const documentsProjectIds = React.useMemo(() => {
    if (propProjectIds) return propProjectIds // props로 받은 경우 그대로 사용
    
    const uniqueIds = [...new Set(allDocuments.map(doc => doc.projectId).filter(Boolean))]
    return uniqueIds.sort()
  }, [allDocuments, propProjectIds])

  // 🔥 최종 projectIds (변경 빈도 최소화)
  const projectIds = React.useMemo(() => {
    if (documentsProjectIds.length > 0) {
      return documentsProjectIds
    }
    return vendorProjectIds
  }, [documentsProjectIds, vendorProjectIds])

  // 🔥 projectIds 디바운싱 (API 호출 과다 방지)
  const debouncedProjectIds = useDebounce(projectIds, 300)

  // 🔥 주요 projectId 메모이제이션
  const primaryProjectId = React.useMemo(() => {
    if (projectIds.length === 1) return projectIds[0]
    
    if (allDocuments.length > 0) {
      const counts = allDocuments.reduce((acc, doc) => {
        const id = doc.projectId || 0
        acc[id] = (acc[id] || 0) + 1
        return acc
      }, {} as Record<number, number>)
      
      return Number(Object.entries(counts)
        .sort(([,a], [,b]) => b - a)[0]?.[0] || projectIds[0] || 0)
    }
    
    return projectIds[0] || 0
  }, [projectIds, allDocuments])

  // 🔥 캐시된 API 호출 함수
  const fetchImportStatusCached = React.useCallback(async (projectId: number): Promise<ImportStatus | null> => {
    const cacheKey = `import-status-${projectId}`
    const cached = statusCache.get(cacheKey)
    
    // 캐시된 데이터가 있고 유효하면 사용
    if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
      return cached.data
    }

    try {
      const response = await fetch(`/api/sync/import/status?projectId=${projectId}&sourceSystem=DOLCE`)
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(errorData.message || 'Failed to fetch import status')
      }
      
      const status = await response.json()
      if (status.error) {
        console.warn(`Status error for project ${projectId}:`, status.error)
        return null
      }
      
      // 캐시에 저장
      statusCache.set(cacheKey, {
        data: status,
        timestamp: Date.now()
      })
      
      return status
    } catch (error) {
      console.error(`Failed to fetch status for project ${projectId}:`, error)
      return null
    }
  }, [])

  // 🔥 모든 projectId에 대한 상태 조회 (최적화된 버전)
  const fetchAllImportStatus = React.useCallback(async () => {
    if (debouncedProjectIds.length === 0) return
    
    setStatusLoading(true)
    const statusMap = new Map<number, ImportStatus>()
    
    try {
      // 🔥 병렬 처리하되 동시 연결 수 제한 (3개씩)
      const batchSize = 3
      const batches = []
      
      for (let i = 0; i < debouncedProjectIds.length; i += batchSize) {
        batches.push(debouncedProjectIds.slice(i, i + batchSize))
      }

      for (const batch of batches) {
        const batchPromises = batch.map(async (projectId) => {
          const status = await fetchImportStatusCached(projectId)
          return { projectId, status }
        })

        const batchResults = await Promise.all(batchPromises)
        
        batchResults.forEach(({ projectId, status }) => {
          if (status) {
            statusMap.set(projectId, status)
          }
        })

        // 배치 간 짧은 지연
        if (batches.length > 1) {
          await new Promise(resolve => setTimeout(resolve, 100))
        }
      }
      
      setImportStatusMap(statusMap)
      
    } catch (error) {
      console.error('Failed to fetch import statuses:', error)
      toast.error(t('dolceImport.messages.statusCheckError'))
    } finally {
      setStatusLoading(false)
    }
  }, [debouncedProjectIds, fetchImportStatusCached, t])

  // 🔥 vendorId로 projects 가져오기 (최적화)
  React.useEffect(() => {
    let isCancelled = false;
  
    if (allDocuments.length !== 0 || !vendorId) return;
  
    setLoadingVendorProjects(true);
  
    getProjectIdsByVendor(vendorId)
      .then((projectIds) => {
        if (!isCancelled) setVendorProjectIds(projectIds);
      })
      .catch((error) => {
        if (!isCancelled) toast.error(t('dolceImport.messages.projectFetchError'));
      })
      .finally(() => {
        if (!isCancelled) setLoadingVendorProjects(false);
      });
  
    return () => { isCancelled = true; };
  }, [allDocuments, vendorId, t]);
  
  // 🔥 컴포넌트 마운트 시 상태 조회 (디바운싱 적용)
  React.useEffect(() => {
    if (debouncedProjectIds.length > 0) {
      fetchAllImportStatus()
    }
  }, [debouncedProjectIds, fetchAllImportStatus])

  

  // 🔥 전체 통계 메모이제이션
  const totalStats = React.useMemo(() => {
    const statuses = Array.from(importStatusMap.values())
    return statuses.reduce((acc, status) => ({
      availableDocuments: acc.availableDocuments + (status.availableDocuments || 0),
      newDocuments: acc.newDocuments + (status.newDocuments || 0),
      updatedDocuments: acc.updatedDocuments + (status.updatedDocuments || 0),
      importEnabled: acc.importEnabled || status.importEnabled
    }), {
      availableDocuments: 0,
      newDocuments: 0,
      updatedDocuments: 0,
      importEnabled: false
    })
  }, [importStatusMap])

  // 🔥 주요 상태 메모이제이션
  const primaryImportStatus = React.useMemo(() => {
    return importStatusMap.get(primaryProjectId)
  }, [importStatusMap, primaryProjectId])

  // 🔥 가져오기 실행 함수 최적화
  const handleImport = React.useCallback(async () => {
    if (projectIds.length === 0) return
    
    setImportProgress(0)
    setIsImporting(true)
    
    try {
      const progressInterval = setInterval(() => {
        setImportProgress(prev => Math.min(prev + 10, 85))
      }, 500)

      // 🔥 순차 처리로 서버 부하 방지
      const results = []
      for (const projectId of projectIds) {
        try {
          const response = await fetch('/api/sync/import', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              projectId, 
              sourceSystem: 'DOLCE' 
            })
          })

          if (!response.ok) {
            const errorData = await response.json()
            throw new Error(`Project ${projectId}: ${errorData.message || 'Import failed'}`)
          }

          const result = await response.json()
          results.push(result)
          
          // 프로젝트 간 짧은 지연
          if (projectIds.length > 1) {
            await new Promise(resolve => setTimeout(resolve, 200))
          }
        } catch (error) {
          console.error(`Import failed for project ${projectId}:`, error)
          results.push({ success: false, error: error instanceof Error ? error.message : 'Unknown error' })
        }
      }
      
      clearInterval(progressInterval)
      setImportProgress(100)
      
      // 결과 집계
      const totalResult = results.reduce((acc, result) => ({
        newCount: acc.newCount + (result.newCount || 0),
        updatedCount: acc.updatedCount + (result.updatedCount || 0),
        skippedCount: acc.skippedCount + (result.skippedCount || 0),
        success: acc.success && result.success
      }), {
        newCount: 0,
        updatedCount: 0,
        skippedCount: 0,
        success: true
      })
      
      setTimeout(() => {
        setImportProgress(0)
        setIsDialogOpen(false)
        setIsImporting(false)
        
        if (totalResult.success) {
          toast.success(
            t('dolceImport.messages.importSuccess'),
            {
              description: t('dolceImport.messages.importSuccessDescription', {
                newCount: totalResult.newCount,
                updatedCount: totalResult.updatedCount,
                skippedCount: totalResult.skippedCount,
                projectCount: projectIds.length
              })
            }
          )
        } else {
          toast.error(
            t('dolceImport.messages.importPartiallyFailed'),
            {
              description: t('dolceImport.messages.importPartiallyFailedDescription')
            }
          )
        }
        
        // 🔥 캐시 무효화
        statusCache.clear()
        fetchAllImportStatus()
        onImportComplete?.()
      }, 500)
      
    } catch (error) {
      setImportProgress(0)
      setIsImporting(false)
      
      toast.error(t('dolceImport.messages.importFailed'), {
        description: error instanceof Error ? error.message : t('dolceImport.messages.unknownError')
      })
    }
  }, [projectIds, fetchAllImportStatus, onImportComplete, t])

  // 🔥 상태 뱃지 메모이제이션
  const statusBadge = React.useMemo(() => {
    if (loadingVendorProjects) {
      return <Badge variant="secondary">{t('dolceImport.status.loadingProjectInfo')}</Badge>
    }

    if (statusLoading) {
      return <Badge variant="secondary">{t('dolceImport.status.checkingConnection')}</Badge>
    }

    if (importStatusMap.size === 0) {
      return <Badge variant="destructive">{t('dolceImport.status.connectionError')}</Badge>
    }

    if (!totalStats.importEnabled) {
      return <Badge variant="secondary">{t('dolceImport.status.importDisabled')}</Badge>
    }

    if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) {
      return (
        <Badge variant="samsung" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {t('dolceImport.status.updatesAvailable', { projectCount: projectIds.length })}
        </Badge>
      )
    }

    return (
      <Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
        <CheckCircle className="w-3 h-3" />
        {t('dolceImport.status.synchronized')}
      </Badge>
    )
  }, [loadingVendorProjects, statusLoading, importStatusMap.size, totalStats, projectIds.length, t])

  const canImport = totalStats.importEnabled && 
    (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0)

  // 🔥 새로고침 핸들러 최적화
  const handleRefresh = React.useCallback(() => {
    statusCache.clear() // 캐시 무효화
    fetchAllImportStatus()
  }, [fetchAllImportStatus])


   // 🔥 자동 동기화 실행 (기존 useEffect들 다음에 추가)
   React.useEffect(() => {
    // 조건: 가져오기 가능하고, 동기화할 항목이 있고, 현재 진행중이 아닐 때
    if (canImport && 
        (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) && 
        !isImporting && 
        !isDialogOpen) {
      
      // 상태 로딩이 완료된 후 잠깐 대기 (사용자가 상태를 확인할 수 있도록)
      const timer = setTimeout(() => {
        console.log(`🔄 자동 동기화 시작: 새 문서 ${totalStats.newDocuments}개, 업데이트 ${totalStats.updatedDocuments}개`)
        
        // 동기화 시작 알림
        toast.info(
          '새로운 문서가 발견되어 자동 동기화를 시작합니다',
          {
            description: `새 문서 ${totalStats.newDocuments}개, 업데이트 ${totalStats.updatedDocuments}개`,
            duration: 3000
          }
        )
        
        // 자동으로 다이얼로그 열고 동기화 실행
        setIsDialogOpen(true)
        
        // 잠깐 후 실제 동기화 시작 (다이얼로그가 열리는 시간)
        setTimeout(() => {
          handleImport()
        }, 500)
      }, 1500) // 1.5초 대기

      return () => clearTimeout(timer)
    }
  }, [canImport, totalStats.newDocuments, totalStats.updatedDocuments, isImporting, isDialogOpen, handleImport])

  
  // 로딩 중이거나 projectIds가 없으면 버튼을 표시하지 않음
  if (projectIds.length === 0) {
    return null 
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              size="sm"
              className="flex items-center border-blue-200 hover:bg-blue-50"
              disabled={isImporting || statusLoading}
            >
              {isImporting ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Download className="w-4 h-4" />
              )}
              <span className="hidden sm:inline">{t('dolceImport.buttons.getList')}</span>
              {totalStats.newDocuments + totalStats.updatedDocuments > 0 && (
                <Badge 
                  variant="samsung" 
                  className="h-5 w-5 p-0 text-xs flex items-center justify-center"
                >
                  {totalStats.newDocuments + totalStats.updatedDocuments}
                </Badge>
              )}
            </Button>
          </div>
        </PopoverTrigger>
        
        <PopoverContent className="w-96">
          <div className="space-y-4">
            <div className="space-y-2">
              <h4 className="font-medium">{t('dolceImport.labels.importStatus')}</h4>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{t('dolceImport.labels.currentStatus')}</span>
                {statusBadge}
              </div>
            </div>

            {/* 프로젝트 소스 표시 */}
            {allDocuments.length === 0 && vendorProjectIds.length > 0 && (
              <div className="text-xs text-blue-600 bg-blue-50 p-2 rounded">
                {t('dolceImport.descriptions.noDocumentsImportAll')}
              </div>
            )}

            {/* 다중 프로젝트 정보 표시 */}
            {projectIds.length > 1 && (
              <div className="text-sm">
                <div className="text-muted-foreground">{t('dolceImport.labels.targetProjects')}</div>
                <div className="font-medium">{t('dolceImport.labels.projectCount', { count: projectIds.length })}</div>
                <div className="text-xs text-muted-foreground">
                  {t('dolceImport.labels.projectIds')}: {projectIds.join(', ')}
                </div>
              </div>
            )}

            {totalStats && (
              <div className="space-y-3">
                <Separator />
                
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <div className="text-muted-foreground">{t('dolceImport.labels.newDocuments')}</div>
                    <div className="font-medium">{totalStats.newDocuments || 0}</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">{t('dolceImport.labels.updates')}</div>
                    <div className="font-medium">{totalStats.updatedDocuments || 0}</div>
                  </div>
                </div>

                <div className="text-sm">
                  <div className="text-muted-foreground">{t('dolceImport.labels.totalDocuments')}</div>
                  <div className="font-medium">{totalStats.availableDocuments || 0}</div>
                </div>

                {/* 각 프로젝트별 세부 정보 */}
                {projectIds.length > 1 && (
                  <details className="text-sm">
                    <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
                      {t('dolceImport.labels.detailsByProject')}
                    </summary>
                    <div className="mt-2 space-y-2 pl-2 border-l-2 border-muted">
                      {projectIds.map(projectId => {
                        const status = importStatusMap.get(projectId)
                        return (
                          <div key={projectId} className="text-xs">
                            <div className="font-medium">{t('dolceImport.labels.projectLabel', { projectId })}</div>
                            {status ? (
                              <div className="text-muted-foreground">
                                {t('dolceImport.descriptions.projectDetails', {
                                  newDocuments: status.newDocuments,
                                  updatedDocuments: status.updatedDocuments
                                })}
                              </div>
                            ) : (
                              <div className="text-destructive">{t('dolceImport.status.statusCheckFailed')}</div>
                            )}
                          </div>
                        )
                      })}
                    </div>
                  </details>
                )}
              </div>
            )}

            <Separator />

            <div className="flex gap-2">
              <Button
                onClick={() => setIsDialogOpen(true)}
                disabled={!canImport || isImporting}
                className="flex-1"
                size="sm"
              >
                {isImporting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t('dolceImport.buttons.importing')}
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    {t('dolceImport.buttons.importNow')}
                  </>
                )}
              </Button>
              
              <Button
                variant="outline"
                size="sm"
                onClick={handleRefresh}
                disabled={statusLoading}
              >
                {statusLoading ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <RefreshCw className="w-4 h-4" />
                )}
              </Button>
            </div>
          </div>
        </PopoverContent>
      </Popover>

      {/* 가져오기 진행 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{t('dolceImport.dialog.title')}</DialogTitle>
            <DialogDescription>
              {t('dolceImport.dialog.description')}
              {projectIds.length > 1 && ` (${t('dolceImport.dialog.multipleProjects', { count: projectIds.length })})`}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {totalStats && (
              <div className="rounded-lg border p-4 space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span>{t('dolceImport.labels.itemsToImport')}</span>
                  <span className="font-medium">
                    {totalStats.newDocuments + totalStats.updatedDocuments}
                  </span>
                </div>
                
                <div className="text-xs text-muted-foreground">
                  {t('dolceImport.descriptions.includesNewAndUpdated')}
                  <br />
                  {t('dolceImport.descriptions.b4DocumentsNote')}
                  {projectIds.length > 1 && (
                    <>
                      <br />
                      {t('dolceImport.descriptions.sequentialImport', { count: projectIds.length })}
                    </>
                  )}
                </div>

                {isImporting && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>{t('dolceImport.labels.progress')}</span>
                      <span>{importProgress}%</span>
                    </div>
                    <Progress value={importProgress} className="h-2" />
                  </div>
                )}
              </div>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isImporting}
              >
                {t('buttons.cancel')}
              </Button>
              <Button
                onClick={handleImport}
                disabled={isImporting || !canImport}
              >
                {isImporting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t('dolceImport.buttons.importing')}
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    {t('dolceImport.buttons.startImport')}
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}