import { Tag, Space, Button, Spin, Typography } from 'antd';
import { useState, useEffect } from 'react';
import { UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { User, UserRole, UserStatus } from '@/types/api';

const roleColors: Record<UserRole, string> = {
  SUPER_ADMIN: 'red',
  INFLUENCE_ADMIN: 'volcano',
  MAP_ADMIN: 'orange',
  BROADCAST_ADMIN: 'gold',
  CONTENT_ADMIN: 'lime',
  MEDIA_ADMIN: 'purple',
  PAYMENTS_ADMIN: 'green',
  EVENTS_ADMIN: 'cyan',
  SOCIAL_ADMIN: 'magenta',
  POLLS_ADMIN: 'geekblue',
  ANALYTICS_ADMIN: 'processing',
  USER: 'blue',
  TEMP: 'default',
};

const statusColors: Record<UserStatus, string> = {
  ACTIVE: 'green',
  INACTIVE: 'default',
  SUSPENDED: 'red',
  EXPIRED: 'orange',
  PENDING_VERIFICATION: 'purple',
  PENDING_APPROVAL: 'gold',
};

interface UserAccountStatusPanelProps {
  userId: string;
}

export default function UserAccountStatusPanel({ userId }: UserAccountStatusPanelProps) {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    setLoading(true);
    api.get<User>(`/users/${userId}`)
      .then(({ data }) => setUser(data))
      .catch(() => setUser(null))
      .finally(() => setLoading(false));
  }, [userId]);

  if (loading) return <Spin size="small" />;
  if (!user) return <Typography.Text type="secondary">User account not found.</Typography.Text>;

  const roles = Array.isArray(user.roles) && user.roles.length > 0 ? user.roles : [user.role];

  return (
    <div
      style={{
        padding: '10px 12px',
        background: 'rgba(255,255,255,0.04)',
        borderRadius: 6,
        border: '1px solid rgba(255,255,255,0.08)',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <Space size={6}>
          <Tag color={statusColors[user.status]}>{user.status.replace(/_/g, ' ')}</Tag>
          {roles.map((r) => (
            <Tag key={r} color={roleColors[r]} style={{ margin: 0 }}>{r.replace(/_/g, ' ')}</Tag>
          ))}
        </Space>
        <Button
          size="small"
          icon={<UserOutlined />}
          onClick={() => navigate('/app/users')}
        >
          Edit User
        </Button>
      </div>
      <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.45)' }}>
        <span>{user.email}</span>
        {user.lastLoginAt && (
          <span style={{ marginLeft: 12 }}>
            Last login: {dayjs(user.lastLoginAt).format('MMM D, YYYY h:mm A')}
          </span>
        )}
      </div>
    </div>
  );
}
