// 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"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import { useSession } from "next-auth/react"

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 { data: session } = useSession();

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

  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])

  const vendorId = session?.user.companyId

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

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


  // 동기화 실행 함수
  const handleSync = async () => {
    if (documentsContractIds.length === 0) {
      toast.info(t('shiSync.messages.noContractsToSync'))
      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(t('shiSync.messages.noPendingChanges'))
        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(t('shiSync.messages.contractError', { projectId, error: errorMsg }))
            console.error(`Contract ${projectId} sync failed:`, result)
          }
        } catch (error) {
          failedSyncs++
          const errorMessage = error instanceof Error ? error.message : t('shiSync.messages.unknownError')
          errors.push(t('shiSync.messages.contractError', { projectId, error: 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(
            t('shiSync.messages.allSyncCompleted', { successCount: totalSuccessCount }),
            {
              description: t('shiSync.messages.allSyncCompletedDescription', {
                contractCount: successfulSyncs,
                itemCount: totalSuccessCount
              })
            }
          )
        } else if (successfulSyncs > 0) {
          toast.warning(
            t('shiSync.messages.partialSyncCompleted', {
              successfulCount: successfulSyncs,
              failedCount: failedSyncs
            }),
            {
              description: errors.slice(0, 3).join(', ') +
                (errors.length > 3 ? t('shiSync.messages.andMore') : '')
            }
          )
        } else {
          toast.error(
            t('shiSync.messages.allSyncFailed', { failedCount: failedSyncs }),
            {
              description: errors[0] || t('shiSync.messages.allContractsSyncFailed')
            }
          )
        }

        // 모든 contract 상태 갱신
        refetchAll()
        onSyncComplete?.()
      }, 500)

    } catch (error) {
      setSyncProgress(0)
      setCurrentSyncingContract(null)

      const errorMessage = syncUtils.formatError(error as Error)
      toast.error(t('shiSync.messages.syncFailed'), {
        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" />
          {t('shiSync.status.checking')}
        </Badge>
      )
    }

    if (totalStats.hasError) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {t('shiSync.status.connectionError')}
        </Badge>
      )
    }

    if (documentsContractIds.length === 0) {
      return <Badge variant="secondary">{t('shiSync.status.noContracts')}</Badge>
    }

    if (totalStats.totalPending > 0) {
      return (
        <Badge variant="destructive" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          {t('shiSync.status.pendingItems', { count: totalStats.totalPending })}
        </Badge>
      )
    }

    if (totalStats.totalSynced > 0) {
      return (
        <Badge variant="default" className="gap-1 bg-emerald-500 hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700">
          <CheckCircle className="w-3 h-3" />
          {t('shiSync.status.synchronized')}
        </Badge>
      )
    }

    return <Badge variant="secondary">{t('shiSync.status.noChanges')}</Badge>
  }

  return (
    <>
      <Popover>
        <PopoverTrigger asChild>
          <div className="flex items-center gap-3">
            <Button
              variant="default"
              size="sm"
              className="flex items-center gap-2 bg-primary hover:bg-primary/90"
              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">{t('shiSync.buttons.sendToSHI')}</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">{t('shiSync.labels.syncStatus')}</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">{t('shiSync.labels.overallStatus')}</span>
                {getSyncStatusBadge()}
              </div>

              <div className="text-xs text-muted-foreground">
                {t('shiSync.descriptions.targetInfo', {
                  contractCount: documentsContractIds.length,
                  targetSystem
                })}
              </div>
            </div>

            {/* 에러 상태 표시 */}
            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  {t('shiSync.descriptions.statusCheckError')}
                  {process.env.NODE_ENV === 'development' && (
                    <div className="text-xs mt-1 font-mono">
                      Debug: {t('shiSync.descriptions.contractsWithError', {
                        count: 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">{t('shiSync.labels.pending')}</div>
                    <div className="font-medium text-orange-600">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalPending })}
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">{t('shiSync.labels.synced')}</div>
                    <div className="font-medium text-emerald-600 dark:text-emerald-400">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalSynced })}
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-muted-foreground">{t('shiSync.labels.failed')}</div>
                    <div className="font-medium text-destructive">
                      {t('shiSync.labels.itemCount', { count: totalStats.totalFailed })}
                    </div>
                  </div>
                </div>

                {/* EntityType별 상세 통계 추가 */}
                {totalStats.entityTypeDetailsTotals && (
                  <>
                    <Separator className="my-2" />
                    <div className="space-y-2">
                      <div className="text-sm font-medium flex items-center gap-2">
                        {t('shiSync.labels.detailsByType')}
                        {/* <Badge variant="outline" className="text-xs">
                          {t('shiSync.labels.experimental')}
                        </Badge> */}
                      </div>

                      <div className="space-y-1 text-xs">
                        {/* Document 통계 */}
                        {totalStats.entityTypeDetailsTotals.document && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.documents')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.document.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.document.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.document.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.document.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.document.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.document.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}

                        {/* Revision 통계 */}
                        {totalStats.entityTypeDetailsTotals.revision && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.revisions')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.revision.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.revision.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.revision.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.revision.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.revision.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.revision.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}

                        {/* Attachment 통계 */}
                        {totalStats.entityTypeDetailsTotals.attachment && (
                          <div className="flex items-center justify-between p-2 rounded bg-muted/50">
                            <span className="font-medium">
                              {t('shiSync.labels.attachments')}
                            </span>
                            <div className="flex gap-3 text-xs">
                              {totalStats.entityTypeDetailsTotals.attachment.pending > 0 && (
                                <span className="text-orange-600">
                                  {totalStats.entityTypeDetailsTotals.attachment.pending} {t('shiSync.labels.pendingShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.attachment.synced > 0 && (
                                <span className="text-emerald-600">
                                  {totalStats.entityTypeDetailsTotals.attachment.synced} {t('shiSync.labels.syncedShort')}
                                </span>
                              )}
                              {totalStats.entityTypeDetailsTotals.attachment.failed > 0 && (
                                <span className="text-destructive">
                                  {totalStats.entityTypeDetailsTotals.attachment.failed} {t('shiSync.labels.failedShort')}
                                </span>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </>
                )}

                {/* 계약별 상세 상태 */}
                {contractStatuses.length > 1 && (
                  <div className="space-y-2">
                    <div className="text-sm font-medium">{t('shiSync.labels.statusByContract')}</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">{t('shiSync.labels.contractLabel', { projectId })}</span>
                            {isLoading ? (
                              <Badge variant="secondary" className="text-xs">
                                <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                                {t('shiSync.status.loading')}
                              </Badge>
                            ) : error ? (
                              <Badge variant="destructive" className="text-xs">
                                <AlertTriangle className="w-3 h-3 mr-1" />
                                {t('shiSync.status.error')}
                              </Badge>
                            ) : syncStatus && syncStatus.pendingChanges > 0 ? (
                              <Badge variant="destructive" className="text-xs">
                                {t('shiSync.status.pendingCount', { count: syncStatus.pendingChanges })}
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="text-xs">
                                <CheckCircle className="w-3 h-3 mr-1" />
                                {t('shiSync.status.upToDate')}
                              </Badge>
                            )}
                          </div>
                        ))}
                      </div>
                    </ScrollArea>
                  </div>
                )}
              </div>
            )}

            {/* 계약 정보가 없는 경우 */}
            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  {t('shiSync.descriptions.noDocumentsToSync')}
                </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" />
                    {t('shiSync.buttons.syncing')}
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    {t('shiSync.buttons.syncNow')}
                  </>
                )}
              </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" />
              {t('shiSync.dialog.title')}
            </DialogTitle>
            <DialogDescription>
              {t('shiSync.dialog.description', {
                contractCount: 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>{t('shiSync.labels.syncTarget')}</span>
                  <span className="font-medium">{t('shiSync.labels.itemCount', { count: totalStats.totalPending })}</span>
                </div>

                <div className="flex items-center justify-between text-sm">
                  <span>{t('shiSync.labels.targetContracts')}</span>
                  <span className="font-medium">{t('shiSync.labels.contractCount', { count: documentsContractIds.length })}</span>
                </div>

                <div className="text-xs text-muted-foreground">
                  {t('shiSync.descriptions.includesChanges')}
                </div>

                {isSyncing && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>{t('shiSync.labels.progress')}</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" />
                        {t('shiSync.descriptions.currentlyProcessing', { contractId: currentSyncingContract })}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {totalStats.hasError && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  {t('shiSync.descriptions.dialogStatusCheckError')}
                </AlertDescription>
              </Alert>
            )}

            {documentsContractIds.length === 0 && (
              <Alert>
                <AlertDescription>
                  {t('shiSync.descriptions.noContractsToSync')}
                </AlertDescription>
              </Alert>
            )}

            <div className="flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setIsDialogOpen(false)}
                disabled={isSyncing}
              >
                {t('buttons.cancel')}
              </Button>
              <Button
                onClick={handleSync}
                disabled={isSyncing || !totalStats.canSync}
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t('shiSync.buttons.syncing')}
                  </>
                ) : (
                  <>
                    <Send className="w-4 h-4 mr-2" />
                    {t('shiSync.buttons.startSync')}
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}