import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Typography,
  Card,
  Tag,
  Button,
  Empty,
  Spin,
  Alert,
  Space,
  Grid,
  theme,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { Campaign } from '@/types/api';
import {
  CAMPAIGN_MODERATION_STATUS_COLORS,
  CAMPAIGN_MODERATION_STATUS_LABELS,
  GOVERNMENT_LEVEL_LABELS,
  GOVERNMENT_LEVEL_COLORS,
} from '@/types/api';
import type { GovernmentLevel } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

export default function MyCampaignsPage() {
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCampaigns();
  }, []);

  const fetchCampaigns = async () => {
    setLoading(true);
    try {
      const { data } = await api.get<Campaign[]>('/campaigns/user/my-campaigns');
      setCampaigns(data);
    } catch {
      // handled below
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        <Title level={3} style={{ color: '#fff', margin: 0 }}>My Campaigns</Title>
        <Link to="/campaigns/create">
          <Button type="primary" icon={<PlusOutlined />}>Create Campaign</Button>
        </Link>
      </div>

      {campaigns.length === 0 ? (
        <Empty
          description={<Text style={{ color: 'rgba(255,255,255,0.45)' }}>You haven't created any campaigns yet</Text>}
          style={{ padding: 60 }}
        >
          <Link to="/campaigns/create">
            <Button type="primary" icon={<PlusOutlined />}>Create Your First Campaign</Button>
          </Link>
        </Empty>
      ) : (
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          {campaigns.map((campaign) => {
            const canEdit = campaign.moderationStatus === 'CHANGES_REQUESTED' || campaign.moderationStatus === 'PENDING_REVIEW';
            const isActive = campaign.status === 'ACTIVE' && campaign.moderationStatus === 'APPROVED';

            return (
              <Card
                key={campaign.id}
                style={{
                  background: token.colorBgContainer,
                  border: '1px solid rgba(255,255,255,0.08)',
                  borderRadius: 10,
                }}
              >
                <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 16, justifyContent: 'space-between' }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
                      <Text strong style={{ color: '#fff', fontSize: 16 }}>{campaign.title}</Text>
                      {campaign.moderationStatus && (
                        <Tag color={CAMPAIGN_MODERATION_STATUS_COLORS[campaign.moderationStatus]}>
                          {CAMPAIGN_MODERATION_STATUS_LABELS[campaign.moderationStatus]}
                        </Tag>
                      )}
                    </div>

                    {campaign.description && (
                      <Paragraph style={{ color: 'rgba(255,255,255,0.55)', margin: '0 0 8px' }} ellipsis={{ rows: 2 }}>
                        {campaign.description}
                      </Paragraph>
                    )}

                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 8 }}>
                      {campaign.targetGovernmentLevels.map((l: GovernmentLevel) => (
                        <Tag key={l} color={GOVERNMENT_LEVEL_COLORS[l]} style={{ fontSize: 11 }}>
                          {GOVERNMENT_LEVEL_LABELS[l]}
                        </Tag>
                      ))}
                    </div>

                    <Text style={{ color: 'rgba(255,255,255,0.35)', fontSize: 12 }}>
                      Created {new Date(campaign.createdAt).toLocaleDateString()}
                    </Text>

                    {(campaign.moderationStatus === 'REJECTED' || campaign.moderationStatus === 'CHANGES_REQUESTED') && campaign.rejectionReason && (
                      <Alert
                        type={campaign.moderationStatus === 'REJECTED' ? 'error' : 'warning'}
                        message={campaign.moderationStatus === 'REJECTED' ? 'Rejection Reason' : 'Changes Requested'}
                        description={campaign.rejectionReason}
                        style={{ marginTop: 12 }}
                        showIcon
                      />
                    )}
                  </div>

                  <div style={{ display: 'flex', gap: 8, alignItems: isMobile ? 'stretch' : 'flex-start', flexDirection: isMobile ? 'row' : 'column' }}>
                    {canEdit && (
                      <Link to={`/campaigns/create?edit=${campaign.id}`}>
                        <Button icon={<EditOutlined />} block={isMobile}>Edit</Button>
                      </Link>
                    )}
                    {isActive && (
                      <Link to={`/campaign/${campaign.slug}`}>
                        <Button type="primary" icon={<EyeOutlined />} block={isMobile}>View</Button>
                      </Link>
                    )}
                  </div>
                </div>
              </Card>
            );
          })}
        </Space>
      )}
    </div>
  );
}
