// components/sync/send-to-shi-button.tsx (최종 완성 버전)
"use client"

import * as React from "react"
import { Send, Loader2, CheckCircle, AlertTriangle, Settings, RefreshCw } 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 { ScrollArea } from "@/components/ui/scroll-area"
import { Alert, AlertDescription } from "@/components/ui/alert"
// ✅ 업데이트된 Hook import
import { useClientSyncStatus, useTriggerSync, syncUtils } from "@/hooks/use-sync-status"
import type { EnhancedDocument } from "@/types/enhanced-documents"

interface SendToSHIButtonProps {
  documents?: EnhancedDocument[]
  onSyncComplete?: () => void
  projectType: "ship" | "plant"
}

export function SendToSHIButton({ 
  documents = [], 
  onSyncComplete,
  projectType
}: SendToSHIButtonProps) {
  const [isDialogOpen, setIsDialogOpen] = React.useState(false)
  const [syncProgress, setSyncProgress] = React.useState(0)
  const [currentSyncingContract, setCurrentSyncingContract] = React.useState<number | null>(null)

  const targetSystem = projectType === 'ship' ? "DOLCE" : "SWP"
  
  // 문서에서 유효한 계약 ID 목록 추출 (projectId 사용)
  const documentsContractIds = React.useMemo(() => {
    const validIds = documents
      .map(doc => (doc as any).projectId)
      .filter((id): id is number => typeof id === 'number' && id > 0)
    
    const uniqueIds = [...new Set(validIds)]
    return uniqueIds.sort()
  }, [documents])

  // ✅ 클라이언트 전용 Hook 사용 (서버 사이드 렌더링 호환)
  const { contractStatuses, totalStats, refetchAll } = useClientSyncStatus(
    documentsContractIds, 
    targetSystem
  )

  const { triggerSync, isLoading: isSyncing, error: syncError } = useTriggerSync()

  // 개발 환경에서 디버깅 정보
  React.useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log('SendToSHIButton Debug Info:', {
        documentsContractIds,
        totalStats,
        contractStatuses: contractStatuses.map(({ projectId, syncStatus, error }) => ({
          projectId,
          pendingChanges: syncStatus?.pendingChanges,
          hasError: !!error
        }))
      })
    }
  }, [documentsContractIds, totalStats, contractStatuses])

  // 동기화 실행 함수
  const handleSync = async () => {
    if (documentsContractIds.length === 0) {
      toast.info('동기화할 계약이 없습니다.')
      return
    }
    
    setSyncProgress(0)
    let successfulSyncs = 0
    let failedSyncs = 0
    let totalSuccessCount = 0
    let totalFailureCount = 0
    const errors: string[] = []
    
    try {
      // 동기화 가능한 계약들만 필터링
      const contractsToSync = contractStatuses.filter(({ syncStatus, error }) => {
        if (error) {
          console.warn(`Contract ${contractStatuses.find(c => c.error === error)?.projectId} has error:`, error)
          return false
        }
        if (!syncStatus) return false
        if (!syncStatus.syncEnabled) return false
        if (syncStatus.pendingChanges <= 0) return false
        return true
      })

      if (contractsToSync.length === 0) {
        toast.info('동기화할 변경사항이 없습니다.')
        setIsDialogOpen(false)
        return
      }

      console.log(`Starting sync for ${contractsToSync.length} contracts`)

      // 각 contract별로 순차 동기화
      for (let i = 0; i < contractsToSync.length; i++) {
        const { projectId } = contractsToSync[i]
        setCurrentSyncingContract(projectId)
        
        try {
          console.log(`Syncing contract ${projectId}...`)
          const result = await triggerSync({ 
            projectId, 
            targetSystem 
          })
          
          if (result?.success) {
            successfulSyncs++
            totalSuccessCount += result.successCount || 0
            console.log(`Contract ${projectId} sync successful:`, result)
          } else {
            failedSyncs++
            totalFailureCount += result?.failureCount || 0
            const errorMsg = result?.errors?.[0] || result?.message || 'Unknown sync error'
            errors.push(`Contract ${projectId}: ${errorMsg}`)
            console.error(`Contract ${projectId} sync failed:`, result)
          }
        } catch (error) {
          failedSyncs++
          const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류'
          errors.push(`Contract ${projectId}: ${errorMessage}`)
          console.error(`Contract ${projectId} sync exception:`, error)
        }

        // 진행률 업데이트
        setSyncProgress(((i + 1) / contractsToSync.length) * 100)
      }

      setCurrentSyncingContract(null)
      
      // 결과 처리 및 토스트 표시
      setTimeout(() => {
        setSyncProgress(0)
        setIsDialogOpen(false)
        
        if (failedSyncs === 0) {
          toast.success(
            `모든 계약 동기화 완료: ${totalSuccessCount}건 성공`,
            {
              description: `${successfulSyncs}개 계약에서 ${totalSuccessCount}개 항목이 SHI 시스템으로 전송되었습니다.`
            }
          )
        } else if (successfulSyncs > 0) {
          toast.warning(
            `부분 동기화 완료: ${successfulSyncs}개 성공, ${failedSyncs}개 실패`,
            {
              description: errors.slice(0, 3).join(', ') + (errors.length > 3 ? ' 외 더보기...' : '')
            }
          )
        } else {
          toast.error(
            `동기화 실패: ${failedSyncs}개 계약 모두 실패`,
            {
              description: errors[0] || '모든 계약 동기화에 실패했습니다.'
            }
          )
        }
        
        // 모든 contract 상태 갱신
        refetchAll()
        onSyncComplete?.()
      }, 500)
      
    } catch (error) {
      setSyncProgress(0)
      setCurrentSyncingContract(null)
      
      const errorMessage = syncUtils.formatError(error as Error)
      toast.error('동기화 실패', {
        description: errorMessage
      })
      console.error('Sync process failed:', error)
    }
  }

  // 동기화 상태에 따른 뱃지 생성
  const getSyncStatusBadge = () => {
    if (totalStats.isLoading) {
      return (
        <Badge variant="secondary" className="gap-1">
          <Loader2 className="w-3 h-3 animate-spin" />
          확인 중...
        </Badge>
      )
    }

    if (totalStats.hasError) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          연결 오류
        </Badge>
      )
    }

    if (documentsContractIds.length === 0) {
      return <Badge variant="secondary">계약 없음</Badge>
    }

    if (totalStats.totalPending > 0) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {totalStats.totalPending}건 대기
        </Badge>
      )
    }

    if (totalStats.totalSynced > 0) {
      return (
        <Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
          <CheckCircle className="w-3 h-3" />
          동기화됨
        </Badge>
      )
    }

    return <Badge variant="secondary">변경사항 없음</Badge>
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="default"
              size="sm"
              className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700"
              disabled={isSyncing || totalStats.isLoading || documentsContractIds.length === 0}
            >
              {isSyncing ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Send className="w-4 h-4" />
              )}
              <span className="hidden sm:inline">Send to SHI</span>
              {totalStats.totalPending > 0 && (
                <Badge 
                  variant="destructive" 
                  className="h-5 w-5 p-0 text-xs flex items-center justify-center ml-1"
                >
                  {totalStats.totalPending}
                </Badge>
              )}
            </Button>
          </div>
        </PopoverTrigger>
        
        <PopoverContent className="w-96" align="end">
          <div className="space-y-4">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <h4 className="font-medium">SHI 동기화 상태</h4>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={refetchAll}
                  disabled={totalStats.isLoading}
                  className="h-6 w-6 p-0"
                >
                  {totalStats.isLoading ? (
                    <Loader2 className="w-3 h-3 animate-spin" />
                  ) : (
                    <RefreshCw className="w-3 h-3" />
                  )}
                </Button>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">전체 상태</span>
                {getSyncStatusBadge()}
              </div>
              
              <div className="text-xs text-muted-foreground">
                {documentsContractIds.length}개 계약 대상 • {targetSystem} 시스템
              </div>
            </div>

            {/* 에러 상태 표시 */}
            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요.
                  {process.env.NODE_ENV === 'development' && (
                    <div className="text-xs mt-1 font-mono">
                      Debug: {contractStatuses.filter(({ error }) => error).length}개 계약에서 오류
                    </div>
                  )}
                </AlertDescription>
              </Alert>
            )}

            {/* 정상 상태일 때 통계 표시 */}
            {!totalStats.hasError && documentsContractIds.length > 0 && (
              <div className="space-y-3">
                <Separator />
                
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div className="text-center">
                    <div className="text-muted-foreground">대기 중</div>
                    <div className="font-medium text-orange-600">{totalStats.totalPending}건</div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">동기화됨</div>
                    <div className="font-medium text-green-600">{totalStats.totalSynced}건</div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">실패</div>
                    <div className="font-medium text-red-600">{totalStats.totalFailed}건</div>
                  </div>
                </div>

                {/* 계약별 상세 상태 */}
                {contractStatuses.length > 1 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium">계약별 상태</div>
                    <ScrollArea className="h-32">
                      <div className="space-y-2">
                        {contractStatuses.map(({ projectId, syncStatus, isLoading, error }) => (
                          <div key={projectId} className="flex items-center justify-between text-xs p-2 rounded border">
                            <span className="font-medium">Contract {projectId}</span>
                            {isLoading ? (
                              <Badge variant="secondary" className="text-xs">
                                <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                                로딩...
                              </Badge>
                            ) : error ? (
                              <Badge variant="destructive" className="text-xs">
                                <AlertTriangle className="w-3 h-3 mr-1" />
                                오류
                              </Badge>
                            ) : syncStatus && syncStatus.pendingChanges > 0 ? (
                              <Badge variant="destructive" className="text-xs">
                                {syncStatus.pendingChanges}건 대기
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">
                                <CheckCircle className="w-3 h-3 mr-1" />
                                최신
                              </Badge>
                            )}
                          </div>
                        ))}
                      </div>
                    </ScrollArea>
                  </div>
                )}
              </div>
            )}

            {/* 계약 정보가 없는 경우 */}
            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  동기화할 문서가 없습니다. 문서를 선택해주세요.
                </AlertDescription>
              </Alert>
            )}

            <Separator />

            {/* 액션 버튼들 */}
            <div className="flex gap-2">
              <Button
                onClick={() => setIsDialogOpen(true)}
                disabled={!totalStats.canSync || isSyncing}
                className="flex-1"
                size="sm"
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    동기화 중...
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    지금 동기화
                  </>
                )}
              </Button>
              
              <Button
                variant="outline"
                size="sm"
                onClick={refetchAll}
                disabled={totalStats.isLoading}
                className="px-3"
              >
                {totalStats.isLoading ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Settings className="w-4 h-4" />
                )}
              </Button>
            </div>
          </div>
        </PopoverContent>
      </Popover>

      {/* 동기화 진행 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Send className="w-5 h-5" />
              SHI 시스템으로 동기화
            </DialogTitle>
            <DialogDescription>
              {documentsContractIds.length}개 계약의 변경된 문서 데이터를 {targetSystem} 시스템으로 전송합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {!totalStats.hasError && documentsContractIds.length > 0 && (
              <div className="rounded-lg border p-4 space-y-3">
                <div className="flex items-center justify-between text-sm">
                  <span>전송 대상</span>
                  <span className="font-medium">{totalStats.totalPending}건</span>
                </div>
                
                <div className="flex items-center justify-between text-sm">
                  <span>대상 계약</span>
                  <span className="font-medium">{documentsContractIds.length}개</span>
                </div>
                
                <div className="text-xs text-muted-foreground">
                  문서, 리비전, 첨부파일의 변경사항이 포함됩니다.
                </div>

                {isSyncing && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>진행률</span>
                      <span>{Math.round(syncProgress)}%</span>
                    </div>
                    <Progress value={syncProgress} className="h-2" />
                    {currentSyncingContract && (
                      <div className="text-xs text-muted-foreground flex items-center gap-1">
                        <Loader2 className="w-3 h-3 animate-spin" />
                        현재 처리 중: Contract {currentSyncingContract}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인하고 다시 시도해주세요.
                </AlertDescription>
              </Alert>
            )}

            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  동기화할 계약이 없습니다. 문서를 선택해주세요.
                </AlertDescription>
              </Alert>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isSyncing}
              >
                취소
              </Button>
              <Button
                onClick={handleSync}
                disabled={isSyncing || !totalStats.canSync}
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    동기화 중...
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    동기화 시작
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}