"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { AdminSidebar } from "@/components/layout/admin-sidebar"
import { AdminHeader } from "@/components/layout/admin-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { useAuthStore } from "@/store/auth-store"
import { AuthGuard } from "@/components/auth/auth-guard"
import {
  IconUpload,
  IconCheck,
  IconX,
  IconAlertCircle,
  IconFileText,
} from "@tabler/icons-react"
import { cn } from "@/lib/utils"

interface FileType {
  id: string
  order: number
  title: string
  description: string
  fileType: string
  exampleFileName: string
}

const FILE_TYPES: FileType[] = [
  {
    id: "animal-info",
    order: 1,
    title: "① 개체정보",
    description: "농장주명 + 개체번호 매핑 정보 (필수: 가장 먼저 업로드)",
    fileType: "유전자",  // 백엔드 FileType.GENE
    exampleFileName: "25년_코쿤_충북한우유전체SNP분석결과_miDNA유전체연구소.xlsx",
  },
  {
    id: "genome-result",
    order: 2,
    title: "② 유전능력평가 결과 (DGV)",
    description: "533두의 유전체 분석 데이터 (CSV 파일)",
    fileType: "유전체",  // 백엔드 FileType.GENOME
    exampleFileName: "2_20250702)2025_유전체 분석결과(DGV)_...",
  },
  {
    id: "snp-typing",
    order: 3,
    title: "③ 개체별 SNP 타이핑 결과",
    description: "개체별 SNP 유전자형 분석 결과",
    fileType: "유전자",  // 백엔드 FileType.GENE
    exampleFileName: "KOR002108023350.xlsx",
  },
  {
    id: "mpt-result",
    order: 4,
    title: "④ MPT 분석결과",
    description: "혈액 샘플 분석 결과 (선택사항)",
    fileType: "혈액대사검사",  // 백엔드 FileType.MPT
    exampleFileName: "■종합혈액화학검사결과서_통합_20250520.xls",
  },
]

interface UploadState {
  file: File | null
  status: "idle" | "uploading" | "success" | "error"
  message: string
  isDragging: boolean
  fileType: FileType
}

