import { headers } from "next/headers";
import { desc } from "drizzle-orm";

import { auth } from "@/lib/auth";
import { db } from "@/db";
import { upload } from "@/db/schema";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { FileUpload } from "@/components/file-upload";
import { UploadDeleteButton } from "@/components/upload-delete-button";
import { FileIcon, Upload as UploadIcon } from "lucide-react";

function formatSize(bytes: number) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function formatDate(date: Date) {
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export default async function UploadsPage() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  const uploads = await db
    .select()
    .from(upload)
    .orderBy(desc(upload.createdAt))
    .limit(100);

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-1">
        <h1 className="text-2xl font-semibold tracking-tight">文件管理</h1>
        <p className="text-sm text-muted-foreground">
          上传文件到阿里云 OSS，获取 CDN 加速链接。
        </p>
      </div>

      {/* 上传区 */}
      <Card>
        <CardHeader>
          <CardTitle>上传文件</CardTitle>
          <CardDescription>
            文件将上传到 OSS 并返回 CDN 加速 URL
          </CardDescription>
        </CardHeader>
        <CardContent>
          <FileUpload />
        </CardContent>
      </Card>

      {/* 文件列表 */}
      <Card>
        <CardHeader>
          <CardTitle>文件列表</CardTitle>
          <CardDescription>共 {uploads.length} 个文件</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>文件名</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead className="text-right">大小</TableHead>
                  <TableHead>上传时间</TableHead>
                  <TableHead>CDN 链接</TableHead>
                  <TableHead className="w-10 text-right"></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {uploads.length === 0 ? (
                  <TableRow>
                    <TableCell
                      colSpan={6}
                      className="py-8 text-center text-muted-foreground"
                    >
                      暂无文件，上传一个试试吧
                    </TableCell>
                  </TableRow>
                ) : (
                  uploads.map((file) => (
                    <TableRow key={file.id}>
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <FileIcon className="size-4 shrink-0 text-muted-foreground" />
                          <span className="truncate font-medium">
                            {file.originalName}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{file.mimeType}</Badge>
                      </TableCell>
                      <TableCell className="text-right tabular-nums">
                        {formatSize(file.size)}
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {formatDate(file.createdAt)}
                      </TableCell>
                      <TableCell>
                        <a
                          href={file.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-sm text-primary hover:underline"
                        >
                          {file.url.length > 40
                            ? `${file.url.slice(0, 37)}...`
                            : file.url}
                        </a>
                      </TableCell>
                      <TableCell className="text-right">
                        <UploadDeleteButton id={file.id} name={file.originalName} />
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
