"use client";

import { type ReactNode, useState, useEffect } from "react";
import {
  useAnnouncements,
  useAnnouncementFilter,
  useCreateAnnouncement,
  usePublishAnnouncement,
  useArchiveAnnouncement,
  useToggleAnnouncementPin,
} from "@/hooks/use-announcements";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Input,
  Select,
  Button,
  Badge,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
  Pagination,
} from "@/components/ui";
import { t } from "@/lib/i18n";
import type { AnnouncementViewModel } from "@/types/view-models";

const AUDIENCE_OPTIONS = [
  { value: "all", label: "全部" },
  { value: "teachers", label: "教师" },
  { value: "students", label: "学生" },
  { value: "parents", label: "家长" },
] as const;

const audienceLabel: Record<string, string> = {
  all: "全部",
  teachers: "教师",
  students: "学生",
  parents: "家长",
};

export default function AnnouncementsPage(): ReactNode {
  const { filter, setPage, setSearch, setStatus } = useAnnouncementFilter();
  const { data, loading, error } = useAnnouncements(filter);
  const { show } = useToast();
  const [createAnnouncement] = useCreateAnnouncement();
  const [publishAnnouncement] = usePublishAnnouncement();
  const [archiveAnnouncement] = useArchiveAnnouncement();
  const [togglePin] = useToggleAnnouncementPin();
  const [searchInput, setSearchInput] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [formTitle, setFormTitle] = useState("");
  const [formContent, setFormContent] = useState("");
  const [formAudience, setFormAudience] = useState<string[]>(["all"]);
  const [submitting, setSubmitting] = useState(false);

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

  const openCreateModal = () => {
    setFormTitle("");
    setFormContent("");
    setFormAudience(["all"]);
    setModalOpen(true);
  };

  const toggleAudience = (value: string) => {
    setFormAudience((prev) => {
      if (value === "all") {
        return ["all"];
      }
      const next = prev.filter((a) => a !== "all");
      if (next.includes(value)) {
        const filtered = next.filter((a) => a !== value);
        return filtered.length === 0 ? ["all"] : filtered;
      }
      return [...next, value];
    });
  };

  const handleCreate = async () => {
    if (!formTitle.trim() || !formContent.trim()) {
      show("warning", "请填写标题和内容");
      return;
    }
    setSubmitting(true);
    try {
      await createAnnouncement({
        title: formTitle,
        content: formContent,
        audience: formAudience,
      });
      show("success", "公告已创建");
      setModalOpen(false);
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "创建失败",
        err instanceof Error ? err.message : String(err),
      );
    } finally {
      setSubmitting(false);
    }
  };

  const handlePublish = async (ann: AnnouncementViewModel) => {
    try {
      await publishAnnouncement(ann.id);
      show("success", "公告已发布");
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "操作失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  const handleArchive = async (ann: AnnouncementViewModel) => {
    try {
      await archiveAnnouncement(ann.id);
      show("success", "公告已归档");
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "操作失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  const handleTogglePin = async (ann: AnnouncementViewModel) => {
    try {
      await togglePin(ann.id);
      show("success", ann.isPinned ? "已取消置顶" : "已置顶");
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "操作失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.announcements.title")}
        description="管理全校公告、发布与归档"
        actions={
          <Button variant="primary" onClick={openCreateModal}>
            {t("admin.announcements.new")}
          </Button>
        }
      />

      <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.status ?? "all"}
            onChange={(e) => setStatus(e.target.value)}
          >
            <option value="all">{t("admin.common.all")}</option>
            <option value="draft">{t("admin.announcements.draft")}</option>
            <option value="published">
              {t("admin.announcements.published")}
            </option>
            <option value="archived">
              {t("admin.announcements.archived")}
            </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.common.status"),
                    t("admin.announcements.audience"),
                    t("admin.announcements.author"),
                    t("admin.announcements.pin"),
                    t("admin.announcements.readCount"),
                    t("admin.announcements.publishedAt"),
                    t("admin.common.createdAt"),
                    t("admin.common.actions"),
                  ]}
                >
                  {data.items.map((ann) => (
                    <TableRow key={ann.id}>
                      <TableCell style={{ fontWeight: 500 }}>
                        {ann.title}
                      </TableCell>
                      <TableCell>
                        <Badge status={ann.status} />
                      </TableCell>
                      <TableCell>
                        {ann.audience
                          .map((a) => audienceLabel[a] ?? a)
                          .join(", ")}
                      </TableCell>
                      <TableCell>{ann.authorName}</TableCell>
                      <TableCell>
                        {ann.isPinned ? <Badge status="pinned" /> : "—"}
                      </TableCell>
                      <TableCell>
                        {ann.readCount}/{ann.totalCount}
                      </TableCell>
                      <TableCell style={{ whiteSpace: "nowrap" }}>
                        {ann.publishedAt
                          ? new Date(ann.publishedAt).toLocaleDateString(
                              "zh-CN",
                            )
                          : "—"}
                      </TableCell>
                      <TableCell style={{ whiteSpace: "nowrap" }}>
                        {new Date(ann.createdAt).toLocaleDateString("zh-CN")}
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          {ann.status === "draft" && (
                            <Button
                              variant="primary"
                              onClick={() => handlePublish(ann)}
                            >
                              {t("admin.announcements.publish")}
                            </Button>
                          )}
                          {ann.status === "published" && (
                            <Button
                              variant="secondary"
                              onClick={() => handleArchive(ann)}
                            >
                              {t("admin.announcements.archive")}
                            </Button>
                          )}
                          <Button
                            variant="ghost"
                            onClick={() => handleTogglePin(ann)}
                          >
                            {ann.isPinned
                              ? t("admin.announcements.unpin")
                              : t("admin.announcements.pin")}
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </Table>
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>

      {modalOpen && (
        <div
          role="dialog"
          aria-modal="true"
          style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0,0,0,0.4)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1000,
          }}
        >
          <div
            style={{
              width: 480,
              padding: 24,
              background: "var(--bg-paper)",
              borderRadius: 8,
              border: "1px solid var(--color-rule)",
            }}
          >
            <h2
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 18,
                color: "var(--color-ink)",
                marginBottom: 16,
              }}
            >
              {t("admin.announcements.new")}
            </h2>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  标题
                </span>
                <Input
                  type="text"
                  value={formTitle}
                  onChange={(e) => setFormTitle(e.target.value)}
                  placeholder="请输入公告标题"
                />
              </div>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  内容
                </span>
                <textarea
                  value={formContent}
                  onChange={(e) => setFormContent(e.target.value)}
                  rows={5}
                  style={{
                    padding: "6px 10px",
                    border: "1px solid var(--color-rule)",
                    borderRadius: 4,
                    background: "var(--bg-paper)",
                    color: "var(--color-ink)",
                    fontSize: 13,
                    resize: "vertical",
                  }}
                  placeholder="请输入公告内容"
                />
              </label>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  {t("admin.announcements.audience")}
                </span>
                <div className="flex gap-3">
                  {AUDIENCE_OPTIONS.map((opt) => (
                    <label
                      key={opt.value}
                      className="flex items-center gap-1"
                      style={{
                        fontSize: 13,
                        color: "var(--color-ink)",
                        cursor: "pointer",
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={formAudience.includes(opt.value)}
                        onChange={() => toggleAudience(opt.value)}
                      />
                      {opt.label}
                    </label>
                  ))}
                </div>
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "flex-end",
                  gap: 8,
                  marginTop: 8,
                }}
              >
                <Button variant="secondary" onClick={() => setModalOpen(false)}>
                  {t("admin.common.cancel")}
                </Button>
                <Button
                  variant="primary"
                  onClick={handleCreate}
                  disabled={submitting}
                >
                  {submitting
                    ? t("admin.common.loading")
                    : t("admin.common.save")}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
