"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 { getContractIdsByVendor } from "../service" // 서버 액션 import

interface ImportFromDOLCEButtonProps {
  allDocuments: SimplifiedDocumentsView[] // contractId 대신 문서 배열
  onImportComplete?: () => void
}

export function ImportFromDOLCEButton({ 
  allDocuments, 
  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 [vendorContractIds, setVendorContractIds] = React.useState<number[]>([]) // 서버에서 가져온 contractIds
  const [loadingVendorContracts, setLoadingVendorContracts] = React.useState(false)
  const { data: session } = useSession()

  const vendorId = session?.user.companyId;

  // allDocuments에서 추출한 contractIds
  const documentsContractIds = React.useMemo(() => {
    const uniqueIds = [...new Set(allDocuments.map(doc => doc.contractId).filter(Boolean))]
    return uniqueIds.sort()
  }, [allDocuments])

  // 최종 사용할 contractIds (allDocuments가 있으면 문서에서, 없으면 vendor의 모든 contracts)
  const contractIds = React.useMemo(() => {
    if (documentsContractIds.length > 0) {
      return documentsContractIds
    }
    return vendorContractIds
  }, [documentsContractIds, vendorContractIds])

  console.log(contractIds, "contractIds")

  // vendorId로 contracts 가져오기
  React.useEffect(() => {
    const fetchVendorContracts = async () => {
      // allDocuments가 비어있고 vendorId가 있을 때만 실행
      if (allDocuments.length === 0 && vendorId) {
        setLoadingVendorContracts(true)
        try {
          const contractIds = await getContractIdsByVendor(vendorId)
          setVendorContractIds(contractIds)
        } catch (error) {
          console.error('Failed to fetch vendor contracts:', error)
          toast.error('Failed to fetch contract information.')
        } finally {
          setLoadingVendorContracts(false)
        }
      }
    }

    fetchVendorContracts()
  }, [allDocuments.length, vendorId])

  // 주요 contractId (가장 많이 나타나는 것)
  const primaryContractId = React.useMemo(() => {
    if (contractIds.length === 1) return contractIds[0]
    
    if (allDocuments.length > 0) {
      const counts = allDocuments.reduce((acc, doc) => {
        const id = doc.contractId || 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] || contractIds[0] || 0)
    }
    
    return contractIds[0] || 0
  }, [contractIds, allDocuments])

  // 모든 contractId에 대한 상태 조회
  const fetchAllImportStatus = async () => {
    if (contractIds.length === 0) return
    
    setStatusLoading(true)
    const statusMap = new Map<number, ImportStatus>()
    
    try {
      // 각 contractId별로 상태 조회
      const statusPromises = contractIds.map(async (contractId) => {
        try {
          const response = await fetch(`/api/sync/import/status?contractId=${contractId}&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 contract ${contractId}:`, status.error)
            return { contractId, status: null }
          }
          
          return { contractId, status }
        } catch (error) {
          console.error(`Failed to fetch status for contract ${contractId}:`, error)
          return { contractId, status: null }
        }
      })

      const results = await Promise.all(statusPromises)
      
      results.forEach(({ contractId, status }) => {
        if (status) {
          statusMap.set(contractId, status)
        }
      })
      
      setImportStatusMap(statusMap)
      
    } catch (error) {
      console.error('Failed to fetch import statuses:', error)
      toast.error('Unable to check status. Please verify project settings.')
    } finally {
      setStatusLoading(false)
    }
  }

  // 컴포넌트 마운트 시 상태 조회
  React.useEffect(() => {
    if (contractIds.length > 0) {
      fetchAllImportStatus()
    }
  }, [contractIds])

  // 주요 contractId의 상태
  const primaryImportStatus = importStatusMap.get(primaryContractId)

  // 전체 통계 계산
  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 handleImport = async () => {
    if (contractIds.length === 0) return
    
    setImportProgress(0)
    setIsImporting(true)
    
    try {
      // 진행률 시뮬레이션
      const progressInterval = setInterval(() => {
        setImportProgress(prev => Math.min(prev + 10, 85))
      }, 500)

      // 여러 contractId에 대해 순차적으로 가져오기 실행
      const importPromises = contractIds.map(async (contractId) => {
        const response = await fetch('/api/sync/import', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            contractId, 
            sourceSystem: 'DOLCE' 
          })
        })

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

        return response.json()
      })

      const results = await Promise.all(importPromises)
      
      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(
            `DOLCE import completed`,
            {
              description: `New ${totalResult.newCount}, Updated ${totalResult.updatedCount}, Skipped ${totalResult.skippedCount} (${contractIds.length} contracts)`
            }
          )
        } else {
          toast.error(
            `DOLCE import partially failed`,
            {
              description: 'Some contracts failed to import.'
            }
          )
        }
        
        fetchAllImportStatus() // 상태 갱신
        onImportComplete?.()
      }, 500)
      
    } catch (error) {
      setImportProgress(0)
      setIsImporting(false)
      
      toast.error('DOLCE import failed', {
        description: error instanceof Error ? error.message : 'An unknown error occurred.'
      })
    }
  }

  const getStatusBadge = () => {
    if (loadingVendorContracts) {
      return <Badge variant="secondary">Loading contract information...</Badge>
    }

    if (statusLoading) {
      return <Badge variant="secondary">Checking DOLCE connection...</Badge>
    }

    if (importStatusMap.size === 0) {
      return <Badge variant="destructive">DOLCE Connection Error</Badge>
    }

    if (!totalStats.importEnabled) {
      return <Badge variant="secondary">DOLCE Import Disabled</Badge>
    }

    if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) {
      return (
        <Badge variant="samsung" className="gap-1">
          <AlertTriangle className="w-3 h-3" />
          Updates Available ({contractIds.length} contracts)
        </Badge>
      )
    }

    return (
      <Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
        <CheckCircle className="w-3 h-3" />
        Synchronized with DOLCE
      </Badge>
    )
  }

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

  // 로딩 중이거나 contractIds가 없으면 버튼을 표시하지 않음
  if (loadingVendorContracts || contractIds.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">Import from DOLCE</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">DOLCE Import Status</h4>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Current Status</span>
                {getStatusBadge()}
              </div>
            </div>

            {/* 계약 소스 표시 */}
            {allDocuments.length === 0 && vendorContractIds.length > 0 && (
              <div className="text-xs text-blue-600 bg-blue-50 p-2 rounded">
                No documents found, importing from all contracts.
              </div>
            )}

            {/* 다중 계약 정보 표시 */}
            {contractIds.length > 1 && (
              <div className="text-sm">
                <div className="text-muted-foreground">Target Contracts</div>
                <div className="font-medium">{contractIds.length} contracts</div>
                <div className="text-xs text-muted-foreground">
                  Contract IDs: {contractIds.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">New Documents</div>
                    <div className="font-medium">{totalStats.newDocuments || 0}</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">Updates</div>
                    <div className="font-medium">{totalStats.updatedDocuments || 0}</div>
                  </div>
                </div>

                <div className="text-sm">
                  <div className="text-muted-foreground">Total DOLCE Documents (B3/B4/B5)</div>
                  <div className="font-medium">{totalStats.availableDocuments || 0}</div>
                </div>

                {/* 각 계약별 세부 정보 (펼치기/접기 가능) */}
                {contractIds.length > 1 && (
                  <details className="text-sm">
                    <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
                      Details by Contract
                    </summary>
                    <div className="mt-2 space-y-2 pl-2 border-l-2 border-muted">
                      {contractIds.map(contractId => {
                        const status = importStatusMap.get(contractId)
                        return (
                          <div key={contractId} className="text-xs">
                            <div className="font-medium">Contract {contractId}</div>
                            {status ? (
                              <div className="text-muted-foreground">
                                New {status.newDocuments}, Updates {status.updatedDocuments}
                              </div>
                            ) : (
                              <div className="text-destructive">Status check failed</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" />
                    Importing...
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    Import Now
                  </>
                )}
              </Button>
              
              <Button
                variant="outline"
                size="sm"
                onClick={fetchAllImportStatus}
                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>Import Document List from DOLCE</DialogTitle>
            <DialogDescription>
              Import the latest document list from Samsung Heavy Industries DOLCE system.
              {contractIds.length > 1 && ` (${contractIds.length} contracts targeted)`}
            </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>Items to Import</span>
                  <span className="font-medium">
                    {totalStats.newDocuments + totalStats.updatedDocuments}
                  </span>
                </div>
                
                <div className="text-xs text-muted-foreground">
                  Includes new and updated documents (B3, B4, B5).
                  <br />
                  For B4 documents, GTTPreDwg and GTTWorkingDwg issue stages will be auto-generated.
                  {contractIds.length > 1 && (
                    <>
                      <br />
                      Will import sequentially from {contractIds.length} contracts.
                    </>
                  )}
                </div>

                {isImporting && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span>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}
              >
                Cancel
              </Button>
              <Button
                onClick={handleImport}
                disabled={isImporting || !canImport}
              >
                {isImporting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Importing...
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4 mr-2" />
                    Start Import
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}