"use client";

import { type ReactNode, useState, useEffect } from "react";
import {
  useFiles,
  useFileStats,
  useDeleteFiles,
  useFileFilter,
} from "@/hooks/use-files";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Input,
  Select,
  Button,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
  Pagination,
} from "@/components/ui";
import { t } from "@/lib/i18n";

/** 格式化文件大小 */
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

export default function FilesPage(): ReactNode {
  const { filter, setPage, setSearch, setMimeType, setEntityType } =
    useFileFilter();
  const { data, loading, error, refetch } = useFiles(filter);
  const { data: stats } = useFileStats();
  const [deleteFiles] = useDeleteFiles();
  const { show } = useToast();
  const [searchInput, setSearchInput] = useState("");
  const [selected, setSelected] = useState<Set<string>>(new Set());

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchInput), 300);
    return () => clearTimeout(timer);
  }, [searchInput, setSearch]);

  const toggleSelect = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (!data || data.items.length === 0) return;
    if (selected.size === data.items.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(data.items.map((f) => f.id)));
    }
  };

  const handleBatchDelete = async () => {
    if (selected.size === 0) {
      show("warning", "请先选择文件");
      return;
    }
    if (!window.confirm(`确认删除选中的 ${selected.size} 个文件？`)) return;
    const ok = await deleteFiles(Array.from(selected));
    if (ok) {
      show("success", `已删除 ${selected.size} 个文件`);
      setSelected(new Set());
      refetch();
    } else {
      show("error", "删除失败");
    }
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.files.title")}
        description="全校文件资源管理"
        actions={
          <Button
            variant="danger"
            onClick={handleBatchDelete}
            disabled={selected.size === 0}
          >
            {t("admin.files.batchDelete")} ({selected.size})
          </Button>
        }
      />

      {/* 统计摘要 */}
      {stats && (
        <div className="grid grid-cols-2 gap-4 mb-4">
          <PaperCard className="p-4">
            <p
              style={{
                fontSize: 11,
                color: "var(--color-ink-muted)",
                textTransform: "uppercase",
                letterSpacing: "0.05em",
              }}
            >
              {t("admin.files.totalFiles")}
            </p>
            <p
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 28,
                color: "var(--color-ink)",
                margin: "8px 0 0 0",
              }}
            >
              {stats.totalFiles}
            </p>
          </PaperCard>
          <PaperCard className="p-4">
            <p
              style={{
                fontSize: 11,
                color: "var(--color-ink-muted)",
                textTransform: "uppercase",
                letterSpacing: "0.05em",
              }}
            >
              {t("admin.files.totalSize")}
            </p>
            <p
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 28,
                color: "var(--color-ink)",
                margin: "8px 0 0 0",
              }}
            >
              {formatFileSize(stats.totalSize)}
            </p>
          </PaperCard>
        </div>
      )}

      {/* 筛选栏 */}
      <PaperCard className="p-4 mb-4">
        <div className="flex gap-3 items-center">
          <Input
            type="search"
            placeholder={t("admin.common.search")}
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            style={{ width: 240 }}
          />
          <Select
            value={filter.mimeType ?? ""}
            onChange={(e) => setMimeType(e.target.value)}
          >
            <option value="">
              {t("admin.common.all")}
              {t("admin.files.mimeType")}
            </option>
            <option value="application/pdf">PDF</option>
            <option value="image/jpeg">JPEG</option>
            <option value="image/png">PNG</option>
            <option value="application/vnd.openxmlformats-officedocument.wordprocessingml.document">
              Word
            </option>
            <option value="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
              Excel
            </option>
            <option value="application/vnd.openxmlformats-officedocument.presentationml.presentation">
              PPT
            </option>
            <option value="video/mp4">MP4</option>
          </Select>
          <Select
            value={filter.entityType ?? ""}
            onChange={(e) => setEntityType(e.target.value)}
          >
            <option value="">
              {t("admin.common.all")}
              {t("admin.files.entityType")}
            </option>
            <option value="exam">考试</option>
            <option value="lesson_plan">教案</option>
            <option value="user_avatar">用户头像</option>
            <option value="announcement">公告</option>
            <option value="homework">作业</option>
          </Select>
        </div>
      </PaperCard>

      {/* 文件列表 */}
      <PaperCard className="p-4">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && data && (
          <>
            {data.items.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <>
                <Table
                  headers={[
                    "",
                    t("admin.files.filename"),
                    t("admin.files.mimeType"),
                    t("admin.files.size"),
                    t("admin.files.entityType"),
                    t("admin.files.uploadedBy"),
                    t("admin.common.createdAt"),
                  ]}
                >
                  {data.items.map((file) => {
                    const isImage = file.mimeType.startsWith("image/");
                    const isPdf = file.mimeType === "application/pdf";
                    return (
                      <TableRow key={file.id}>
                        <TableCell style={{ width: 32 }}>
                          <input
                            type="checkbox"
                            checked={selected.has(file.id)}
                            onChange={() => toggleSelect(file.id)}
                          />
                        </TableCell>
                        <TableCell>
                          {isImage ? (
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: 8,
                              }}
                            >
                              <img
                                src={file.url}
                                alt={file.filename}
                                style={{
                                  width: 32,
                                  height: 32,
                                  objectFit: "cover",
                                  borderRadius: 4,
                                }}
                              />
                              <span>{file.filename}</span>
                            </div>
                          ) : isPdf ? (
                            <a
                              href={file.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{ color: "var(--color-accent)" }}
                            >
                              {file.filename}
                            </a>
                          ) : (
                            <span>{file.filename}</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <span
                            style={{
                              fontFamily: "var(--font-mono)",
                              fontSize: 11,
                            }}
                          >
                            {file.mimeType}
                          </span>
                        </TableCell>
                        <TableCell
                          style={{
                            fontFamily: "var(--font-mono)",
                            fontSize: 11,
                          }}
                        >
                          {formatFileSize(file.size)}
                        </TableCell>
                        <TableCell>{file.entityType}</TableCell>
                        <TableCell>{file.uploadedByName}</TableCell>
                        <TableCell style={{ whiteSpace: "nowrap" }}>
                          {new Date(file.createdAt).toLocaleDateString("zh-CN")}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </Table>
                <div
                  style={{
                    marginTop: 12,
                    marginBottom: 8,
                    fontSize: 12,
                    color: "var(--color-ink-muted)",
                  }}
                >
                  <label
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={
                        data.items.length > 0 &&
                        selected.size === data.items.length
                      }
                      onChange={toggleSelectAll}
                    />
                    全选 (已选 {selected.size}/{data.items.length})
                  </label>
                </div>
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>
    </div>
  );
}
