import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Card, Typography, Statistic, Row, Col, Skeleton, Space, Tag, Alert, Button } from 'antd';
import { TeamOutlined, ScheduleOutlined, EnvironmentOutlined, TrophyOutlined, CalendarOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import UserAvatar from '@/components/social/UserAvatar';
import FriendButton from '@/components/social/FriendButton';
import PokeButton from '@/components/social/PokeButton';
import MessageButton from '@/components/social/MessageButton';
import type { SocialProfile, SocialProfileMe, AchievementWithProgress } from '@/types/social';
import dayjs from 'dayjs';
import { getErrorMessage } from '@/utils/getErrorMessage';

export default function SocialProfilePage() {
  const { userId } = useParams<{ userId: string }>();
  const { user: currentUser } = useAuthStore();
  const isOwnProfile = !userId || userId === currentUser?.id;

  const [profileMe, setProfileMe] = useState<SocialProfileMe | null>(null);
  const [profileOther, setProfileOther] = useState<SocialProfile | null>(null);
  const [achievements, setAchievements] = useState<AchievementWithProgress[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchProfile = async () => {
    setLoading(true);
    setError(null);
    try {
      if (isOwnProfile) {
        const [profileRes, achRes] = await Promise.all([
          api.get<SocialProfileMe>('/social/profile/me'),
          api.get('/social/achievements'),
        ]);
        setProfileMe(profileRes.data);
        setAchievements(achRes.data.achievements?.filter((a: AchievementWithProgress) => a.unlocked) || []);
      } else {
        const [profileRes, achRes] = await Promise.all([
          api.get<SocialProfile>(`/social/profile/${userId}`),
          api.get(`/social/achievements/user/${userId}`).catch(() => ({ data: { achievements: [] } })),
        ]);
        setProfileOther(profileRes.data);
        setAchievements(achRes.data.achievements || []);
      }
    } catch (err: unknown) {
      setError(getErrorMessage(err, 'Failed to load profile'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchProfile(); }, [userId]);

  if (loading) return <Skeleton active paragraph={{ rows: 6 }} />;
  if (error) return <Alert message="Error" description={error} type="error" showIcon />;

  // Own profile
  if (isOwnProfile && profileMe) {
    const { user, stats } = profileMe;
    return (
      <div style={{ padding: '12px 0' }}>
        <Card>
          <Space direction="vertical" align="center" style={{ width: '100%', textAlign: 'center' }}>
            <UserAvatar userId={user.id} name={user.name} email={user.email} size={72} />
            <Typography.Title level={4} style={{ margin: 0 }}>
              {user.name || user.email}
            </Typography.Title>
            <Typography.Text type="secondary">
              Joined {dayjs(user.createdAt).format('MMM YYYY')}
            </Typography.Text>
            <Tag>{user.role}</Tag>
          </Space>
        </Card>

        <Card title="Volunteer Stats" style={{ marginTop: 12 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Statistic title="Friends" value={stats.friendCount} prefix={<TeamOutlined />} />
            </Col>
            <Col span={8}>
              <Statistic title="Shifts" value={stats.shiftSignups} prefix={<ScheduleOutlined />} />
            </Col>
            <Col span={8}>
              <Statistic title="Doors" value={stats.canvassVisits} prefix={<EnvironmentOutlined />} />
            </Col>
          </Row>
        </Card>

        {achievements.length > 0 && (
          <Card
            title={<><TrophyOutlined /> Badges ({achievements.length})</>}
            size="small"
            style={{ marginTop: 12 }}
            extra={<Link to="/volunteer/achievements">View all</Link>}
          >
            <Space wrap>
              {achievements.slice(0, 6).map((a) => (
                <Tag key={a.id} color="gold">{a.name}</Tag>
              ))}
            </Space>
          </Card>
        )}

        {stats.pendingReceived > 0 && (
          <Alert
            message={`${stats.pendingReceived} pending friend request${stats.pendingReceived > 1 ? 's' : ''}`}
            type="info"
            showIcon
            style={{ marginTop: 12 }}
          />
        )}
      </div>
    );
  }

  // Other user's profile
  if (profileOther) {
    const { user, friendCount, stats, friendshipStatus, mutualFriends } = profileOther;
    return (
      <div style={{ padding: '12px 0' }}>
        <Card>
          <Space direction="vertical" align="center" style={{ width: '100%', textAlign: 'center' }}>
            <UserAvatar userId={user.id} name={user.name} email={user.email} size={72} showOnline />
            <Typography.Title level={4} style={{ margin: 0 }}>
              {user.name || user.email}
            </Typography.Title>
            <Typography.Text type="secondary">
              Joined {dayjs(user.createdAt).format('MMM YYYY')}
            </Typography.Text>
            <Space>
              <Tag>{user.role}</Tag>
              <Typography.Text type="secondary">{friendCount} friends</Typography.Text>
            </Space>

            <Space>
              <FriendButton
                userId={user.id}
                status={friendshipStatus}
                onStatusChange={fetchProfile}
              />
              <PokeButton
                userId={user.id}
                isFriend={friendshipStatus.status === 'accepted'}
              />
              <MessageButton
                friendId={user.id}
                isFriend={friendshipStatus.status === 'accepted'}
              />
              {friendshipStatus.status === 'accepted' && (
                <Link to={`/volunteer/calendar/friend/${user.id}`}>
                  <Button icon={<CalendarOutlined />}>View Calendar</Button>
                </Link>
              )}
            </Space>
          </Space>
        </Card>

        {mutualFriends.count > 0 && (
          <Card size="small" style={{ marginTop: 12 }}>
            <Typography.Text type="secondary">
              {mutualFriends.count} mutual friend{mutualFriends.count > 1 ? 's' : ''}
              {mutualFriends.users.length > 0 && ': '}
              {mutualFriends.users.map((u) => u.name || u.email).join(', ')}
            </Typography.Text>
          </Card>
        )}

        {stats && (
          <Card title="Volunteer Stats" style={{ marginTop: 12 }}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic title="Shifts" value={stats.shiftSignups} prefix={<ScheduleOutlined />} />
              </Col>
              <Col span={12}>
                <Statistic title="Doors" value={stats.canvassVisits} prefix={<EnvironmentOutlined />} />
              </Col>
            </Row>
          </Card>
        )}

        {achievements.length > 0 && (
          <Card
            title={<><TrophyOutlined /> Badges ({achievements.length})</>}
            size="small"
            style={{ marginTop: 12 }}
          >
            <Space wrap>
              {achievements.map((a) => (
                <Tag key={a.id} color="gold">{a.name}</Tag>
              ))}
            </Space>
          </Card>
        )}
      </div>
    );
  }

  return null;
}
