import React, { useCallback, useEffect, useState } from 'react';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Switch from '@mui/material/Switch';
import FormControlLabel from '@mui/material/FormControlLabel';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import RssFeedIcon from '@mui/icons-material/RssFeed';
import { getSettings, saveSettings } from '../../api/settings.js';
import { listCategories, updateCategoryProfile } from '../../api/forum.js';
import { showSnack } from '../snack.jsx';

/** 完整订阅 URL（运行时拼 origin，不硬编码域名） */
function feedUrl(path) {
  return window.location.origin + path;
}

/** 版块图标小方块：icon 非 http 渲染 emoji/首字 */
function CatIcon({ c }) {
  const isImg = /^https?:\/\//i.test(c.icon || '');
  const letter = isImg ? (c.name || '?').charAt(0) : (c.icon || (c.name || '?').charAt(0));
  return (
    <Box
      sx={{
        width: 30, height: 30, borderRadius: 2, flexShrink: 0, fontWeight: 700, fontSize: 15,
        display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
        background: c.icon_color || 'rgba(0,0,0,0.08)', color: '#fff',
      }}
    >
      {letter}
    </Box>
  );
}

/**
 * RSS 订阅管理（admin，路由 /admin/rss）：
 * 1) 源管理：博客（常开只读）/ 论坛全站（feed_forum_enabled）/ 各版块（feed_enabled，即时保存）
 * 2) 内容设置：feed_show_full（全文/摘要）+ feed_max_items（1-100）→ saveSettings
 */
