import { useState, useEffect, useCallback } from 'react';
import { useOutletContext } from 'react-router-dom';
import {
  Row, Col, Card, Statistic, Table, Tag, Typography, Spin, Space, Button, Tooltip,
} from 'antd';
import {
  TeamOutlined,
  HeartOutlined,
  LinkOutlined,
  DisconnectOutlined,
  ThunderboltOutlined,
  BellOutlined,
  TrophyOutlined,
  UsergroupAddOutlined,
  ReloadOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip as RechartsTooltip,
  ResponsiveContainer,
} from 'recharts';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/types/api';

const { Text } = Typography;

interface DashboardStats {
  network: {
    totalUsers: number;
    connectedUsers: number;
    isolatedUsers: number;
    friendships: { total: number; accepted: number; pending: number; declined: number };
    acceptanceRate: number;
    avgFriendsPerUser: number;
    onlineNow: number;
    totalBlocks: number;
  };
  engagement: {
    pokes: { last24h: number; last7d: number; last30d: number };
    recommendations: number;
    digestSubscribers: number;
  };
  achievements: {
    totalUnlocks: number;
    byCategory: Record<string, number>;
    recentUnlocks: Array<{
      userId: string;
      userName: string | null;
      achievementId: string;
      unlockedAt: string;
    }>;
  };
  groups: {
    total: number;
    byType: Record<string, number>;
    avgMembers: number;
    largest: { id: string; name: string; memberCount: number } | null;
  };
  topConnected: Array<{
    rank: number;
    userId: string;
    name: string | null;
    email: string;
    friendCount: number;
  }>;
  friendshipTrends: Array<{ date: string; count: number }>;
}

