import { View, Text, Input, Textarea, Button, ScrollView } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState, useCallback } from "react";
import AdminGuard from "../../components/AdminGuard";
import { useUserStore } from "../../store/user";
import {
  getAnnouncements,
  createAnnouncement,
  publishAnnouncement,
  withdrawAnnouncement,
} from "../../api/admin";
import { useInfiniteList } from "../../hooks/useInfiniteList";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

type AnnouncementItem = {
  id: number;
  title: string;
  content: string;
  status: string;
  createdAt: string;
  publishedAt?: string;
};

const STATUS_TABS = [
  { key: "", label: "全部" },
  { key: "published", label: "已发布" },
  { key: "draft", label: "草稿" },
];

const statusLabels: Record<string, string> = {
  draft: "草稿",
  published: "已发布",
  withdrawn: "已撤回",
};

export default function AdminAnnouncementPage() {
  const adminUser = useUserStore((s) => s.adminUser);
  const [activeTab, setActiveTab] = useState("");
  const [showCreate, setShowCreate] = useState(false);

  // Create form
  const [newTitle, setNewTitle] = useState("");
  const [newContent, setNewContent] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const fetcher = useCallback(
    (page: number, pageSize: number) =>
      getAnnouncements({ status: activeTab || undefined, page, size: pageSize }).then((res: any) => ({
        items: res.items || res.records || [],
        total: res.total,
      })),
    [activeTab]
  );

  const { items, loading, loadingMore, hasMore, refresh, loadMore, prepend } =
    useInfiniteList<AnnouncementItem>({ fetcher, pageSize: 20 });

  useDidShow(() => {
    void refresh();
  });

  const onScrollToLower = () => {
    if (hasMore && !loadingMore) void loadMore();
  };

  const doCreate = async (publish: boolean) => {
    if (!newTitle.trim()) {
      Taro.showToast({ title: "请输入标题", icon: "none" });
      return;
    }
    if (!newContent.trim()) {
      Taro.showToast({ title: "请输入内容", icon: "none" });
      return;
    }
    setSubmitting(true);
    try {
      const result = await createAnnouncement({
        title: newTitle.trim(),
        content: newContent.trim(),
        scopeType: adminUser?.roleCode === "BRANCH_ADMIN" ? "branch" : "platform",
        branchIds: adminUser?.branchIds,
      });
      if (publish) {
        await publishAnnouncement(result.id);
      }
      Taro.showToast({ title: publish ? "已发布" : "已保存草稿", icon: "none" });
      setNewTitle("");
      setNewContent("");
      setShowCreate(false);
      void refresh();
    } catch {
      // toast already shown
    } finally {
      setSubmitting(false);
    }
  };

  const doWithdraw = async (id: number) => {
    const res = await showActionDrawer({
      type: "confirm",
      title: "撤回公告",
      content: "确定撤回此公告？",
      confirmText: "撤回",
      cancelText: "取消"
    });
    if (!res.confirm) return;
    try {
      await withdrawAnnouncement(id);
      Taro.showToast({ title: "已撤回", icon: "none" });
      void refresh();
    } catch {
      // toast already shown
    }
  };

  const doPublish = async (id: number) => {
    const res = await showActionDrawer({
      type: "confirm",
      title: "发布公告",
      content: "确定发布此公告？",
      confirmText: "发布",
      cancelText: "取消"
    });
    if (!res.confirm) return;
    try {
      await publishAnnouncement(id);
      Taro.showToast({ title: "已发布", icon: "none" });
      void refresh();
    } catch {
      // toast already shown
    }
  };

  return (
    <AdminGuard>
      <View className="page-shell admin-announcement">
        <View className="page-body admin-announcement__body">
          {/* Tabs + Create Button */}
          <View className="admin-announcement__header">
            <ScrollView scrollX className="admin-announcement__tabs-scroll">
              <View className="admin-announcement__tabs">
                {STATUS_TABS.map((tab) => (
                  <View
                    key={tab.key}
                    className={`admin-announcement__tab ${activeTab === tab.key ? "is-active" : ""}`}
                    onClick={() => setActiveTab(tab.key)}
                  >
                    <Text>{tab.label}</Text>
                  </View>
                ))}
              </View>
            </ScrollView>
            <View className="admin-announcement__create-btn" onClick={() => setShowCreate(true)}>
              <Text>+ 新建</Text>
            </View>
          </View>

          {/* Create Form */}
          {showCreate ? (
            <View className="admin-announcement__form">
              <View className="acc-field">
                <Text className="acc-label">公告标题</Text>
                <Input
                  className="acc-input"
                  value={newTitle}
                  maxlength={100}
                  placeholder="请输入公告标题"
                  onInput={(e) => setNewTitle(e.detail.value)}
                />
              </View>
              <View className="acc-field">
                <Text className="acc-label">公告内容</Text>
                <Textarea
                  className="acc-textarea"
                  value={newContent}
                  maxlength={10000}
                  placeholder="请输入公告内容..."
                  onInput={(e) => setNewContent(e.detail.value)}
                />
              </View>
              <View className="admin-announcement__form-btns">
                <Button className="aa-btn aa-btn--cancel" onClick={() => setShowCreate(false)}>
                  取消
                </Button>
                <Button className="aa-btn aa-btn--draft" onClick={() => void doCreate(false)} disabled={submitting}>
                  保存草稿
                </Button>
                <Button className="aa-btn aa-btn--publish" onClick={() => void doCreate(true)} disabled={submitting}>
                  直接发布
                </Button>
              </View>
            </View>
          ) : null}

          {/* List */}
          <ScrollView
            className="admin-announcement__list"
            scrollY
            refresherEnabled
            refresherTriggered={loading}
            onRefresherRefresh={() => void refresh()}
            onScrollToLower={onScrollToLower}
          >
            {items.length === 0 && !loading ? (
              <View className="admin-announcement__empty">
                <Text>暂无公告</Text>
              </View>
            ) : (
              items.map((item) => (
                <View key={item.id} className="admin-announcement-card">
                  <View className="admin-announcement-card__top">
                    <Text className={`admin-announcement-card__status status--${item.status}`}>
                      {statusLabels[item.status] || item.status}
                    </Text>
                    <Text className="admin-announcement-card__time">
                      {item.publishedAt?.slice(0, 16) || item.createdAt?.slice(0, 16)}
                    </Text>
                  </View>
                  <Text className="admin-announcement-card__title">{item.title}</Text>
                  <Text className="admin-announcement-card__content">
                    {item.content.length > 100 ? item.content.slice(0, 100) + "..." : item.content}
                  </Text>
                  <View className="admin-announcement-card__actions">
                    {item.status === "published" ? (
                      <Text
                        className="admin-announcement-card__action admin-announcement-card__action--warn"
                        onClick={() => void doWithdraw(item.id)}
                      >
                        撤回
                      </Text>
                    ) : null}
                    {item.status === "draft" ? (
                      <Text
                        className="admin-announcement-card__action admin-announcement-card__action--primary"
                        onClick={() => void doPublish(item.id)}
                      >
                        发布
                      </Text>
                    ) : null}
                  </View>
                </View>
              ))
            )}
          </ScrollView>
        </View>
        {actionDrawer}
      </View>
    </AdminGuard>
  );
}
