import { useState, useEffect } from "react";
import { adminFetch } from "./adminApi";
import { useToast } from "./Toast";
import { copyItemLink } from "./utils";
import MusicForm from "./MusicForm";
import QRCodeModal from "./QRCodeModal";
import PageHeader, {
  PrimaryButton,
  StatusChip,
  ActionButton,
  EmptyState,
  LoadingBlock,
  IconEdit,
  IconCopy,
  IconQR,
  IconDelete,
} from "./PageHeader";
import { TableCard, TableHeadRow } from "./StampList";

type Music = {
  id: string;
  title: string;
  subtitle: string | null;
  audioFile: string;
  sortOrder: number;
  enabled: boolean;
};

export default function MusicList() {
  const toast = useToast();
  const [music, setMusic] = useState<Music[]>([]);
  const [loading, setLoading] = useState(true);

  const [formState, setFormState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });
  const [qrState, setQrState] = useState<{ open: boolean; id: string | null }>({ open: false, id: null });

  const fetchMusic = async () => {
    try {
      const data = await adminFetch<Music[]>("/music");
      setMusic(data);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMusic();
  }, []);

  const handleDelete = async (id: string, title: string) => {
    if (!confirm(`确定删除音乐「${title}」？`)) return;
    try {
      await adminFetch(`/music/${id}`, { method: "DELETE" });
      toast.show("已删除");
      fetchMusic();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "删除失败", "error");
    }
  };

  const handleToggle = async (id: string, enabled: boolean) => {
    await adminFetch(`/music/${id}`, {
      method: "PUT",
      body: JSON.stringify({ enabled: !enabled }),
    });
    fetchMusic();
  };

  const handleCopyLink = async (id: string) => {
    try {
      await copyItemLink("music", id);
      toast.show("链接已复制");
    } catch {
      toast.show("复制失败", "error");
    }
  };

  return (
    <>
      <PageHeader
        eyebrow="04 · Music"
        title="音乐管理"
        caption="音频作品与对应点位的 NFC 链接"
        action={<PrimaryButton onClick={() => setFormState({ open: true, id: null })}>添加音乐</PrimaryButton>}
      />

      {loading ? (
        <LoadingBlock />
      ) : (
        <TableCard>
          {music.length === 0 ? (
            <EmptyState
              message="尚未上传音乐"
              action={
                <PrimaryButton onClick={() => setFormState({ open: true, id: null })}>
                  添加第一首音乐
                </PrimaryButton>
              }
            />
          ) : (
            <table className="w-full">
              <thead>
                <TableHeadRow cols={["标题 · 副标题", "音频", "排序", "状态", "操作"]} />
              </thead>
              <tbody>
                {music.map((item, i) => (
                  <tr
                    key={item.id}
                    className="border-t border-[var(--border-muted)] hover:bg-white/60 transition-colors animate-admin-row"
                    style={{ animationDelay: `${Math.min(i, 12) * 0.03}s` }}
                  >
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-3">
                        <div
                          className="w-10 h-10 rounded-full flex items-center justify-center shrink-0 border border-[var(--border-muted)]"
                          style={{ backgroundColor: "rgba(212,165,116,0.08)" }}
                        >
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--gold)" strokeWidth="1.8">
                            <path d="M9 18V5l12-2v13M9 9l12-2" />
                            <circle cx="6" cy="18" r="3" />
                            <circle cx="18" cy="16" r="3" />
                          </svg>
                        </div>
                        <div className="min-w-0">
                          <p className="text-[15px] font-medium text-[var(--text-primary)]">{item.title}</p>
                          {item.subtitle && (
                            <p className="text-xs text-[var(--text-muted)] mt-0.5 max-w-[260px] truncate">
                              {item.subtitle}
                            </p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-4 w-[260px]">
                      {item.audioFile ? (
                        <audio
                          src={item.audioFile}
                          controls
                          preload="none"
                          className="h-8 max-w-[240px]"
                        />
                      ) : (
                        <span className="text-xs text-[var(--text-muted)]/60">未上传</span>
                      )}
                    </td>
                    <td className="px-5 py-4 text-center w-[80px]">
                      <span
                        className="text-[13px] text-[var(--text-secondary)]"
                        style={{ fontFamily: "'Playfair Display', serif" }}
                      >
                        {item.sortOrder}
                      </span>
                    </td>
                    <td className="px-5 py-4 text-center w-[110px]">
                      <StatusChip enabled={item.enabled} onClick={() => handleToggle(item.id, item.enabled)} />
                    </td>
                    <td className="px-5 py-4 w-[180px]">
                      <div className="flex items-center justify-end gap-1">
                        <ActionButton title="编辑" onClick={() => setFormState({ open: true, id: item.id })}>
                          {IconEdit}
                        </ActionButton>
                        <ActionButton title="复制链接" onClick={() => handleCopyLink(item.id)}>
                          {IconCopy}
                        </ActionButton>
                        <ActionButton title="二维码" onClick={() => setQrState({ open: true, id: item.id })}>
                          {IconQR}
                        </ActionButton>
                        <ActionButton
                          title="删除"
                          variant="danger"
                          onClick={() => handleDelete(item.id, item.title)}
                        >
                          {IconDelete}
                        </ActionButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </TableCard>
      )}

      <MusicForm
        open={formState.open}
        id={formState.id}
        onClose={() => setFormState({ open: false, id: null })}
        onSaved={fetchMusic}
      />
      <QRCodeModal
        open={qrState.open}
        type="music"
        id={qrState.id}
        onClose={() => setQrState({ open: false, id: null })}
      />
    </>
  );
}
