import { useState, useRef } from 'react';
import { Typography, Button, Space, Grid } from 'antd';
import { CalendarOutlined, PlusOutlined, LinkOutlined } from '@ant-design/icons';
import { useSettingsStore } from '@/stores/settings.store';
import { useAuthStore } from '@/stores/auth.store';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import UnifiedCalendar from '@/components/calendar/UnifiedCalendar';
import ShiftSignupModal from '@/components/public/ShiftSignupModal';
import type { UnifiedCalendarItem } from '@/types/api';

const { Title, Text } = Typography;

/** Build the Gancio URL from the current hostname */
function getGancioUrl(): string | undefined {
  const domain = import.meta.env.VITE_DOMAIN as string | undefined;
  const hostname = window.location.hostname;
  if (domain && hostname.endsWith(domain)) {
    return `${window.location.protocol}//events.${domain}`;
  }
  return undefined;
}

export default function EventsPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { settings: siteSettings } = useSettingsStore();
  const { user, isAuthenticated } = useAuthStore();
  const eventsAds = usePageAds('events');
  const meetEnabled = siteSettings?.enableMeet ?? false;
  const canCreateMeeting = isAuthenticated && !!user && user.role !== 'TEMP';

  useDocumentTitle(`Calendar | ${siteSettings?.organizationName || 'Changemaker'}`);

  const [signupShift, setSignupShift] = useState<{ id: string; title: string; date: string; startTime: string; endTime: string; location: string | null } | null>(null);
  const [signupOpen, setSignupOpen] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  // Ref to trigger "add event" in the calendar side panel
  const addEventRef = useRef<(() => void) | null>(null);

  const gancioUrl = getGancioUrl();

  const handleShiftSignup = (item: UnifiedCalendarItem) => {
    if (!item.shiftId) return;
    setSignupShift({
      id: item.shiftId,
      title: item.title,
      date: item.date,
      startTime: item.startTime,
      endTime: item.endTime,
      location: item.location,
    });
    setSignupOpen(true);
  };

  return (
    <div>
      {/* Hero */}
      <div
        style={{
          background: 'linear-gradient(135deg, #3498db, #2c3e50)',
          borderRadius: 12,
          padding: isMobile ? '24px 16px' : '36px 24px',
          textAlign: 'center',
          marginBottom: 24,
        }}
      >
        <Title level={2} style={{ color: '#fff', margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.2)' }}>
          <CalendarOutlined style={{ marginRight: 8 }} />
          Community Calendar
        </Title>
        <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 16, display: 'block', marginTop: 8 }}>
          Volunteer shifts and community events in one place
        </Text>
      </div>

      {/* Actions bar */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 8 }}>
        {/* Legend */}
        <Space size={12}>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#1890ff' }} />
            <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>Shifts</Text>
          </Space>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#52c41a' }} />
            <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>Events</Text>
          </Space>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#722ed1' }} />
            <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>Ticketed</Text>
          </Space>
        </Space>

        {/* Submit button — opens side panel with form for tomorrow */}
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => addEventRef.current?.()}
        >
          Submit Event
        </Button>
      </div>

      {/* Calendar */}
      <div key={refreshKey}>
        <UnifiedCalendar
          onShiftSignup={handleShiftSignup}
          gancioUrl={gancioUrl}
          onEventSubmitted={() => setRefreshKey(k => k + 1)}
          onAddEvent={addEventRef}
          canCreateMeeting={canCreateMeeting}
          meetEnabled={meetEnabled}
        />
      </div>

      <AdBanner ads={eventsAds} placement="events" />

      {/* Gancio link footer */}
      {gancioUrl && (
        <div style={{ textAlign: 'center', marginTop: 24, padding: '16px 0' }}>
          <Button
            type="link"
            icon={<LinkOutlined />}
            href={gancioUrl}
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: 'rgba(255,255,255,0.55)' }}
          >
            View full calendar at {gancioUrl.replace(/^https?:\/\//, '')}
          </Button>
        </div>
      )}

      {/* Shift signup modal */}
      <ShiftSignupModal
        shift={signupShift}
        open={signupOpen}
        onClose={() => setSignupOpen(false)}
        onSuccess={() => setRefreshKey(k => k + 1)}
      />
    </div>
  );
}
