import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Typography, List, Tag, Skeleton, Alert, Space, Button, App } from 'antd';
import { ScheduleOutlined, SendOutlined, TeamOutlined, VideoCameraOutlined, PhoneOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import UserAvatar from '@/components/social/UserAvatar';
import FriendButton from '@/components/social/FriendButton';
import type { SocialGroupDetail } from '@/types/social';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import dayjs from 'dayjs';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Title, Text } = Typography;

const TYPE_CONFIG: Record<string, { color: string; label: string; icon: React.ReactNode }> = {
  SHIFT_TEAM: { color: 'green', label: 'Shift Team', icon: <ScheduleOutlined /> },
  CAMPAIGN_TEAM: { color: 'blue', label: 'Campaign Team', icon: <SendOutlined /> },
  CUSTOM: { color: 'purple', label: 'Group', icon: <TeamOutlined /> },
};

export default function GroupDetailPage() {
  const { id } = useParams<{ id: string }>();
  const { message, modal } = App.useApp();
  const { user: currentUser } = useAuthStore();
  const { settings } = useSettingsStore();
  const [group, setGroup] = useState<SocialGroupDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [callLoading, setCallLoading] = useState(false);

  const showCallButtons = settings?.enableMeet && settings?.enableSocial;
  const hasActiveCall = group?.meeting?.isActive === true;

  const fetchGroup = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data } = await api.get<SocialGroupDetail>(`/social/groups/${id}`);
      setGroup(data);
    } catch (err: unknown) {
      setError(getErrorMessage(err, 'Failed to load group'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) fetchGroup();
  }, [id]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleStartCall = async () => {
    setCallLoading(true);
    try {
      await api.post(`/social/groups/${id}/call/start`);
      // Get token and open Jitsi
      const { data } = await api.post<{ token: string; room: string; slug: string }>(`/social/groups/${id}/call/token`);
      window.open(`/meet/${data.slug}`, '_blank');
      fetchGroup();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to start call'));
    } finally {
      setCallLoading(false);
    }
  };

  const handleJoinCall = async () => {
    setCallLoading(true);
    try {
      const { data } = await api.post<{ token: string; room: string; slug: string }>(`/social/groups/${id}/call/token`);
      window.open(`/meet/${data.slug}`, '_blank');
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to join call'));
    } finally {
      setCallLoading(false);
    }
  };

  const handleEndCall = () => {
    modal.confirm({
      title: 'End Group Call',
      content: 'This will end the call for everyone. Continue?',
      okText: 'End Call',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await api.post(`/social/groups/${id}/call/end`);
          message.success('Call ended');
          fetchGroup();
        } catch (err: unknown) {
          message.error(getErrorMessage(err, 'Failed to end call'));
        }
      },
    });
  };

  if (loading) return <Skeleton active paragraph={{ rows: 8 }} />;
  if (error) return <Alert message="Error" description={error} type="error" showIcon />;
  if (!group) return null;

  const config = TYPE_CONFIG[group.type] ?? TYPE_CONFIG['CUSTOM']!;

  return (
    <div style={{ padding: '12px 0' }}>
      <Card>
        <Space direction="vertical" align="center" style={{ width: '100%', textAlign: 'center' }}>
          <Title level={4} style={{ margin: 0 }}>{group.name}</Title>
          <Tag color={config.color} icon={config.icon}>{config.label}</Tag>
          <Text type="secondary">
            {group.memberCount} member{group.memberCount !== 1 ? 's' : ''}
            {' · '}Created {dayjs(group.createdAt).format('MMM D, YYYY')}
          </Text>
          {showCallButtons && (
            <Space style={{ marginTop: 8 }}>
              {hasActiveCall ? (
                <>
                  <Button
                    type="primary"
                    icon={<VideoCameraOutlined />}
                    loading={callLoading}
                    onClick={handleJoinCall}
                  >
                    Join Call
                  </Button>
                  <Button
                    danger
                    icon={<PhoneOutlined />}
                    onClick={handleEndCall}
                  >
                    End Call
                  </Button>
                </>
              ) : (
                <Button
                  type="primary"
                  ghost
                  icon={<VideoCameraOutlined />}
                  loading={callLoading}
                  onClick={handleStartCall}
                >
                  Start Group Call
                </Button>
              )}
            </Space>
          )}
        </Space>
      </Card>

      <Card title="Members" style={{ marginTop: 12 }}>
        <List
          dataSource={group.members}
          renderItem={(member) => {
            const isMe = member.userId === currentUser?.id;
            return (
              <List.Item
                extra={
                  !isMe ? (
                    <FriendButton
                      userId={member.userId}
                      onStatusChange={fetchGroup}
                      size="small"
                    />
                  ) : (
                    <Tag>You</Tag>
                  )
                }
              >
                <List.Item.Meta
                  avatar={
                    <UserAvatar
                      userId={member.userId}
                      name={member.user.name}
                      email={member.user.email}
                      size={36}
                    />
                  }
                  title={member.user.name || member.user.email}
                  description={`Joined ${dayjs(member.joinedAt).format('MMM D')}`}
                />
              </List.Item>
            );
          }}
        />
      </Card>
    </div>
  );
}
