import { useState } from 'react';
import { Card, Input, Button, List, Space, Typography, Tag, App } from 'antd';
import { PlusOutlined, TeamOutlined, CrownOutlined, LoginOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface TeamInfo {
  id: string;
  name: string;
  captainUserId: string;
  captain: { id: string; name: string | null; email: string };
  members: { id: number; userId: string }[];
}

interface TeamJoinCardProps {
  challengeId: string;
  teams: TeamInfo[];
  maxTeamSize: number;
  onTeamCreated: () => void;
  onTeamJoined: () => void;
}

export default function TeamJoinCard({
  challengeId,
  teams,
  maxTeamSize,
  onTeamCreated,
  onTeamJoined,
}: TeamJoinCardProps) {
  const { message } = App.useApp();
  const [teamName, setTeamName] = useState('');
  const [creating, setCreating] = useState(false);
  const [joiningId, setJoiningId] = useState<string | null>(null);

  const handleCreate = async () => {
    if (!teamName.trim()) return;
    setCreating(true);
    try {
      await api.post(`/social/challenges/${challengeId}/teams`, { name: teamName.trim() });
      message.success('Team created');
      setTeamName('');
      onTeamCreated();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to create team'));
    } finally {
      setCreating(false);
    }
  };

  const handleJoin = async (teamId: string) => {
    setJoiningId(teamId);
    try {
      await api.post(`/social/challenges/${challengeId}/teams/${teamId}/join`);
      message.success('Joined team');
      onTeamJoined();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to join team'));
    } finally {
      setJoiningId(null);
    }
  };

  return (
    <Space direction="vertical" size={16} style={{ width: '100%' }}>
      <Card size="small" title="Create a Team">
        <Space.Compact style={{ width: '100%' }}>
          <Input
            placeholder="Team name"
            value={teamName}
            onChange={(e) => setTeamName(e.target.value)}
            onPressEnter={handleCreate}
            maxLength={100}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            loading={creating}
            onClick={handleCreate}
            disabled={!teamName.trim()}
          >
            Create
          </Button>
        </Space.Compact>
      </Card>

      {teams.length > 0 && (
        <Card size="small" title="Join an Existing Team">
          <List
            size="small"
            dataSource={teams}
            renderItem={(team: TeamInfo) => {
              const isFull = team.members.length >= maxTeamSize;
              return (
                <List.Item
                  actions={[
                    isFull ? (
                      <Tag color="red" key="full">Full</Tag>
                    ) : (
                      <Button
                        key="join"
                        size="small"
                        type="primary"
                        icon={<LoginOutlined />}
                        loading={joiningId === team.id}
                        onClick={() => handleJoin(team.id)}
                      >
                        Join
                      </Button>
                    ),
                  ]}
                >
                  <List.Item.Meta
                    avatar={<TeamOutlined style={{ fontSize: 18 }} />}
                    title={team.name}
                    description={
                      <Space size={8}>
                        <span>{team.members.length}/{maxTeamSize} members</span>
                        <span>
                          <CrownOutlined style={{ color: '#faad14', marginRight: 2 }} />
                          {team.captain.name || team.captain.email}
                        </span>
                      </Space>
                    }
                  />
                </List.Item>
              );
            }}
            locale={{ emptyText: <Typography.Text type="secondary">No teams yet</Typography.Text> }}
          />
        </Card>
      )}
    </Space>
  );
}