export default function RssManage() {
  const [cats, setCats] = useState([]);
  const [forumFeed, setForumFeed] = useState(true);
  const [showFull, setShowFull] = useState('0');
  const [maxItems, setMaxItems] = useState('20');
  const [saving, setSaving] = useState(false);

  const load = useCallback(() => {
    getSettings()
      .then((s) => {
        setForumFeed(s.feed_forum_enabled !== '0'); // 默认开启
        setShowFull(s.feed_show_full === '1' ? '1' : '0');
        setMaxItems(s.feed_max_items || '20');
      })
      .catch((e) => showSnack(e.message, 'error'));
    listCategories()
      .then((cs) => setCats(cs || []))
      .catch((e) => showSnack(e.message, 'error'));
  }, []);

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

  const copyUrl = async (url) => {
    try {
      await navigator.clipboard.writeText(url);
      showSnack('链接已复制');
    } catch {
      showSnack('复制失败，请手动复制', 'error');
    }
  };

  // 论坛全站开关：即时保存
  const toggleForumFeed = async (next) => {
    setForumFeed(next);
    try {
      await saveSettings({ feed_forum_enabled: next ? '1' : '0' });
      showSnack(next ? '已开启论坛订阅' : '已关闭论坛订阅');
    } catch (e) {
      setForumFeed(!next);
      showSnack(e.message, 'error');
    }
  };

  // 版块级开关：即时保存（feed_enabled 已进 profile 白名单）
  const toggleCatFeed = async (cat, next) => {
    const prev = cat.feed_enabled !== 0 && cat.feed_enabled !== '0';
    setCats((cs) => cs.map((c) => (c.id === cat.id ? { ...c, feed_enabled: next ? 1 : 0 } : c)));
    try {
      await updateCategoryProfile(cat.id, { feed_enabled: next ? '1' : '0' });
      showSnack(next ? `已开启「${cat.name}」订阅` : `已关闭「${cat.name}」订阅`);
    } catch (e) {
      setCats((cs) => cs.map((c) => (c.id === cat.id ? { ...c, feed_enabled: prev ? 1 : 0 } : c)));
      showSnack(e.message, 'error');
    }
  };

  const saveContent = async () => {
    const n = parseInt(maxItems, 10);
    if (isNaN(n) || n < 1 || n > 100) { showSnack('条目数需为 1-100 的数字', 'error'); return; }
    setSaving(true);
    try {
      await saveSettings({ feed_show_full: showFull, feed_max_items: String(n) });
      showSnack('内容设置已保存');
    } catch (e) {
      showSnack(e.message, 'error');
    }
    setSaving(false);
  };

  /** 源行：名称/描述 + URL（复制）+ 开关 */
  const SourceRow = ({ name, desc, path, onToggle, checked, disabled, badge }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, py: 1.25, borderBottom: '1px solid', borderColor: 'divider', '&:last-of-type': { borderBottom: 'none' } }}>
      <Box sx={{ minWidth: 0, flex: 1 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="body2" sx={{ fontWeight: 600, fontSize: 14 }}>{name}</Typography>
          {badge}
        </Box>
        {desc && <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>{desc}</Typography>}
        <Box component="code" sx={{
          display: 'flex', alignItems: 'center', gap: 0.5, mt: 0.5,
          fontSize: 12, color: 'text.secondary', fontFamily: 'monospace',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {feedUrl(path)}
          <IconButton size="small" onClick={() => copyUrl(feedUrl(path))} title="复制链接" sx={{ flexShrink: 0 }}>
            <ContentCopyIcon sx={{ fontSize: 14 }} />
          </IconButton>
        </Box>
      </Box>
      {disabled ? (
        <Chip size="small" label="始终启用" variant="outlined" sx={{ flexShrink: 0 }} />
      ) : (
        <FormControlLabel
          control={<Switch checked={checked} onChange={(e) => onToggle(e.target.checked)} />}
          label=""
          sx={{ m: 0, flexShrink: 0 }}
        />
      )}
    </Box>
  );

  return (
    <Box sx={{ maxWidth: 720 }}>
      <Typography variant="h5" sx={{ mb: 0.5 }}>RSS 订阅</Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2, fontSize: 13 }}>
        管理各位置的订阅源：订阅器（如 Feedly / Inoreader）可关注这些链接获取最新内容
      </Typography>

      {/* 源管理 */}
      <Paper id="sec-rss-sources" sx={{ p: 2.5, mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
          <RssFeedIcon fontSize="small" sx={{ color: 'primary.main' }} />
          <Typography variant="h6" sx={{ fontSize: 16 }}>订阅源</Typography>
        </Box>

        <SourceRow
          name="博客"
          desc="已发布文章（全文/摘要按下方内容设置）"
          path="/feed.xml"
          disabled
        />
        <SourceRow
          name="论坛（全站）"
          desc="全部版块的最新帖子"
          path="/feed/forum.xml"
          checked={forumFeed}
          onToggle={toggleForumFeed}
        />

        {cats.length > 0 && (
          <Box sx={{ mt: 1 }}>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5 }}>
              版块级订阅（关闭后该版块不进入全站源，其独立源返回 404）
            </Typography>
            {cats.map((c) => {
              const on = c.feed_enabled !== 0 && c.feed_enabled !== '0';
              return (
                <Box key={c.id} sx={{ display: 'flex', alignItems: 'center', gap: 1.5, py: 1, borderBottom: '1px solid', borderColor: 'divider' }}>
                  <CatIcon c={c} />
                  <Box sx={{ minWidth: 0, flex: 1 }}>
                    <Typography variant="body2" sx={{ fontWeight: 600, fontSize: 14 }}>{c.name}</Typography>
                    <Box component="code" sx={{
                      display: 'flex', alignItems: 'center', gap: 0.5,
                      fontSize: 12, color: 'text.secondary', fontFamily: 'monospace',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>
                      {feedUrl(`/feed/forum/c/${c.id}.xml`)}
                      <IconButton size="small" onClick={() => copyUrl(feedUrl(`/feed/forum/c/${c.id}.xml`))} title="复制链接" sx={{ flexShrink: 0 }}>
                        <ContentCopyIcon sx={{ fontSize: 14 }} />
                      </IconButton>
                    </Box>
                  </Box>
                  <FormControlLabel
                    control={<Switch checked={on} onChange={(e) => toggleCatFeed(c, e.target.checked)} />}
                    label=""
                    sx={{ m: 0, flexShrink: 0 }}
                  />
                </Box>
              );
            })}
          </Box>
        )}
      </Paper>

      {/* 内容设置 */}
      <Paper id="sec-rss-content" sx={{ p: 2.5 }}>
        <Typography variant="h6" sx={{ mb: 1, fontSize: 16 }}>内容设置</Typography>

        <FormControlLabel
          control={<Switch checked={showFull === '1'} onChange={(e) => setShowFull(e.target.checked ? '1' : '0')} />}
          label={(
            <Box sx={{ py: 0.5 }}>
              <Box sx={{ fontSize: 14, fontWeight: 500 }}>输出全文</Box>
              <Box sx={{ fontSize: 12, color: 'text.secondary' }}>关闭则仅输出摘要（博客用文章摘要，论坛用内容截断）</Box>
            </Box>
          )}
        />

        <TextField
          label="每条源最大条目数"
          type="number"
          value={maxItems}
          onChange={(e) => setMaxItems(e.target.value)}
          inputProps={{ min: 1, max: 100 }}
          helperText="1-100，默认 20"
          sx={{ mt: 1.5, maxWidth: 220 }}
        />

        <Box sx={{ mt: 2 }}>
          <Button variant="contained" onClick={saveContent} disabled={saving}>
            {saving ? '保存中…' : '保存内容设置'}
          </Button>
        </Box>
      </Paper>
    </Box>
  );
}
