import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Tabs, List, Button, Typography, Empty, Skeleton, Input, message, Pagination } from 'antd';
import { CheckOutlined, CloseOutlined, UserDeleteOutlined, SearchOutlined, TeamOutlined } from '@ant-design/icons';
import { useSocialStore } from '@/stores/social.store';
import UserAvatar from '@/components/social/UserAvatar';
import GroupCard from '@/components/social/GroupCard';
import { api } from '@/lib/api';
import type { BlockedUser, SocialGroupSummary } from '@/types/social';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

export default function FriendsPage() {
  const navigate = useNavigate();
  const {
    friends, friendsPagination, pendingReceived, pendingSent,
    loadingFriends,
    fetchFriends, fetchPendingReceived, fetchPendingSent,
    acceptRequest, declineRequest, cancelRequest, unfriend,
  } = useSocialStore();
  const [blocked, setBlocked] = useState<BlockedUser[]>([]);
  const [groups, setGroups] = useState<SocialGroupSummary[]>([]);
  const [groupsLoading, setGroupsLoading] = useState(false);
  const [friendsPage, setFriendsPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    fetchFriends(1);
    fetchPendingReceived();
    fetchPendingSent();
    loadBlocked();
    loadGroups();
  }, []);

  const loadBlocked = async () => {
    try {
      const { data } = await api.get('/social/blocks');
      setBlocked(data.blocked);
    } catch {}
  };

  const loadGroups = async () => {
    setGroupsLoading(true);
    try {
      const { data } = await api.get('/social/groups', { params: { limit: 50 } });
      setGroups(data.groups);
    } catch {}
    setGroupsLoading(false);
  };

  const handleFriendsPageChange = (page: number) => {
    setFriendsPage(page);
    fetchFriends(page);
  };

  const handleUnblock = async (userId: string) => {
    try {
      await api.delete(`/social/blocks/${userId}`);
      message.success('User unblocked');
      loadBlocked();
    } catch {
      message.error('Failed to unblock');
    }
  };

  const filteredFriends = searchTerm
    ? friends.filter((f) => {
        const name = (f.user.name || '').toLowerCase();
        const email = f.user.email.toLowerCase();
        const term = searchTerm.toLowerCase();
        return name.includes(term) || email.includes(term);
      })
    : friends;

  return (
    <div style={{ padding: '12px 0' }}>
      <Typography.Title level={4} style={{ margin: '0 0 12px 0' }}>Friends</Typography.Title>

      <Tabs
        defaultActiveKey="friends"
        items={[
          {
            key: 'friends',
            label: `Friends (${friendsPagination?.total ?? 0})`,
            children: (
              <>
                <Input
                  prefix={<SearchOutlined />}
                  placeholder="Search friends..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  style={{ marginBottom: 12 }}
                  allowClear
                />
                {loadingFriends ? (
                  <Skeleton active paragraph={{ rows: 4 }} />
                ) : filteredFriends.length === 0 ? (
                  <Empty description={searchTerm ? 'No matching friends' : 'No friends yet'} />
                ) : (
                  <>
                    <List
                      dataSource={filteredFriends}
                      renderItem={(f) => (
                        <List.Item
                          actions={[
                            <Button
                              key="unfriend"
                              type="text"
                              danger
                              size="small"
                              icon={<UserDeleteOutlined />}
                              onClick={() => unfriend(f.user.id).then(() => message.success('Unfriended'))}
                            />,
                          ]}
                          style={{ cursor: 'pointer' }}
                          onClick={() => navigate(`/volunteer/profile/${f.user.id}`)}
                        >
                          <List.Item.Meta
                            avatar={<UserAvatar userId={f.user.id} name={f.user.name} email={f.user.email} size={36} showOnline />}
                            title={f.user.name || f.user.email}
                            description={`Friends since ${dayjs(f.acceptedAt).fromNow()}`}
                          />
                        </List.Item>
                      )}
                    />
                    {friendsPagination && friendsPagination.totalPages > 1 && (
                      <Pagination
                        current={friendsPage}
                        total={friendsPagination.total}
                        pageSize={20}
                        onChange={handleFriendsPageChange}
                        size="small"
                        style={{ textAlign: 'center', marginTop: 8 }}
                        showSizeChanger={false}
                      />
                    )}
                  </>
                )}
              </>
            ),
          },
          {
            key: 'received',
            label: `Requests (${pendingReceived.length})`,
            children: pendingReceived.length === 0 ? (
              <Empty description="No pending requests" />
            ) : (
              <List
                dataSource={pendingReceived}
                renderItem={(r) => (
                  <List.Item
                    actions={[
                      <Button
                        key="accept"
                        type="primary"
                        size="small"
                        icon={<CheckOutlined />}
                        onClick={() => acceptRequest(r.friendshipId).then(() => message.success('Accepted'))}
                      >
                        Accept
                      </Button>,
                      <Button
                        key="decline"
                        size="small"
                        icon={<CloseOutlined />}
                        onClick={() => declineRequest(r.friendshipId).then(() => message.success('Declined'))}
                      />,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<UserAvatar userId={r.from.id} name={r.from.name} email={r.from.email} size={36} />}
                      title={r.from.name || r.from.email}
                      description={dayjs(r.createdAt).fromNow()}
                    />
                  </List.Item>
                )}
              />
            ),
          },
          {
            key: 'sent',
            label: `Sent (${pendingSent.length})`,
            children: pendingSent.length === 0 ? (
              <Empty description="No sent requests" />
            ) : (
              <List
                dataSource={pendingSent}
                renderItem={(r) => (
                  <List.Item
                    actions={[
                      <Button
                        key="cancel"
                        size="small"
                        icon={<CloseOutlined />}
                        onClick={() => cancelRequest(r.friendshipId).then(() => message.success('Cancelled'))}
                      >
                        Cancel
                      </Button>,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<UserAvatar userId={r.to.id} name={r.to.name} email={r.to.email} size={36} />}
                      title={r.to.name || r.to.email}
                      description={`Sent ${dayjs(r.createdAt).fromNow()}`}
                    />
                  </List.Item>
                )}
              />
            ),
          },
          {
            key: 'blocked',
            label: `Blocked (${blocked.length})`,
            children: blocked.length === 0 ? (
              <Empty description="No blocked users" />
            ) : (
              <List
                dataSource={blocked}
                renderItem={(b) => (
                  <List.Item
                    actions={[
                      <Button
                        key="unblock"
                        size="small"
                        onClick={() => handleUnblock(b.user.id)}
                      >
                        Unblock
                      </Button>,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<UserAvatar userId={b.user.id} name={b.user.name} email={b.user.email} size={36} />}
                      title={b.user.name || b.user.email}
                      description={`Blocked ${dayjs(b.blockedAt).fromNow()}`}
                    />
                  </List.Item>
                )}
              />
            ),
          },
          {
            key: 'groups',
            label: <><TeamOutlined /> Groups ({groups.length})</>,
            children: groupsLoading ? (
              <Skeleton active paragraph={{ rows: 3 }} />
            ) : groups.length === 0 ? (
              <Empty description="No groups yet — groups are created when you share shifts or campaigns with others" />
            ) : (
              <div>
                {groups.map((g) => (
                  <GroupCard key={g.id} group={g} />
                ))}
              </div>
            ),
          },
        ]}
      />
    </div>
  );
}
