import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Typography,
  Button,
  Grid,
  Skeleton,
  Empty,
  List,
  Tag,
  Space,
  Tabs,
  Alert,
  theme,
} from 'antd';
import {
  ArrowLeftOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  UserOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import PersonalCalendarView from '@/components/calendar/PersonalCalendarView';
import type {
  PersonalCalendarItem,
  AdminCalendarView,
  AdminCalendarUser,
  AdminCalendarItem,
} from '@/types/api';
import { ROLE_COLORS } from '@/utils/role-constants';

const { Title, Text } = Typography;

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

  const [view, setView] = useState<AdminCalendarView | null>(null);
  const [users, setUsers] = useState<AdminCalendarUser[]>([]);
  const [items, setItems] = useState<AdminCalendarItem[]>([]);
  const [truncated, setTruncated] = useState(false);
  const [totalUsers, setTotalUsers] = useState(0);
  const [loading, setLoading] = useState(true);
  const [currentMonth, setCurrentMonth] = useState<Dayjs>(dayjs());
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  const fetchData = 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 [viewsRes, itemsRes] = await Promise.all([
        api.get<{ views: AdminCalendarView[] }>('/admin/calendar/shared'),
        api.get<{
          items: AdminCalendarItem[];
          users: AdminCalendarUser[];
          totalUsers: number;
          truncated: boolean;
        }>(`/admin/calendar/shared/${id}/items`, { params: { startDate, endDate } }),
      ]);
      const found = viewsRes.data.views.find((v) => v.id === id);
      if (found) setView(found);
      setItems(itemsRes.data.items);
      setUsers(itemsRes.data.users);
      setTotalUsers(itemsRes.data.totalUsers);
      setTruncated(itemsRes.data.truncated);
    } catch {
      navigate('/app/scheduling/calendar');
    } finally {
      setLoading(false);
    }
  }, [id, currentMonth, navigate]);

  useEffect(() => {
    setLoading(true);
    fetchData();
  }, [fetchData]);

  const calendarItems: PersonalCalendarItem[] = items.map((item) => ({
    id: item.id,
    type: item.type as PersonalCalendarItem['type'],
    layerId: item.layerId,
    title: item.title,
    date: item.date,
    startTime: item.startTime,
    endTime: item.endTime,
    isAllDay: false,
    location: item.location,
    color: item.userColor,
    itemType: item.itemType as PersonalCalendarItem['itemType'],
    busyStatus: 'BUSY' as const,
    showDetailsTo: 'EVERYONE' as const,
  }));

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

  const handleItemClick = () => {};

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

  if (!view) return null;

  const usersPanel = (
    <div>
      <Text strong style={{ fontSize: 14, display: 'block', marginBottom: 12 }}>
        <UserOutlined /> Users ({totalUsers})
      </Text>
      {truncated && (
        <Alert
          type="warning"
          message={`Showing ${users.length} of ${totalUsers} users`}
          style={{ marginBottom: 12, fontSize: 12 }}
          showIcon
        />
      )}
      <List
        size="small"
        dataSource={users}
        renderItem={(u) => (
          <List.Item style={{ padding: '6px 0' }}>
            <Space size={8}>
              <div
                style={{
                  width: 10,
                  height: 10,
                  borderRadius: '50%',
                  background: u.color,
                  flexShrink: 0,
                }}
              />
              <Text style={{ fontSize: 13 }} ellipsis>
                {u.name || u.email}
              </Text>
              <Tag color={ROLE_COLORS[u.role] || 'default'} style={{ fontSize: 10, margin: 0 }}>
                {u.role}
              </Tag>
            </Space>
          </List.Item>
        )}
      />
    </div>
  );

  const dateDetailPanel = selectedDate && (
    <div>
      <Text strong style={{ fontSize: 15, display: 'block', marginBottom: 12 }}>
        {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', flexDirection: 'column', alignItems: 'stretch' }}>
              <List.Item.Meta
                avatar={
                  <div
                    style={{
                      width: 4,
                      height: 32,
                      borderRadius: 2,
                      background: item.userColor || item.color,
                      flexShrink: 0,
                    }}
                  />
                }
                title={
                  <Space size={4}>
                    <Text style={{ fontSize: 13 }} ellipsis>{item.title}</Text>
                    <Text type="secondary" style={{ fontSize: 11 }}>
                      ({item.userName})
                    </Text>
                  </Space>
                }
                description={
                  <Space size={4} wrap style={{ fontSize: 11 }}>
                    <Tag icon={<ClockCircleOutlined />} style={{ fontSize: 11, margin: 0 }}>
                      {item.startTime?.slice(0, 5)} - {item.endTime?.slice(0, 5)}
                    </Tag>
                    {item.location && (
                      <Tag icon={<EnvironmentOutlined />} style={{ fontSize: 11, margin: 0 }}>
                        {item.location}
                      </Tag>
                    )}
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      )}
    </div>
  );

  if (isMobile) {
    return (
      <div style={{ padding: 12 }}>
        <Space style={{ marginBottom: 12 }}>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/app/scheduling/calendar')}
          />
          <Title level={5} style={{ margin: 0 }}>{view.name}</Title>
        </Space>
        {view.description && (
          <Text type="secondary" style={{ display: 'block', marginBottom: 12, fontSize: 13 }}>
            {view.description}
          </Text>
        )}
        <Tabs
          defaultActiveKey="calendar"
          items={[
            {
              key: 'calendar',
              label: 'Calendar',
              children: (
                <>
                  <PersonalCalendarView
                    items={calendarItems}
                    currentMonth={currentMonth}
                    selectedDate={selectedDate}
                    onDateSelect={setSelectedDate}
                    onItemClick={handleItemClick}
                    onMonthChange={setCurrentMonth}
                  />
                  {dateDetailPanel}
                </>
              ),
            },
            { key: 'users', label: 'Users', children: usersPanel },
          ]}
        />
      </div>
    );
  }

  return (
    <div style={{ padding: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
        <Space>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/app/scheduling/calendar')}
          />
          <CalendarOutlined style={{ fontSize: 18 }} />
          <Title level={4} style={{ margin: 0 }}>{view.name}</Title>
        </Space>
        {view.description && (
          <Text type="secondary" style={{ marginLeft: 16, fontSize: 13 }}>
            {view.description}
          </Text>
        )}
      </div>

      <div style={{ display: 'flex', gap: 0 }}>
        <div style={{ width: 220, flexShrink: 0, paddingRight: 16 }}>
          {usersPanel}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <PersonalCalendarView
            items={calendarItems}
            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>
  );
}
