import { useState, useEffect } from 'react';
import { Typography, Card, Tag, Space, Spin, Button, Grid, Statistic, Row, Col, theme } from 'antd';
import {
  SendOutlined,
  CalendarOutlined,
  ScheduleOutlined,
  PlayCircleOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  MailOutlined,
  ClockCircleOutlined,
  RocketOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import axios from 'axios';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useSettingsStore } from '@/stores/settings.store';
import HomepageSection from '@/components/public/HomepageSection';
import ActivityFeed from '@/components/public/ActivityFeed';

dayjs.extend(relativeTime);

const { Title, Text, Paragraph } = Typography;

interface HomepageData {
  featuredCampaigns: Array<{
    id: string;
    slug: string;
    title: string;
    description: string | null;
    emailCount: number;
    highlightCampaign: boolean;
  }>;
  upcomingShifts: Array<{
    id: string;
    title: string;
    startTime: string;
    endTime: string;
    location: string | null;
    currentVolunteers: number;
    maxVolunteers: number | null;
  }>;
  latestMedia: Array<{
    id: number;
    title: string | null;
    thumbnailPath: string | null;
    durationSeconds: number | null;
  }>;
  upcomingEvents: Array<{
    id: number;
    title: string;
    placeName: string;
    startDatetime: string;
    tags: string[];
  }>;
  stats: {
    totalEmailsSent: number;
    activeCampaigns: number;
    totalShiftSignups: number;
  };
  enabledModules: {
    influence: boolean;
    map: boolean;
    media: boolean;
    events: boolean;
    payments: boolean;
    landingPages: boolean;
  };
}

