import { useState, useCallback } from 'react';
import {
  List,
  Button,
  Typography,
  Tag,
  Space,
  Modal,
  Checkbox,
  message,
  Empty,
  Skeleton,
  Popconfirm,
} from 'antd';
import { UserAddOutlined, LogoutOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { SharedCalendarMember } from '@/types/api';

const { Text } = Typography;

interface Friend {
  id: string;
  name: string | null;
  email: string;
}

interface SharedViewMembersPanelProps {
  viewId: string;
  members: SharedCalendarMember[];
  isOwner: boolean;
  onInvite: () => void;
  onLeave: () => void;
  onRefresh: () => void;
}

export default function SharedViewMembersPanel({
  viewId,
  members,
  isOwner,
  onInvite: _onInvite,
  onLeave,
  onRefresh,
}: SharedViewMembersPanelProps) {
  const [inviteModalOpen, setInviteModalOpen] = useState(false);
  const [friends, setFriends] = useState<Friend[]>([]);
  const [selectedFriends, setSelectedFriends] = useState<string[]>([]);
  const [loadingFriends, setLoadingFriends] = useState(false);
  const [inviting, setInviting] = useState(false);

  const memberUserIds = new Set(members.map((m) => m.userId));

  const fetchFriends = useCallback(async () => {
    setLoadingFriends(true);
    try {
      const { data } = await api.get('/social/friends');
      const accepted = (data.friends || data || [])
        .filter((f: any) => f.status === 'accepted')
        .map((f: any) => f.friend || f.user || f);
      setFriends(accepted);
    } catch {
      // ignore
    } finally {
      setLoadingFriends(false);
    }
  }, []);

  const openInviteModal = () => {
    setInviteModalOpen(true);
    setSelectedFriends([]);
    fetchFriends();
  };

  const handleInvite = async () => {
    if (selectedFriends.length === 0) return;
    setInviting(true);
    try {
      await api.post(`/calendar/shared/${viewId}/invite`, { userIds: selectedFriends });
      message.success(`Invited ${selectedFriends.length} friend(s)`);
      setInviteModalOpen(false);
      onRefresh();
    } catch {
      message.error('Failed to invite');
    } finally {
      setInviting(false);
    }
  };

  const statusColor: Record<string, string> = {
    ACCEPTED: 'green',
    INVITED: 'gold',
    DECLINED: 'red',
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <Text strong style={{ fontSize: 14 }}>Members</Text>
        <Button size="small" icon={<UserAddOutlined />} onClick={openInviteModal}>
          Invite
        </Button>
      </div>

      {members.length === 0 ? (
        <Empty description="No members yet" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <List
          size="small"
          dataSource={members}
          renderItem={(member) => (
            <List.Item style={{ padding: '6px 0' }}>
              <Space size={8}>
                <div
                  style={{
                    width: 28,
                    height: 28,
                    borderRadius: '50%',
                    background: member.color,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 12,
                    color: '#fff',
                    flexShrink: 0,
                  }}
                >
                  {(member.user.name || member.user.email)[0]?.toUpperCase()}
                </div>
                <div>
                  <Text style={{ fontSize: 13 }} ellipsis>
                    {member.user.name || member.user.email}
                  </Text>
                  <div>
                    <Tag
                      color={statusColor[member.status] || 'default'}
                      style={{ fontSize: 10, margin: 0 }}
                    >
                      {member.status}
                    </Tag>
                  </div>
                </div>
              </Space>
            </List.Item>
          )}
        />
      )}

      {!isOwner && (
        <Popconfirm
          title="Leave this shared calendar?"
          onConfirm={onLeave}
          okText="Leave"
          okType="danger"
        >
          <Button
            size="small"
            danger
            icon={<LogoutOutlined />}
            style={{ marginTop: 12, width: '100%' }}
          >
            Leave Calendar
          </Button>
        </Popconfirm>
      )}

      <Modal
        title="Invite Friends"
        open={inviteModalOpen}
        onCancel={() => setInviteModalOpen(false)}
        onOk={handleInvite}
        okText="Send Invites"
        confirmLoading={inviting}
        okButtonProps={{ disabled: selectedFriends.length === 0 }}
      >
        {loadingFriends ? (
          <Skeleton active paragraph={{ rows: 3 }} />
        ) : friends.length === 0 ? (
          <Empty description="No friends to invite" />
        ) : (
          <Checkbox.Group
            value={selectedFriends}
            onChange={(vals) => setSelectedFriends(vals as string[])}
            style={{ width: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {friends.map((friend) => {
                const alreadyMember = memberUserIds.has(friend.id);
                return (
                  <Checkbox key={friend.id} value={friend.id} disabled={alreadyMember}>
                    {friend.name || friend.email}
                    {alreadyMember && (
                      <Text type="secondary" style={{ marginLeft: 8, fontSize: 11 }}>
                        (already member)
                      </Text>
                    )}
                  </Checkbox>
                );
              })}
            </Space>
          </Checkbox.Group>
        )}
      </Modal>
    </div>
  );
}