function FileUploadCard({ fileType }: { fileType: FileType }) {
  const [state, setState] = React.useState<UploadState>({
    file: null,
    status: "idle",
    message: "",
    isDragging: false,
    fileType: fileType,
  })
  const fileInputRef = React.useRef<HTMLInputElement>(null)

  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setState(prev => ({ ...prev, isDragging: true }))
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setState(prev => ({ ...prev, isDragging: false }))
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setState(prev => ({ ...prev, isDragging: false }))

    const files = e.dataTransfer.files
    if (files && files.length > 0) {
      const file = files[0]
      if (isValidFile(file)) {
        setState(prev => ({ ...prev, file, status: "idle", message: "" }))
      } else {
        setState(prev => ({
          ...prev,
          status: "error",
          message: "엑셀/CSV 파일(.xlsx, .xls, .csv)만 업로드 가능합니다.",
        }))
      }
    }
  }

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (files && files.length > 0) {
      const file = files[0]
      if (isValidFile(file)) {
        setState(prev => ({ ...prev, file, status: "idle", message: "" }))
      } else {
        setState(prev => ({
          ...prev,
          status: "error",
          message: "엑셀/CSV 파일(.xlsx, .xls, .csv)만 업로드 가능합니다.",
        }))
      }
    }
  }

  const isValidFile = (file: File): boolean => {
    const validExtensions = [
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "application/vnd.ms-excel",
      "text/csv",
      "application/csv",
      "application/haansoftxls",
      "text/plain",
    ]
    return (
      validExtensions.includes(file.type) ||
      file.name.endsWith(".xlsx") ||
      file.name.endsWith(".xls") ||
      file.name.endsWith(".csv") ||
      file.name.endsWith(".txt")
    )
  }

  const handleUpload = async () => {
    if (!state.file) {
      setState(prev => ({
        ...prev,
        status: "error",
        message: "파일을 선택해주세요.",
      }))
      return
    }

    setState(prev => ({ ...prev, status: "uploading", message: "" }))

    try {
      const formData = new FormData()
      formData.append("file", state.file)
      formData.append("div", state.fileType.id)


      // const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/uploadfile`, {
      //   method: "POST",
      //   body: formData,
      //   headers: {
      //     'Authorization': `Bearer ${localStorage.getItem('accessToken')}`,
      //   },
      // })

      // 배치 파일 업로드 테스트
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/admin/batchUpload`, {
        method: "POST",
        body: formData,
        headers: {
          'Authorization': `Bearer ${useAuthStore.getState().accessToken}`,
        },
      })



      if (!response.ok) {
        throw new Error("파일 업로드에 실패했습니다.")
      }

      const result = await response.json()

      setState(prev => ({
        ...prev,
        status: "success",
        message: result.message || "파일이 성공적으로 업로드되었습니다.",
      }))

      setTimeout(() => {
        setState({
          file: null,
          status: "idle",
          message: "",
          isDragging: false,
          fileType: fileType,
        })
        if (fileInputRef.current) {
          fileInputRef.current.value = ""
        }
      }, 3000)
    } catch (error) {
      setState(prev => ({
        ...prev,
        status: "error",
        message:
          error instanceof Error
            ? error.message
            : "파일 업로드 중 오류가 발생했습니다.",
      }))
    }
  }

  const handleRemoveFile = () => {
    setState({
      file: null,
      status: "idle",
      message: "",
      isDragging: false,
      fileType: fileType,
    })
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 Bytes"
    const k = 1024
    const sizes = ["Bytes", "KB", "MB", "GB"]
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i]
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <IconFileText className="h-5 w-5" />
          {fileType.title}
        </CardTitle>
        <CardDescription>
          {fileType.description}
          <br />
          <span className="text-xs mt-1 inline-block">
            예시: <code className="bg-muted px-1 py-0.5 rounded">{fileType.exampleFileName}</code>
          </span>
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 파일 업로드 영역 */}
        <div
          onDragEnter={handleDragEnter}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          className={cn(
            "relative border-2 border-dashed rounded-lg p-6 text-center transition-colors",
            state.isDragging
              ? "border-primary bg-primary/5"
              : "border-muted-foreground/25 hover:border-muted-foreground/50",
            state.file && "border-primary bg-primary/5"
          )}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".xlsx,.xls"
            onChange={handleFileSelect}
            className="hidden"
            id={`file-upload-${fileType.id}`}
          />

          {!state.file ? (
            <div className="space-y-3">
              <div className="flex justify-center">
                <IconUpload className="h-10 w-10 text-muted-foreground" />
              </div>
              <div className="space-y-1">
                <p className="text-sm font-medium">
                  파일을 드래그하거나 클릭하여 선택하세요
                </p>
                <p className="text-xs text-muted-foreground">
                  지원 형식: .xlsx, .xls, .csv
                </p>
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() =>
                  document.getElementById(`file-upload-${fileType.id}`)?.click()
                }
              >
                파일 선택
              </Button>
            </div>
          ) : (
            <div className="space-y-3">
              <div className="flex justify-center">
                <IconCheck className="h-10 w-10 text-green-600" />
              </div>
              <div className="space-y-1">
                <p className="text-sm font-medium">{state.file.name}</p>
                <p className="text-xs text-muted-foreground">
                  {formatFileSize(state.file.size)}
                </p>
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleRemoveFile}
              >
                <IconX className="h-4 w-4 mr-1" />
                파일 제거
              </Button>
            </div>
          )}
        </div>

        {/* 업로드 상태 메시지 */}
        {state.message && (
          <div
            className={cn(
              "flex items-center gap-2 p-3 rounded-lg text-sm",
              state.status === "success" &&
                "bg-green-50 text-green-900 border border-green-200",
              state.status === "error" &&
                "bg-red-50 text-red-900 border border-red-200",
              state.status === "uploading" &&
                "bg-blue-50 text-blue-900 border border-blue-200"
            )}
          >
            {state.status === "success" && <IconCheck className="h-5 w-5" />}
            {state.status === "error" && <IconAlertCircle className="h-5 w-5" />}
            <span>{state.message}</span>
          </div>
        )}

        {/* 업로드 버튼 */}
        <div className="flex justify-end">
          <Button
            type="button"
            onClick={handleUpload}
            disabled={!state.file || state.status === "uploading"}
          >
            {state.status === "uploading" ? (
              <>
                <span className="mr-2">업로드 중...</span>
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
              </>
            ) : (
              <>
                <IconUpload className="h-4 w-4 mr-2" />
                업로드
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

function AdminUploadContent() {
  const { user } = useAuthStore()
  const router = useRouter()

  React.useEffect(() => {
    const isAdmin = user?.userRole === 'ADMIN'
    if (user && !isAdmin) {
      alert('관리자만 접근 가능합니다.')
      router.push('/dashboard')
    }
  }, [user, router])

  const isAdmin = user?.userRole === 'ADMIN'
  if (!user || !isAdmin) {
    return null
  }

  return (
    <SidebarInset>
      <AdminHeader
        breadcrumbs={[
          { label: "관리자", href: "/admin" },
          { label: "파일 업로드" }
        ]}
      />

      <div className="flex flex-1 flex-col gap-2">
        <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
          {/* 헤더 */}
          <div className="px-4 lg:px-6">
            <div className="rounded-lg p-6 border" style={{ backgroundColor: '#3b82f610' }}>
              <h1 className="text-2xl font-bold mb-2">파일 업로드</h1>
              <p className="text-sm text-muted-foreground">
                유전체 분석 관련 데이터 파일을 업로드하여 시스템에 등록합니다.
              </p>
            </div>
          </div>

          {/* 파일 업로드 카드들 - 1열로 배치하여 순서 명확히 */}
          <div className="px-4 lg:px-6">
            <div className="grid gap-6 md:grid-cols-1">
              {FILE_TYPES.sort((a, b) => a.order - b.order).map((fileType) => (
                <FileUploadCard key={fileType.id} fileType={fileType} />
              ))}
            </div>
          </div>
        </div>
      </div>
    </SidebarInset>
  )
}

export default function AdminUploadPage() {
  return (
    <AuthGuard>
      <SidebarProvider>
        <AdminSidebar />
        <AdminUploadContent />
      </SidebarProvider>
    </AuthGuard>
  )
}
