import { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Button,
  Row,
  Col,
  Progress,
  Tag,
  message,
  Spin,
  Result,
  Pagination,
  Grid,
  theme,
} from 'antd';
import {
  ScheduleOutlined,
  ClockCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  VideoCameraOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import { useSettingsStore } from '@/stores/settings.store';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import { isAlmostFull, isNew } from '@/utils/badges';
import RelatedContent from '@/components/public/RelatedContent';
import ShiftSignupModal from '@/components/public/ShiftSignupModal';
import FriendsAttendingBadge from '@/components/social/FriendsAttendingBadge';

const { Title, Text, Paragraph } = Typography;

const apiBase = '/api';

interface PublicShift {
  id: string;
  title: string;
  description: string | null;
  date: string;
  startTime: string;
  endTime: string;
  location: string | null;
  maxVolunteers: number;
  currentVolunteers: number;
  status: 'OPEN' | 'FULL' | 'CANCELLED';
  meeting?: { id: string; slug: string; isActive: boolean } | null;
}

export default function PublicShiftsPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();
  const { settings: siteSettings } = useSettingsStore();
  const shiftsAds = usePageAds('shifts');

  const [shifts, setShifts] = useState<PublicShift[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [signupModalOpen, setSignupModalOpen] = useState(false);
  const [selectedShift, setSelectedShift] = useState<PublicShift | null>(null);
  const [relatedCampaigns, setRelatedCampaigns] = useState<any[]>([]);

  useEffect(() => {
    document.title = `Volunteer Shifts | ${siteSettings?.organizationName || 'Changemaker'}`;
  }, [siteSettings?.organizationName]);

  // Fetch related campaigns
  useEffect(() => {
    axios.get(`${apiBase}/map/shifts/public/related`)
      .then(({ data }) => setRelatedCampaigns(data.campaigns || []))
      .catch(() => {});
  }, []);

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

  const fetchShifts = async () => {
    setLoading(true);
    try {
      const { data } = await axios.get(`${apiBase}/map/shifts/public`, { params: { page, limit: 20 } });
      setShifts(data.shifts);
      setTotal(data.pagination.total);
    } catch {
      message.error('Failed to load volunteer opportunities');
    } finally {
      setLoading(false);
    }
  };

  const openSignup = (shift: PublicShift) => {
    setSelectedShift(shift);
    setSignupModalOpen(true);
  };

  return (
    <div>
      {/* Hero */}
      <div
        style={{
          background: 'linear-gradient(135deg, #3498db, #2c3e50)',
          borderRadius: 12,
          padding: isMobile ? '32px 16px' : '48px 24px',
          textAlign: 'center',
          marginBottom: 32,
        }}
      >
        <Title level={2} style={{ color: '#fff', margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.2)' }}>
          Volunteer Opportunities
        </Title>
        <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 16 }}>
          Sign up for upcoming shifts and make a difference
        </Text>
      </div>

      <AdBanner ads={shiftsAds} placement="shifts" />

      {/* Content */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: 60 }}>
          <Spin size="large" />
        </div>
      ) : shifts.length === 0 ? (
        <Result
          status="info"
          title="No Upcoming Shifts"
          subTitle="Check back later for volunteer opportunities."
        />
      ) : (
        <Row gutter={[16, 16]}>
          {shifts.map((shift) => {
            const isCancelled = shift.status === 'CANCELLED';
            const spotsLeft = shift.maxVolunteers - shift.currentVolunteers;
            const isFull = !isCancelled && (shift.status === 'FULL' || spotsLeft <= 0);
            const pct = shift.maxVolunteers > 0
              ? Math.round((shift.currentVolunteers / shift.maxVolunteers) * 100)
              : 0;

            return (
              <Col key={shift.id} xs={24} sm={12} lg={8}>
                <Card
                  hoverable={!isFull && !isCancelled}
                  style={{
                    height: '100%',
                    opacity: isFull || isCancelled ? 0.7 : 1,
                  }}
                  styles={{
                    body: {
                      display: 'flex',
                      flexDirection: 'column',
                      height: '100%',
                    },
                  }}
                >
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8, marginBottom: 8 }}>
                      <Title level={5} style={{ margin: 0 }}>
                        {shift.title}
                      </Title>
                      <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                        {isAlmostFull(shift) && !isFull && <Tag color="orange" style={{ margin: 0, fontSize: 11 }}>Almost Full</Tag>}
                        {isNew(shift.date) && <Tag color="cyan" style={{ margin: 0, fontSize: 11 }}>New</Tag>}
                      </div>
                    </div>

                    <div style={{ marginBottom: 12 }}>
                      <div style={{ marginBottom: 4 }}>
                        <ScheduleOutlined style={{ marginRight: 8, color: token.colorPrimary }} />
                        <Text>{dayjs(shift.date).format('dddd, MMMM D, YYYY')}</Text>
                      </div>
                      <div style={{ marginBottom: 4 }}>
                        <ClockCircleOutlined style={{ marginRight: 8, color: token.colorPrimary }} />
                        <Text>{shift.startTime} — {shift.endTime}</Text>
                      </div>
                      {shift.location && (
                        <div style={{ marginBottom: 4 }}>
                          <EnvironmentOutlined style={{ marginRight: 8, color: token.colorPrimary }} />
                          <Text>{shift.location}</Text>
                        </div>
                      )}
                    </div>

                    {shift.description && (
                      <Paragraph
                        type="secondary"
                        ellipsis={{ rows: 2 }}
                        style={{ marginBottom: 12 }}
                      >
                        {shift.description}
                      </Paragraph>
                    )}

                    <div style={{ marginBottom: 12 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                        <Text type="secondary">
                          <TeamOutlined style={{ marginRight: 4 }} />
                          Volunteers
                        </Text>
                        <Text type="secondary">{shift.currentVolunteers}/{shift.maxVolunteers}</Text>
                      </div>
                      <Progress
                        percent={pct}
                        size="small"
                        status={isFull ? 'exception' : 'active'}
                        showInfo={false}
                      />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {isFull ? 'No spots available' : `${spotsLeft} spot${spotsLeft !== 1 ? 's' : ''} remaining`}
                      </Text>
                      <FriendsAttendingBadge shiftId={shift.id} />
                    </div>
                  </div>

                  {shift.meeting?.isActive && (
                    <Button
                      type="default"
                      block
                      icon={<VideoCameraOutlined />}
                      href={`/meet/${shift.meeting.slug}`}
                      target="_blank"
                      style={{ marginBottom: 8 }}
                    >
                      Join Video Briefing
                    </Button>
                  )}
                  <Button
                    type="primary"
                    block
                    size="large"
                    disabled={isFull || isCancelled}
                    onClick={() => openSignup(shift)}
                  >
                    {isCancelled ? 'Cancelled' : isFull ? 'Shift Full' : 'Sign Up'}
                  </Button>
                </Card>
              </Col>
            );
          })}
        </Row>
      )}

      {total > 20 && (
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <Pagination
            current={page}
            total={total}
            pageSize={20}
            onChange={(p) => { setPage(p); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            showSizeChanger={false}
          />
        </div>
      )}

      {/* Related Campaigns */}
      <RelatedContent campaigns={relatedCampaigns} />

      {/* Signup Modal (shared component) */}
      <ShiftSignupModal
        shift={selectedShift}
        open={signupModalOpen}
        onClose={() => setSignupModalOpen(false)}
        onSuccess={fetchShifts}
      />
    </div>
  );
}