function formatDuration(seconds: number | null): string {
  if (!seconds) return '';
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, '0')}`;
}

export default function HomePage() {
  const { settings } = useSettingsStore();
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [data, setData] = useState<HomepageData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get<HomepageData>('/api/homepage')
      .then(({ data }) => setData(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!data) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Text style={{ color: 'rgba(255,255,255,0.5)' }}>Failed to load homepage data</Text>
      </div>
    );
  }

  const orgName = settings?.organizationName ?? 'Changemaker Lite';
  const tagline = (settings as any)?.homepageTagline ?? 'Take action. Make a difference.';
  const logoUrl = settings?.organizationLogoUrl;

  return (
    <div>
      {/* Hero Banner */}
      <div
        style={{
          textAlign: 'center',
          padding: isMobile ? '40px 16px' : '60px 24px',
          marginBottom: 40,
          borderRadius: 12,
          background: 'linear-gradient(135deg, rgba(0,90,156,0.3) 0%, rgba(0,122,204,0.15) 100%)',
          border: '1px solid rgba(255,255,255,0.08)',
        }}
      >
        {logoUrl && (
          <img
            src={logoUrl}
            alt={orgName}
            style={{ maxHeight: 64, marginBottom: 16, objectFit: 'contain' }}
          />
        )}
        <Title level={2} style={{ color: '#fff', margin: 0 }}>{orgName}</Title>
        <Paragraph style={{ color: 'rgba(255,255,255,0.65)', fontSize: 16, marginTop: 8, marginBottom: 24 }}>
          {tagline}
        </Paragraph>
        <Space size={12} wrap>
          {data.enabledModules.influence && (
            <Link to="/campaigns">
              <Button type="primary" size="large" icon={<SendOutlined />}>Browse Campaigns</Button>
            </Link>
          )}
          <Link to="/volunteer">
            <Button size="large" icon={<ScheduleOutlined />}>Volunteer</Button>
          </Link>
        </Space>
      </div>

      {/* Stats */}
      {(data.stats.totalEmailsSent > 0 || data.stats.activeCampaigns > 0 || data.stats.totalShiftSignups > 0) && (
        <Row gutter={[16, 16]} style={{ marginBottom: 40 }}>
          {data.stats.activeCampaigns > 0 && (
            <Col xs={24} sm={8}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title={<span style={{ color: 'rgba(255,255,255,0.55)' }}>Active Campaigns</span>}
                  value={data.stats.activeCampaigns}
                  prefix={<RocketOutlined style={{ color: token.colorPrimary }} />}
                  valueStyle={{ color: '#fff' }}
                />
              </Card>
            </Col>
          )}
          {data.stats.totalEmailsSent > 0 && (
            <Col xs={24} sm={8}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title={<span style={{ color: 'rgba(255,255,255,0.55)' }}>Emails Sent</span>}
                  value={data.stats.totalEmailsSent}
                  prefix={<MailOutlined style={{ color: '#3498db' }} />}
                  valueStyle={{ color: '#fff' }}
                />
              </Card>
            </Col>
          )}
          {data.stats.totalShiftSignups > 0 && (
            <Col xs={24} sm={8}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title={<span style={{ color: 'rgba(255,255,255,0.55)' }}>Volunteer Signups</span>}
                  value={data.stats.totalShiftSignups}
                  prefix={<TeamOutlined style={{ color: '#27ae60' }} />}
                  valueStyle={{ color: '#fff' }}
                />
              </Card>
            </Col>
          )}
        </Row>
      )}

      {/* Featured Campaigns */}
      {data.featuredCampaigns.length > 0 && (
        <HomepageSection title="Featured Campaigns" viewAllLink="/campaigns">
          <Row gutter={[16, 16]}>
            {data.featuredCampaigns.map(c => (
              <Col xs={24} sm={8} key={c.id}>
                <Link to={`/campaign/${c.slug}`} style={{ textDecoration: 'none' }}>
                  <Card
                    hoverable
                    size="small"
                    style={{ height: '100%' }}
                  >
                    <Text strong style={{ color: '#fff', display: 'block', fontSize: 15 }}>{c.title}</Text>
                    {c.description && (
                      <Paragraph
                        style={{ color: 'rgba(255,255,255,0.55)', fontSize: 13, marginTop: 8, marginBottom: 8 }}
                        ellipsis={{ rows: 2 }}
                      >
                        {c.description}
                      </Paragraph>
                    )}
                    <Space size={8}>
                      <Tag icon={<MailOutlined />} color="blue">{c.emailCount} emails</Tag>
                      {c.highlightCampaign && <Tag color="volcano">Featured</Tag>}
                    </Space>
                  </Card>
                </Link>
              </Col>
            ))}
          </Row>
        </HomepageSection>
      )}

      {/* Upcoming Shifts */}
      {data.upcomingShifts.length > 0 && (
        <HomepageSection title="Upcoming Shifts" viewAllLink="/shifts" viewAllLabel="All shifts">
          <Row gutter={[16, 16]}>
            {data.upcomingShifts.map(s => {
              const start = dayjs(s.startTime);
              const spotsLeft = s.maxVolunteers ? s.maxVolunteers - s.currentVolunteers : null;
              return (
                <Col xs={24} sm={8} key={s.id}>
                  <Card size="small" style={{ height: '100%' }}>
                    <Text strong style={{ color: '#fff', display: 'block' }}>{s.title}</Text>
                    <Space direction="vertical" size={4} style={{ marginTop: 8 }}>
                      <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>
                        <ScheduleOutlined style={{ marginRight: 4 }} />
                        {start.format('ddd, MMM D')} at {start.format('h:mm A')}
                      </Text>
                      {s.location && (
                        <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>
                          <EnvironmentOutlined style={{ marginRight: 4 }} />
                          {s.location}
                        </Text>
                      )}
                      <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>
                        <TeamOutlined style={{ marginRight: 4 }} />
                        {s.currentVolunteers} signed up
                        {spotsLeft !== null && spotsLeft > 0 && ` (${spotsLeft} spots left)`}
                      </Text>
                    </Space>
                  </Card>
                </Col>
              );
            })}
          </Row>
        </HomepageSection>
      )}

      {/* Latest Gallery */}
      {data.latestMedia.length > 0 && (
        <HomepageSection title="Latest Videos" viewAllLink="/gallery">
          <div style={{ display: 'flex', gap: 16, overflowX: 'auto', paddingBottom: 8 }}>
            {data.latestMedia.map(v => (
              <Link key={v.id} to={`/gallery/watch/${v.id}`} style={{ textDecoration: 'none', flexShrink: 0 }}>
                <div style={{ width: isMobile ? 200 : 220, borderRadius: 8, overflow: 'hidden', background: 'rgba(255,255,255,0.05)' }}>
                  {v.thumbnailPath ? (
                    <img
                      src={`/media/public/${v.id}/thumbnail`}
                      alt={v.title ?? 'Video'}
                      style={{ width: '100%', height: 124, objectFit: 'cover' }}
                    />
                  ) : (
                    <div style={{ width: '100%', height: 124, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(155,89,182,0.15)' }}>
                      <PlayCircleOutlined style={{ fontSize: 32, color: 'rgba(255,255,255,0.3)' }} />
                    </div>
                  )}
                  <div style={{ padding: '8px 10px' }}>
                    <Text
                      style={{ color: '#fff', fontSize: 13, display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
                    >
                      {v.title ?? 'Untitled'}
                    </Text>
                    {v.durationSeconds && (
                      <Text style={{ color: 'rgba(255,255,255,0.45)', fontSize: 11 }}>
                        <ClockCircleOutlined style={{ marginRight: 4 }} />{formatDuration(v.durationSeconds)}
                      </Text>
                    )}
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </HomepageSection>
      )}

      {/* Upcoming Events */}
      {data.upcomingEvents.length > 0 && (
        <HomepageSection title="Upcoming Events" viewAllLink="/events">
          <Row gutter={[16, 16]}>
            {data.upcomingEvents.map(e => {
              const start = dayjs(e.startDatetime);
              return (
                <Col xs={24} sm={8} key={e.id}>
                  <Card size="small" style={{ height: '100%' }}>
                    <Text strong style={{ color: '#fff', display: 'block' }}>{e.title}</Text>
                    <Space direction="vertical" size={4} style={{ marginTop: 8 }}>
                      <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>
                        <CalendarOutlined style={{ marginRight: 4 }} />
                        {start.format('ddd, MMM D')} at {start.format('h:mm A')}
                      </Text>
                      {e.placeName && (
                        <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>
                          <EnvironmentOutlined style={{ marginRight: 4 }} />
                          {e.placeName}
                        </Text>
                      )}
                      {e.tags.length > 0 && (
                        <Space size={4} wrap>
                          {e.tags.map(t => <Tag key={t} style={{ margin: 0 }}>{t}</Tag>)}
                        </Space>
                      )}
                    </Space>
                  </Card>
                </Col>
              );
            })}
          </Row>
        </HomepageSection>
      )}

      {/* Activity Feed */}
      <HomepageSection title="Recent Activity">
        <Card size="small">
          <ActivityFeed limit={5} compact />
        </Card>
      </HomepageSection>

    </div>
  );
}
