import { useState, useEffect, useCallback } from 'react';
import { useOutletContext } from 'react-router-dom';
import {
  Tabs, Table, Card, Statistic, Row, Col, Tag, Button, Drawer, Select,
  Popconfirm, Typography, Progress, Space, Spin, message, Grid,
} from 'antd';
import {
  StopOutlined,
  TrophyOutlined,
  BellOutlined,
  LockOutlined,
  DeleteOutlined,
  GiftOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import { useMobile } from '@/hooks/useMobile';
import type { AppOutletContext } from '@/types/api';

const { Text } = Typography;

interface BlockItem {
  id: number;
  userId: string;
  userName: string | null;
  userEmail: string;
  blockedUserId: string;
  blockedUserName: string | null;
  blockedUserEmail: string;
  createdAt: string;
}

interface AchievementStat {
  achievementId: string;
  totalUnlocks: number;
  unlockRate: number;
}

interface NotificationStat {
  type: string;
  total: number;
  read: number;
  readRate: number;
}

interface PrivacyItem {
  setting: string;
  enabled: number;
  disabled: number;
  enabledPercent: number;
}

interface ModerationData {
  blocks: { items: BlockItem[]; total: number };
  achievementStats: AchievementStat[];
  notificationStats: NotificationStat[];
  privacyAdoption: PrivacyItem[];
}

const ACHIEVEMENT_DEFS = [
  { id: 'FIRST_SHIFT', name: 'First Steps', category: 'shifts' },
  { id: 'SHIFT_STREAK_3', name: 'Reliable Volunteer', category: 'shifts' },
  { id: 'SHIFT_STREAK_10', name: 'Shift Champion', category: 'shifts' },
  { id: 'FIRST_CANVASS', name: 'Door Knocker', category: 'canvass' },
  { id: 'CANVASS_50_DOORS', name: 'Neighbourhood Explorer', category: 'canvass' },
  { id: 'CANVASS_100_DOORS', name: 'Community Connector', category: 'canvass' },
  { id: 'CANVASS_500_DOORS', name: 'Door-to-Door Legend', category: 'canvass' },
  { id: 'FIRST_CAMPAIGN_EMAIL', name: 'Voice Heard', category: 'campaigns' },
  { id: 'CAMPAIGN_CHAMPION', name: 'Campaign Champion', category: 'campaigns' },
  { id: 'SOCIAL_BUTTERFLY', name: 'Social Butterfly', category: 'social' },
  { id: 'TEAM_PLAYER', name: 'Team Player', category: 'social' },
];

const CATEGORY_COLORS: Record<string, string> = {
  shifts: 'cyan',
  canvass: 'green',
  campaigns: 'orange',
  social: 'pink',
};

const PRIVACY_LABELS: Record<string, string> = {
  showOnlineStatus: 'Show Online Status',
  showCurrentlyWatching: 'Show Currently Watching',
  showInFriendActivity: 'Show in Friend Activity',
  anonymizePublicComments: 'Anonymize Public Comments',
  hidePublicReactions: 'Hide Public Reactions',
  hidePublicFinishes: 'Hide Public Finishes',
  allowFriendRequests: 'Allow Friend Requests',
  closeFriendsOnlyWatching: 'Close Friends Only Watching',
};

export default function SocialModerationPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { isMobile } = useMobile();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<ModerationData | null>(null);
  const [blockPage, setBlockPage] = useState(1);
  const [grantModalOpen, setGrantModalOpen] = useState(false);
  const [grantUserId, setGrantUserId] = useState('');
  const [grantAchievementId, setGrantAchievementId] = useState('');
  const [grantLoading, setGrantLoading] = useState(false);
  const [userOptions, setUserOptions] = useState<Array<{ value: string; label: string }>>([]);
  const { md } = Grid.useBreakpoint();
  const isMobileScreen = !md;

  useEffect(() => {
    setPageHeader({ title: 'Social Moderation' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const fetchData = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const { data: result } = await api.get('/social/admin/moderation', { params: { page, limit: 20 } });
      setData(result);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleRemoveBlock = async (blockId: number) => {
    try {
      await api.post(`/social/admin/blocks/${blockId}/remove`);
      message.success('Block removed');
      fetchData(blockPage);
    } catch {
      message.error('Failed to remove block');
    }
  };

  const handleSearchUsers = async (query: string) => {
    if (query.length < 2) { setUserOptions([]); return; }
    try {
      const { data: result } = await api.get('/users', { params: { search: query, limit: 10 } });
      setUserOptions(
        (result.users || []).map((u: { id: string; name: string | null; email: string }) => ({
          value: u.id,
          label: u.name ? `${u.name} (${u.email})` : u.email,
        })),
      );
    } catch {
      setUserOptions([]);
    }
  };

  const handleGrant = async () => {
    if (!grantUserId || !grantAchievementId) return;
    setGrantLoading(true);
    try {
      await api.post('/social/admin/achievements/grant', {
        userId: grantUserId,
        achievementId: grantAchievementId,
      });
      message.success('Achievement granted');
      setGrantModalOpen(false);
      setGrantUserId('');
      setGrantAchievementId('');
      fetchData(blockPage);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: string } } })?.response?.data?.error || 'Failed to grant';
      message.error(msg);
    } finally {
      setGrantLoading(false);
    }
  };

  if (loading && !data) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!data) return null;

  const achievementDefMap = new Map(ACHIEVEMENT_DEFS.map((a) => [a.id, a]));
  const drawerWidth = 480;
  const activeDrawerWidth = !isMobileScreen && grantModalOpen ? drawerWidth : 0;

  return (
    <>
      <div
        style={{
          marginRight: activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
      <Tabs
        defaultActiveKey="blocks"
        items={[
          {
            key: 'blocks',
            label: <><StopOutlined /> Blocks ({data.blocks.total})</>,
            children: (
              <Table
                dataSource={data.blocks.items}
                scroll={{ x: 'max-content' }}
                rowKey="id"
                size="small"
                pagination={{
                  total: data.blocks.total,
                  pageSize: 20,
                  current: blockPage,
                  onChange: (p) => { setBlockPage(p); fetchData(p); },
                }}
                columns={[
                  {
                    title: 'Blocker',
                    key: 'blocker',
                    render: (_, r) => (
                      <div>
                        <Text strong>{r.userName || r.userEmail}</Text>
                        {r.userName && <div><Text type="secondary" style={{ fontSize: 11 }}>{r.userEmail}</Text></div>}
                      </div>
                    ),
                  },
                  {
                    title: 'Blocked User',
                    key: 'blocked',
                    render: (_, r) => (
                      <div>
                        <Text strong>{r.blockedUserName || r.blockedUserEmail}</Text>
                        {r.blockedUserName && <div><Text type="secondary" style={{ fontSize: 11 }}>{r.blockedUserEmail}</Text></div>}
                      </div>
                    ),
                  },
                  {
                    title: 'Date',
                    dataIndex: 'createdAt',
                    width: 120,
                    responsive: ['md'] as any,
                    render: (v: string) => new Date(v).toLocaleDateString(),
                  },
                  {
                    title: 'Action',
                    width: 100,
                    render: (_, r) => (
                      <Popconfirm
                        title="Remove this block?"
                        description="Both users will be able to see each other again."
                        onConfirm={() => handleRemoveBlock(r.id)}
                        okText="Remove"
                        okType="danger"
                      >
                        <Button size="small" danger icon={<DeleteOutlined />}>
                          {!isMobile && 'Remove'}
                        </Button>
                      </Popconfirm>
                    ),
                  },
                ]}
              />
            ),
          },
          {
            key: 'achievements',
            label: <><TrophyOutlined /> Achievements</>,
            children: (
              <div>
                <div style={{ marginBottom: 16 }}>
                  <Button
                    type="primary"
                    icon={<GiftOutlined />}
                    onClick={() => setGrantModalOpen(true)}
                  >
                    Grant Achievement
                  </Button>
                </div>
                <Table
                  dataSource={data.achievementStats}
                  scroll={{ x: 'max-content' }}
                  rowKey="achievementId"
                  size="small"
                  pagination={false}
                  columns={[
                    {
                      title: 'Achievement',
                      dataIndex: 'achievementId',
                      render: (id: string) => {
                        const def = achievementDefMap.get(id);
                        return (
                          <Space>
                            <Text strong>{def?.name ?? id}</Text>
                            {def && <Tag color={CATEGORY_COLORS[def.category]}>{def.category}</Tag>}
                          </Space>
                        );
                      },
                    },
                    {
                      title: 'Total Unlocks',
                      dataIndex: 'totalUnlocks',
                      width: 120,
                      sorter: (a, b) => a.totalUnlocks - b.totalUnlocks,
                    },
                    {
                      title: 'Unlock Rate',
                      dataIndex: 'unlockRate',
                      width: 200,
                      responsive: ['md'] as any,
                      render: (v: number) => <Progress percent={v} size="small" />,
                      sorter: (a, b) => a.unlockRate - b.unlockRate,
                    },
                  ]}
                />
              </div>
            ),
          },
          {
            key: 'notifications',
            label: <><BellOutlined /> Notifications</>,
            children: (
              <div>
                <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                  <Col xs={8}>
                    <Card size="small">
                      <Statistic
                        title="Total Sent"
                        value={data.notificationStats.reduce((s, n) => s + n.total, 0)}
                      />
                    </Card>
                  </Col>
                  <Col xs={8}>
                    <Card size="small">
                      <Statistic
                        title="Total Read"
                        value={data.notificationStats.reduce((s, n) => s + n.read, 0)}
                      />
                    </Card>
                  </Col>
                  <Col xs={8}>
                    <Card size="small">
                      <Statistic
                        title="Overall Read Rate"
                        value={(() => {
                          const t = data.notificationStats.reduce((s, n) => s + n.total, 0);
                          const r = data.notificationStats.reduce((s, n) => s + n.read, 0);
                          return t > 0 ? Math.round((r / t) * 100) : 0;
                        })()}
                        suffix="%"
                      />
                    </Card>
                  </Col>
                </Row>
                <Table
                  dataSource={data.notificationStats}
                  scroll={{ x: 'max-content' }}
                  rowKey="type"
                  size="small"
                  pagination={false}
                  columns={[
                    {
                      title: 'Type',
                      dataIndex: 'type',
                      render: (v: string) => <Tag>{v.replace(/_/g, ' ')}</Tag>,
                    },
                    { title: 'Total', dataIndex: 'total', width: 100, sorter: (a, b) => a.total - b.total },
                    { title: 'Read', dataIndex: 'read', width: 100 },
                    {
                      title: 'Read Rate',
                      dataIndex: 'readRate',
                      width: 200,
                      render: (v: number) => <Progress percent={v} size="small" status={v < 30 ? 'exception' : 'normal'} />,
                      sorter: (a, b) => a.readRate - b.readRate,
                    },
                  ]}
                />
              </div>
            ),
          },
          {
            key: 'privacy',
            label: <><LockOutlined /> Privacy</>,
            children: (
              <Table
                dataSource={data.privacyAdoption}
                scroll={{ x: 'max-content' }}
                rowKey="setting"
                size="small"
                pagination={false}
                columns={[
                  {
                    title: 'Setting',
                    dataIndex: 'setting',
                    render: (v: string) => <Text>{PRIVACY_LABELS[v] || v}</Text>,
                  },
                  {
                    title: 'Enabled',
                    dataIndex: 'enabled',
                    width: 100,
                    render: (v: number) => <Tag color="green">{v}</Tag>,
                  },
                  {
                    title: 'Disabled',
                    dataIndex: 'disabled',
                    width: 100,
                    render: (v: number) => <Tag color="default">{v}</Tag>,
                  },
                  {
                    title: 'Adoption',
                    dataIndex: 'enabledPercent',
                    width: 200,
                    render: (v: number) => <Progress percent={v} size="small" />,
                    sorter: (a, b) => a.enabledPercent - b.enabledPercent,
                  },
                ]}
              />
            ),
          },
        ]}
      />
      </div>

      {/* Grant Achievement Drawer */}
      <Drawer
        title="Grant Achievement"
        open={grantModalOpen}
        onClose={() => { setGrantModalOpen(false); setGrantUserId(''); setGrantAchievementId(''); }}
        placement="right"
        width={isMobileScreen ? '100%' : drawerWidth}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button
            type="primary"
            loading={grantLoading}
            disabled={!grantUserId || !grantAchievementId}
            onClick={handleGrant}
          >
            Grant
          </Button>
        }
      >
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div>
            <Text strong style={{ display: 'block', marginBottom: 4 }}>User</Text>
            <Select
              showSearch
              value={grantUserId || undefined}
              placeholder="Search for a user..."
              filterOption={false}
              onSearch={handleSearchUsers}
              onChange={setGrantUserId}
              options={userOptions}
              style={{ width: '100%' }}
            />
          </div>
          <div>
            <Text strong style={{ display: 'block', marginBottom: 4 }}>Achievement</Text>
            <Select
              value={grantAchievementId || undefined}
              placeholder="Select achievement..."
              onChange={setGrantAchievementId}
              options={ACHIEVEMENT_DEFS.map((a) => ({
                value: a.id,
                label: `${a.name} (${a.category})`,
              }))}
              style={{ width: '100%' }}
            />
          </div>
        </Space>
      </Drawer>
    </>
  );
}
