import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Typography,
  Button,
  Grid,
  Skeleton,
  Empty,
  List,
  Tag,
  Space,
  message,
  theme,
} from 'antd';
import {
  ArrowLeftOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import FeatureGate from '@/components/FeatureGate';
import PersonalCalendarView from '@/components/calendar/PersonalCalendarView';
import CalendarTimeGrid from '@/components/calendar/CalendarTimeGrid';
import type { PersonalCalendarItem } from '@/types/api';
import axios from 'axios';

const { Title, Text } = Typography;

export default function FriendCalendarPage() {
  const { userId } = useParams<{ userId: string }>();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();

  const [friendName, setFriendName] = useState<string>('');
  const [items, setItems] = useState<PersonalCalendarItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentMonth, setCurrentMonth] = useState<Dayjs>(dayjs());
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  const fetchItems = useCallback(async () => {
    if (!userId) return;
    const startDate = currentMonth.startOf('month').subtract(7, 'day').format('YYYY-MM-DD');
    const endDate = currentMonth.endOf('month').add(7, 'day').format('YYYY-MM-DD');
    try {
      const { data } = await api.get<{ items: PersonalCalendarItem[] }>(
        `/calendar/shared/user/${userId}`,
        { params: { startDate, endDate } },
      );
      setItems(data.items);
    } catch (err: unknown) {
      if (axios.isAxiosError(err) && err.response?.status === 403) {
        message.error('This user has not shared their calendar');
      }
    } finally {
      setLoading(false);
    }
  }, [userId, currentMonth]);

  const fetchFriendName = useCallback(async () => {
    if (!userId) return;
    try {
      const { data } = await api.get(`/social/profile/${userId}`);
      setFriendName(data.user?.name || data.user?.email || 'Friend');
    } catch {
      setFriendName('Friend');
    }
  }, [userId]);

  useEffect(() => {
    setLoading(true);
    Promise.all([fetchItems(), fetchFriendName()]).then(() => setLoading(false));
  }, [fetchItems, fetchFriendName]);

  const selectedDateItems = selectedDate
    ? items.filter((item) => item.date === selectedDate)
    : [];

  const handleItemClick = () => {};

  if (loading) {
    return (
      <div style={{ padding: '12px 0' }}>
        <Skeleton active paragraph={{ rows: 10 }} />
      </div>
    );
  }

  const dateDetailPanel = selectedDate && (
    <div
      style={{
        width: isMobile ? '100%' : 280,
        flexShrink: 0,
        padding: isMobile ? '12px 0' : '0 0 0 16px',
        borderLeft: isMobile ? undefined : `1px solid ${token.colorBorderSecondary}`,
      }}
    >
      <Text strong style={{ fontSize: 15, marginBottom: 12, display: 'block' }}>
        {dayjs(selectedDate).format('ddd, MMM D')}
      </Text>

      {selectedDateItems.length === 0 ? (
        <Empty description="No events" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <List
          size="small"
          dataSource={selectedDateItems}
          renderItem={(item) => (
            <List.Item style={{ padding: '8px 0' }}>
              <List.Item.Meta
                avatar={
                  <div
                    style={{
                      width: 4,
                      height: 32,
                      borderRadius: 2,
                      background: item.color,
                      flexShrink: 0,
                    }}
                  />
                }
                title={
                  <Text style={{ fontSize: 13 }} ellipsis>{item.title}</Text>
                }
                description={
                  <Space size={4} wrap style={{ fontSize: 11 }}>
                    {!item.isAllDay && (
                      <Tag icon={<ClockCircleOutlined />} style={{ fontSize: 11, margin: 0 }}>
                        {item.startTime?.slice(0, 5)} - {item.endTime?.slice(0, 5)}
                      </Tag>
                    )}
                    {item.isAllDay && <Tag style={{ fontSize: 11, margin: 0 }}>All day</Tag>}
                    {item.location && (
                      <Tag icon={<EnvironmentOutlined />} style={{ fontSize: 11, margin: 0 }}>
                        {item.location}
                      </Tag>
                    )}
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      )}
    </div>
  );

  return (
    <FeatureGate feature="enableSocialCalendar">
      <div style={{ padding: '12px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(-1)}
          />
          <CalendarOutlined style={{ fontSize: 18, marginRight: 8 }} />
          <Title level={4} style={{ margin: 0 }}>
            {friendName}&apos;s Calendar
          </Title>
        </div>

        {isMobile ? (
          <div>
            <CalendarTimeGrid
              items={items}
              viewMode="day"
              currentDate={currentMonth}
              onDateSelect={setSelectedDate}
              onItemClick={handleItemClick}
              onNavigate={(dir) => setCurrentMonth((d) => d.add(dir === 'next' ? 1 : -1, 'day'))}
            />
            {dateDetailPanel}
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 0 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <PersonalCalendarView
                items={items}
                currentMonth={currentMonth}
                selectedDate={selectedDate}
                onDateSelect={setSelectedDate}
                onItemClick={handleItemClick}
                onMonthChange={setCurrentMonth}
              />
            </div>
            {dateDetailPanel}
          </div>
        )}
      </div>
    </FeatureGate>
  );
}
