"use client"

import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Download, Upload, FileSpreadsheet, CheckCircle2, XCircle, Loader2 } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { Badge } from "@/shared/components/ui/badge"
import { downloadBase64File } from "@/shared/lib/download"
import {
  downloadUserTemplateAction,
  importUsersAction,
} from "../actions"
import type { UserImportResult } from "../import-export"

type PreviewRow = Record<string, unknown>

type ImportState = {
  status: "idle" | "preview" | "importing" | "done"
  rows: PreviewRow[]
  fileName: string
  result: UserImportResult | null
}

export function UserImportDialog() {
  const router = useRouter()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [open, setOpen] = useState(false)
  const [state, setState] = useState<ImportState>({
    status: "idle",
    rows: [],
    fileName: "",
    result: null,
  })
  const [downloading, setDownloading] = useState(false)

  const resetState = () => {
    setState({ status: "idle", rows: [], fileName: "", result: null })
    if (fileInputRef.current) fileInputRef.current.value = ""
  }

  const handleDownloadTemplate = async () => {
    setDownloading(true)
    const result = await downloadUserTemplateAction()
    setDownloading(false)
    if (result.success && result.data) {
      downloadBase64File(result.data, result.message ?? "template.xlsx")
      toast.success("模板已下载")
    } else {
      toast.error(result.message ?? "下载失败")
    }
  }

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    const lowerName = file.name.toLowerCase()
    if (!lowerName.endsWith(".xlsx") && !lowerName.endsWith(".xls")) {
      toast.error("仅支持 .xlsx 和 .xls 文件")
      return
    }

    const formData = new FormData()
    formData.append("file", file)

    try {
      const res = await fetch("/api/import", {
        method: "POST",
        body: formData,
      })
      const data = await res.json()
      if (!data.success) {
        toast.error(data.message ?? "解析失败")
        return
      }
      const rows = data.sheets?.[0]?.rows ?? []
      if (rows.length === 0) {
        toast.error("文件中无数据")
        return
      }
      setState({
        status: "preview",
        rows,
        fileName: file.name,
        result: null,
      })
      toast.success(`已解析 ${rows.length} 行数据`)
    } catch {
      toast.error("文件解析失败")
    }
  }

  const handleConfirmImport = async () => {
    if (state.rows.length === 0) return
    setState((s) => ({ ...s, status: "importing" }))

    const formData = new FormData()
    if (fileInputRef.current?.files?.[0]) {
      formData.append("file", fileInputRef.current.files[0])
    } else {
      toast.error("请重新选择文件")
      setState((s) => ({ ...s, status: "preview" }))
      return
    }

    const result = await importUsersAction(null, formData)
    if (result.success && result.data) {
      setState((s) => ({ ...s, status: "done", result: result.data! }))
      toast.success(result.message ?? "导入完成")
      router.refresh()
    } else {
      toast.error(result.message ?? "导入失败")
      setState((s) => ({ ...s, status: "preview" }))
    }
  }

  const headers = state.rows.length > 0 ? Object.keys(state.rows[0]) : []

  return (
    <Dialog
      open={open}
      onOpenChange={(v) => {
        setOpen(v)
        if (!v) resetState()
      }}
    >
      <DialogTrigger asChild>
        <Button>
          <Upload className="mr-2 h-4 w-4" />
          批量导入用户
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>批量导入用户</DialogTitle>
          <DialogDescription>
            下载模板填写用户信息后上传。默认密码为 123456，请提示用户首次登录后修改。
          </DialogDescription>
        </DialogHeader>

        {state.status === "idle" && (
          <div className="space-y-4 py-4">
            <div className="flex gap-2">
              <Button
                variant="outline"
                onClick={handleDownloadTemplate}
                disabled={downloading}
              >
                {downloading ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Download className="mr-2 h-4 w-4" />
                )}
                下载导入模板
              </Button>
            </div>
            <div
              className="rounded-lg border-2 border-dashed border-muted-foreground/25 p-8 text-center cursor-pointer hover:border-primary/50 transition-colors"
              onClick={() => fileInputRef.current?.click()}
            >
              <FileSpreadsheet className="mx-auto h-10 w-10 text-muted-foreground mb-2" />
              <p className="text-sm font-medium">点击选择 Excel 文件</p>
              <p className="text-xs text-muted-foreground mt-1">支持 .xlsx / .xls 格式</p>
              <input
                ref={fileInputRef}
                type="file"
                accept=".xlsx,.xls"
                className="hidden"
                onChange={handleFileSelect}
              />
            </div>
          </div>
        )}

        {state.status === "preview" && (
          <div className="space-y-4 py-2">
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                文件 <span className="font-medium">{state.fileName}</span> · 共 {state.rows.length} 行
              </p>
              <Button variant="ghost" size="sm" onClick={resetState}>
                重新选择
              </Button>
            </div>
            <div className="rounded-md border max-h-96 overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    {headers.map((h) => (
                      <TableHead key={h}>{h}</TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {state.rows.slice(0, 50).map((row, i) => (
                    <TableRow key={i}>
                      {headers.map((h) => (
                        <TableCell key={h}>{String(row[h] ?? "")}</TableCell>
                      ))}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
            {state.rows.length > 50 && (
              <p className="text-xs text-muted-foreground text-center">
                仅显示前 50 行，共 {state.rows.length} 行
              </p>
            )}
          </div>
        )}

        {state.status === "importing" && (
          <div className="py-12 flex flex-col items-center gap-3">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="text-sm text-muted-foreground">正在导入用户...</p>
          </div>
        )}

        {state.status === "done" && state.result && (
          <div className="space-y-4 py-2">
            <div className="grid grid-cols-2 gap-3">
              <div className="rounded-lg border bg-green-50 p-4 dark:bg-green-950/30">
                <div className="flex items-center gap-2">
                  <CheckCircle2 className="h-5 w-5 text-green-600" />
                  <span className="text-2xl font-bold">{state.result.successCount}</span>
                </div>
                <p className="text-sm text-muted-foreground mt-1">成功导入</p>
              </div>
              <div className="rounded-lg border bg-red-50 p-4 dark:bg-red-950/30">
                <div className="flex items-center gap-2">
                  <XCircle className="h-5 w-5 text-red-600" />
                  <span className="text-2xl font-bold">{state.result.failedCount}</span>
                </div>
                <p className="text-sm text-muted-foreground mt-1">导入失败</p>
              </div>
            </div>
            {state.result.errors.length > 0 && (
              <div className="rounded-md border max-h-48 overflow-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-20">行号</TableHead>
                      <TableHead className="w-48">邮箱</TableHead>
                      <TableHead>错误</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {state.result.errors.map((err, i) => (
                      <TableRow key={i}>
                        <TableCell>
                          <Badge variant="outline">{err.row}</Badge>
                        </TableCell>
                        <TableCell className="text-xs">{err.email}</TableCell>
                        <TableCell className="text-xs text-red-600">{err.error}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </div>
        )}

        <DialogFooter>
          {state.status === "preview" && (
            <Button onClick={handleConfirmImport}>
              <Upload className="mr-2 h-4 w-4" />
              确认导入 {state.rows.length} 条
            </Button>
          )}
          {state.status === "done" && (
            <Button onClick={() => { setOpen(false); resetState() }}>
              完成
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
