import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip } from 'antd';
import {
  UserAddOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { DashboardRecentSignupsResult, DashboardRecentSignup } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const SOURCE_COLORS: Record<string, string> = {
  AUTHENTICATED: 'blue',
  PUBLIC: 'green',
  ADMIN: 'purple',
};

function SignupRow({ signup }: { signup: DashboardRecentSignup }) {
  const displayName = signup.userName || signup.userEmail;

  return (
    <Flex
      align="center"
      gap={8}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
      }}
    >
      <UserAddOutlined style={{ fontSize: 12, color: '#52c41a', flexShrink: 0 }} />
      <Tooltip title={displayName}>
        <Text strong style={{ fontSize: 13, flexShrink: 0, maxWidth: 100, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {displayName}
        </Text>
      </Tooltip>
      <Tooltip title={signup.shiftTitle}>
        <Text
          type="secondary"
          style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
        >
          {signup.shiftTitle || 'Shift'}
        </Text>
      </Tooltip>
      <Tag
        color={SOURCE_COLORS[signup.signupSource] || 'default'}
        style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
      >
        {signup.signupSource === 'AUTHENTICATED' ? 'Auth' : signup.signupSource === 'PUBLIC' ? 'Public' : signup.signupSource}
      </Tag>
      <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, whiteSpace: 'nowrap' }}>
        {dayjs(signup.signupDate).fromNow(true)}
      </Text>
    </Flex>
  );
}

export default function RecentSignupsCard() {
  const [result, setResult] = useState<DashboardRecentSignupsResult | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchSignups = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<DashboardRecentSignupsResult>('/dashboard/recent-signups');
      setResult(res.data);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchSignups();
    const interval = setInterval(fetchSignups, 3 * 60_000);
    return () => clearInterval(interval);
  }, [fetchSignups]);

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><UserAddOutlined style={{ marginRight: 6, fontSize: 15 }} />Recent Signups</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {result && result.total > 0 && (
            <Text type="secondary" style={{ fontSize: 12 }}>{result.total} (14d)</Text>
          )}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchSignups} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : result && result.signups.length > 0 ? (
        <div>
          {result.signups.map(signup => (
            <SignupRow key={signup.id} signup={signup} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No recent signups</Text>
      )}
    </Card>
  );
}
