import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Typography,
  Button,
  Grid,
  Skeleton,
  Empty,
  List,
  Tag,
  Space,
  Switch,
  Tabs,
  message,
  theme,
} from 'antd';
import {
  ArrowLeftOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import FeatureGate from '@/components/FeatureGate';
import PersonalCalendarView from '@/components/calendar/PersonalCalendarView';
import CalendarTimeGrid from '@/components/calendar/CalendarTimeGrid';
import SharedViewMembersPanel from '@/components/calendar/SharedViewMembersPanel';
import AvailabilityFinder from '@/components/calendar/AvailabilityFinder';
import CalendarComments from '@/components/calendar/CalendarComments';
import CalendarReactions from '@/components/calendar/CalendarReactions';
import type {
  SharedCalendarView,
  SharedCalendarMember,
  SharedCalendarItem,
  SharedViewReactionGroup,
} from '@/types/api';

const { Title, Text } = Typography;

export default function SharedCalendarViewPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();
  const { user } = useAuthStore();
  const currentUserId = user?.id || '';

  const [view, setView] = useState<SharedCalendarView | null>(null);
  const [members, setMembers] = useState<SharedCalendarMember[]>([]);
  const [items, setItems] = useState<SharedCalendarItem[]>([]);
  const [reactions, setReactions] = useState<Record<string, SharedViewReactionGroup[]>>({});
  const [loading, setLoading] = useState(true);
  const [currentMonth, setCurrentMonth] = useState<Dayjs>(dayjs());
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [showAvailability, setShowAvailability] = useState(false);

  const fetchView = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get<SharedCalendarView>(`/calendar/shared/${id}`);
      setView(data);
    } catch {
      message.error('Failed to load shared calendar');
      navigate('/volunteer/calendar/shared');
    }
  }, [id, navigate]);

  const fetchMembers = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get<{ members: SharedCalendarMember[] }>(`/calendar/shared/${id}/members`);
      setMembers(data.members);
    } catch {
      // ignore
    }
  }, [id]);

  const fetchItems = useCallback(async () => {
    if (!id) 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: SharedCalendarItem[] }>(`/calendar/shared/${id}/items`, {
        params: { startDate, endDate },
      });
      setItems(data.items);
    } catch {
      // ignore
    }
  }, [id, currentMonth]);

  const fetchReactions = useCallback(async () => {
    if (!id || !selectedDate) return;
    try {
      const { data } = await api.get<Record<string, SharedViewReactionGroup[]>>(
        `/calendar/shared/${id}/reactions`,
        { params: { date: selectedDate } },
      );
      setReactions(data);
    } catch {
      // ignore
    }
  }, [id, selectedDate]);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      await Promise.all([fetchView(), fetchMembers(), fetchItems()]);
      setLoading(false);
    };
    load();
  }, [fetchView, fetchMembers, fetchItems]);

  useEffect(() => {
    if (selectedDate) fetchReactions();
  }, [fetchReactions, selectedDate]);

  const isOwner = view?.ownerId === currentUserId;

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

  const handleLeave = async () => {
    if (!id) return;
    try {
      await api.delete(`/calendar/shared/${id}/leave`);
      message.success('Left shared calendar');
      navigate('/volunteer/calendar/shared');
    } catch {
      message.error('Failed to leave');
    }
  };

  // Noop for read-only calendar item click
  const handleItemClick = () => {};

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

  if (!view) return null;

  const dateDetailPanel = selectedDate && (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <Text strong style={{ fontSize: 15 }}>
          {dayjs(selectedDate).format('ddd, MMM D')}
        </Text>
      </div>

      {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', flexDirection: 'column', alignItems: 'stretch' }}>
              <List.Item.Meta
                avatar={
                  <div
                    style={{
                      width: 4,
                      height: 32,
                      borderRadius: 2,
                      background: item.memberColor || item.color,
                      flexShrink: 0,
                    }}
                  />
                }
                title={
                  <Space size={4}>
                    <Text style={{ fontSize: 13 }} ellipsis>{item.title}</Text>
                    <Text type="secondary" style={{ fontSize: 11 }}>
                      ({item.memberName})
                    </Text>
                  </Space>
                }
                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>
                }
              />
              <CalendarReactions
                viewId={id!}
                itemId={item.id}
                reactions={reactions[item.id] || []}
                currentUserId={currentUserId}
                onUpdate={fetchReactions}
              />
            </List.Item>
          )}
        />
      )}

      <div style={{ marginTop: 16 }}>
        <CalendarComments
          viewId={id!}
          date={selectedDate}
          currentUserId={currentUserId}
        />
      </div>
    </div>
  );

  const membersPanel = (
    <SharedViewMembersPanel
      viewId={id!}
      members={members}
      isOwner={isOwner}
      onInvite={fetchMembers}
      onLeave={handleLeave}
      onRefresh={fetchMembers}
    />
  );

  const availabilityPanel = (
    <AvailabilityFinder viewId={id!} />
  );

  if (isMobile) {
    return (
      <FeatureGate feature="enableSocialCalendar">
        <div style={{ padding: '12px 0' }}>
          <Space style={{ marginBottom: 12 }}>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/volunteer/calendar/shared')}
            />
            <Title level={5} style={{ margin: 0 }}>{view.name}</Title>
          </Space>

          <Tabs
            defaultActiveKey="calendar"
            items={[
              {
                key: 'calendar',
                label: 'Calendar',
                children: (
                  <>
                    <CalendarTimeGrid
                      items={items}
                      viewMode="day"
                      currentDate={currentMonth}
                      onDateSelect={setSelectedDate}
                      onItemClick={handleItemClick}
                      onNavigate={(dir) => setCurrentMonth((d) => d.add(dir === 'next' ? 1 : -1, 'day'))}
                    />
                    {dateDetailPanel}
                  </>
                ),
              },
              { key: 'members', label: 'Members', children: membersPanel },
              { key: 'availability', label: 'Availability', children: availabilityPanel },
            ]}
          />
        </div>
      </FeatureGate>
    );
  }

  return (
    <FeatureGate feature="enableSocialCalendar">
      <div style={{ padding: '12px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <Space>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/volunteer/calendar/shared')}
            />
            <CalendarOutlined style={{ fontSize: 18 }} />
            <Title level={4} style={{ margin: 0 }}>{view.name}</Title>
          </Space>
          <Space>
            <Text style={{ fontSize: 12 }}>Availability</Text>
            <Switch
              size="small"
              checked={showAvailability}
              onChange={setShowAvailability}
            />
          </Space>
        </div>

        {showAvailability ? (
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 260, flexShrink: 0 }}>
              {membersPanel}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              {availabilityPanel}
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 0 }}>
            <div style={{ width: 260, flexShrink: 0, paddingRight: 16 }}>
              {membersPanel}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <PersonalCalendarView
                items={items}
                currentMonth={currentMonth}
                selectedDate={selectedDate}
                onDateSelect={setSelectedDate}
                onItemClick={handleItemClick}
                onMonthChange={setCurrentMonth}
              />
            </div>
            {selectedDate && (
              <div
                style={{
                  width: 280,
                  flexShrink: 0,
                  padding: '0 0 0 16px',
                  borderLeft: `1px solid ${token.colorBorderSecondary}`,
                }}
              >
                {dateDetailPanel}
              </div>
            )}
          </div>
        )}
      </div>
    </FeatureGate>
  );
}