export default function SocialDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<DashboardStats | null>(null);

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

  const fetchStats = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get('/social/admin/stats');
      setStats(data);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 120_000);
    return () => clearInterval(interval);
  }, [fetchStats]);

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

  if (!stats) return null;

  const { network, engagement, achievements, groups, topConnected, friendshipTrends } = stats;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
        <Button icon={<ReloadOutlined />} onClick={fetchStats} loading={loading}>
          Refresh
        </Button>
      </div>

      {/* Row 1: Network Stats + Engagement */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={16}>
          <Card title={<><TeamOutlined /> Network Overview</>} size="small">
            <Row gutter={[16, 16]}>
              <Col xs={8} sm={6}>
                <Statistic title="Total Users" value={network.totalUsers} prefix={<TeamOutlined />} />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic
                  title="Connected"
                  value={network.connectedUsers}
                  prefix={<LinkOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic
                  title="Isolated"
                  value={network.isolatedUsers}
                  prefix={<DisconnectOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic title="Online Now" value={network.onlineNow} prefix={<EyeOutlined />} valueStyle={{ color: '#1890ff' }} />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic title="Friendships" value={network.friendships.accepted} />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic title="Pending" value={network.friendships.pending} valueStyle={{ color: '#faad14' }} />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic title="Acceptance Rate" value={network.acceptanceRate} suffix="%" valueStyle={{ color: '#52c41a' }} />
              </Col>
              <Col xs={8} sm={6}>
                <Statistic title="Avg Friends" value={network.avgFriendsPerUser} />
              </Col>
            </Row>
            {network.totalBlocks > 0 && (
              <div style={{ marginTop: 8 }}>
                <Text type="secondary">Blocks: {network.totalBlocks}</Text>
              </div>
            )}
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title={<><ThunderboltOutlined /> Engagement</>} size="small">
            <Space direction="vertical" style={{ width: '100%' }} size="small">
              <div>
                <Text type="secondary">Pokes</Text>
                <Row gutter={8}>
                  <Col span={8}><Statistic title="24h" value={engagement.pokes.last24h} valueStyle={{ fontSize: 18 }} /></Col>
                  <Col span={8}><Statistic title="7d" value={engagement.pokes.last7d} valueStyle={{ fontSize: 18 }} /></Col>
                  <Col span={8}><Statistic title="30d" value={engagement.pokes.last30d} valueStyle={{ fontSize: 18 }} /></Col>
                </Row>
              </div>
              <Statistic title="Recommendations" value={engagement.recommendations} prefix={<BellOutlined />} valueStyle={{ fontSize: 18 }} />
              <Statistic title="Digest Subscribers" value={engagement.digestSubscribers} valueStyle={{ fontSize: 18 }} />
            </Space>
          </Card>
        </Col>
      </Row>

      {/* Row 2: Top Connected + Groups + Achievements */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        <Col xs={24} lg={12}>
          <Card title={<><HeartOutlined /> Top Connected Users</>} size="small">
            <Table
              dataSource={topConnected}
              scroll={{ x: 'max-content' }}
              rowKey="userId"
              size="small"
              pagination={false}
              columns={[
                { title: '#', dataIndex: 'rank', width: 40 },
                {
                  title: 'User',
                  key: 'user',
                  render: (_, r) => (
                    <Space>
                      <Text>{r.name || r.email}</Text>
                    </Space>
                  ),
                },
                {
                  title: 'Friends',
                  dataIndex: 'friendCount',
                  width: 80,
                  render: (v: number) => <Tag color="blue">{v}</Tag>,
                },
              ]}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card title={<><UsergroupAddOutlined /> Groups</>} size="small">
            <Statistic title="Total Groups" value={groups.total} />
            {Object.entries(groups.byType).map(([type, count]) => (
              <div key={type} style={{ marginTop: 4 }}>
                <Tag>{type}</Tag> <Text>{count}</Text>
              </div>
            ))}
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">Avg Members: {groups.avgMembers}</Text>
            </div>
            {groups.largest && (
              <div style={{ marginTop: 4 }}>
                <Text type="secondary">Largest: </Text>
                <Tooltip title={`${groups.largest.memberCount} members`}>
                  <Tag color="purple">{groups.largest.name}</Tag>
                </Tooltip>
              </div>
            )}
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card title={<><TrophyOutlined /> Achievements</>} size="small">
            <Statistic title="Total Unlocks" value={achievements.totalUnlocks} />
            {Object.entries(achievements.byCategory).map(([cat, count]) => (
              <div key={cat} style={{ marginTop: 4 }}>
                <Tag color={cat === 'social' ? 'pink' : cat === 'shifts' ? 'cyan' : cat === 'canvass' ? 'green' : 'orange'}>
                  {cat}
                </Tag>
                <Text>{count}</Text>
              </div>
            ))}
            {achievements.recentUnlocks.length > 0 && (
              <div style={{ marginTop: 8 }}>
                <Text type="secondary" style={{ fontSize: 12 }}>Recent:</Text>
                {achievements.recentUnlocks.slice(0, 3).map((u, i) => (
                  <div key={i} style={{ fontSize: 12 }}>
                    <Text>{u.userName || 'Unknown'}</Text>{' '}
                    <Tag style={{ fontSize: 10 }}>{u.achievementId}</Tag>
                  </div>
                ))}
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* Row 3: Friendships Over Time */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        <Col span={24}>
          <Card title="Friendships Over Time (30 days)" size="small">
            {friendshipTrends.length === 0 ? (
              <Text type="secondary">No accepted friendships in the last 30 days.</Text>
            ) : (
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={friendshipTrends}>
                  <XAxis
                    dataKey="date"
                    tickFormatter={(v: string) => v.slice(5)} // MM-DD
                    fontSize={11}
                    stroke="rgba(255,255,255,0.45)"
                  />
                  <YAxis allowDecimals={false} fontSize={11} stroke="rgba(255,255,255,0.45)" />
                  <RechartsTooltip
                    contentStyle={{ background: '#1a1025', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 6 }}
                    labelStyle={{ color: '#fff' }}
                  />
                  <Bar dataKey="count" fill="#9d4edd" radius={[3, 3, 0, 0]} name="Friendships" />
                </BarChart>
              </ResponsiveContainer>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
}
