import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
  Typography, Card, Button, Input, Checkbox, Form, Spin, Result, Progress,
  Space, Divider, Grid, theme, message,
} from 'antd';
import {
  TeamOutlined, CheckCircleFilled, ShareAltOutlined,
  CopyOutlined, ArrowRightOutlined,
  SendOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import { VideoPlayer } from '@/components/media/VideoPlayer';
import type { Petition, SignPetitionResponse } from '@/types/api';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const API = '/api';

type PageState = 'form' | 'submitted' | 'pending_verification';

export default function PetitionPage() {
  const { slug } = useParams<{ slug: string }>();
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [petition, setPetition] = useState<Petition | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [state, setState] = useState<PageState>('form');
  const [submitting, setSubmitting] = useState(false);
  const [signatureCount, setSignatureCount] = useState(0);
  const [form] = Form.useForm();
  const { settings: siteSettings } = useSettingsStore();

  useEffect(() => {
    if (!slug) return;
    (async () => {
      try {
        const { data } = await axios.get(`${API}/petitions/${slug}/details`);
        setPetition(data);
        setSignatureCount(data._count.signatures + data.signatureCountOffset);
      } catch {
        setError(true);
      } finally {
        setLoading(false);
      }
    })();
  }, [slug]);

  const handleSign = async () => {
    if (!slug) return;
    try {
      const values = await form.validateFields();
      setSubmitting(true);
      const { data } = await axios.post<SignPetitionResponse>(`${API}/petitions/${slug}/sign`, values);

      if (data.alreadySigned) {
        message.info('You have already signed this petition. Thank you!');
        setState('submitted');
        return;
      }

      setSignatureCount(prev => prev + 1);

      if (data.verificationSent) {
        setState('pending_verification');
      } else {
        setState('submitted');
      }
    } catch (err: any) {
      const msg = err?.response?.data?.error?.message || 'Failed to submit signature';
      message.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  const handleCopyLink = () => {
    navigator.clipboard.writeText(window.location.href);
    message.success('Link copied!');
  };

  const handleShareTwitter = () => {
    const text = `I signed "${petition?.title}" — add your voice too!`;
    window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(window.location.href)}`, '_blank');
  };

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
  if (error || !petition) return <Result status="404" title="Petition Not Found" subTitle="This petition may have been removed or is not yet active." />;

  const hasGoal = petition.signatureGoal && petition.signatureGoal > 0;
  const pct = hasGoal ? Math.min(100, Math.round((signatureCount / petition.signatureGoal!) * 100)) : null;
  const linkedCampaign = petition.linkedCampaign;

  return (
    <div style={{ maxWidth: 700, margin: '0 auto', padding: isMobile ? '16px 12px' : '32px 16px' }}>
      {/* Cover Video */}
      {petition.coverVideoId && siteSettings?.enableMediaFeatures !== false && (
        <div style={{ marginBottom: 24, borderRadius: 12, overflow: 'hidden' }}>
          <VideoPlayer videoId={petition.coverVideoId} width="100%" height="auto" controls />
        </div>
      )}

      {/* Cover Image (only if no video) */}
      {!petition.coverVideoId && petition.coverPhoto && (
        <div style={{ borderRadius: 12, overflow: 'hidden', marginBottom: 24 }}>
          <img src={petition.coverPhoto} alt={petition.title} style={{ width: '100%', maxHeight: 300, objectFit: 'cover' }} />
        </div>
      )}

      <Title level={2} style={{ marginBottom: 8 }}>{petition.title}</Title>

      {petition.description && (
        <Paragraph style={{ fontSize: 16, lineHeight: 1.7, marginBottom: 24, color: token.colorTextSecondary }}>
          {petition.description}
        </Paragraph>
      )}

      {/* Signature counter */}
      <Card style={{ marginBottom: 24, background: token.colorBgContainer, textAlign: 'center' }}>
        <TeamOutlined style={{ fontSize: 28, color: token.colorPrimary, marginBottom: 8 }} />
        <Title level={3} style={{ margin: 0, color: token.colorPrimary }}>
          {signatureCount.toLocaleString()}
        </Title>
        <Text type="secondary">
          signature{signatureCount !== 1 ? 's' : ''}
          {hasGoal && ` of ${petition.signatureGoal!.toLocaleString()} goal`}
        </Text>
        {hasGoal && (
          <Progress percent={pct!} strokeColor={token.colorPrimary} style={{ marginTop: 12 }} />
        )}
      </Card>

      {/* Sign Form */}
      {state === 'form' && (
        <Card title="Sign this petition" style={{ marginBottom: 24, background: token.colorBgContainer }}>
          <Form form={form} layout="vertical" onFinish={handleSign}>
            {petition.requireName && (
              <Form.Item name="signerName" label="Your Name" rules={[{ required: true, message: 'Name is required' }]}>
                <Input size="large" placeholder="Your full name" maxLength={200} />
              </Form.Item>
            )}

            {petition.requireEmail && (
              <Form.Item name="signerEmail" label="Email" rules={[{ required: true, message: 'Email is required' }, { type: 'email', message: 'Invalid email' }]}>
                <Input size="large" placeholder="your@email.com" maxLength={255} />
              </Form.Item>
            )}

            {petition.requirePostalCode && (
              <Form.Item name="signerPostalCode" label="Postal Code" rules={[{ required: true, message: 'Postal code is required' }]}>
                <Input size="large" placeholder="A1A 1A1" maxLength={20} />
              </Form.Item>
            )}

            {petition.requirePhone && (
              <Form.Item name="signerPhone" label="Phone" rules={[{ required: true, message: 'Phone is required' }]}>
                <Input size="large" placeholder="(555) 123-4567" maxLength={30} />
              </Form.Item>
            )}

            {petition.allowComment && (
              <Form.Item name="signerComment" label={petition.commentLabel || 'Why do you support this?'}>
                <TextArea rows={3} maxLength={2000} placeholder="Share your thoughts (optional)" />
              </Form.Item>
            )}

            <Form.Item name="isAnonymous" valuePropName="checked" style={{ marginBottom: 16 }}>
              <Checkbox>Sign anonymously (your name will not be displayed)</Checkbox>
            </Form.Item>

            <Button type="primary" htmlType="submit" size="large" block loading={submitting} icon={<CheckCircleFilled />}>
              Sign Petition
            </Button>

            {petition.requireEmailConfirmation && (
              <Text type="secondary" style={{ display: 'block', textAlign: 'center', marginTop: 8, fontSize: 12 }}>
                You will receive an email to confirm your signature
              </Text>
            )}
          </Form>
        </Card>
      )}

      {/* Pending verification */}
      {state === 'pending_verification' && (
        <Card style={{ marginBottom: 24, textAlign: 'center', background: token.colorBgContainer }}>
          <Result
            status="info"
            title="Check Your Email"
            subTitle="We've sent a confirmation link to your email. Click it to verify your signature."
          />
        </Card>
      )}

      {/* Submitted / Thank You */}
      {state === 'submitted' && (
        <Card style={{ marginBottom: 24, textAlign: 'center', background: token.colorBgContainer }}>
          <CheckCircleFilled style={{ fontSize: 48, color: '#52c41a', marginBottom: 16 }} />
          <Title level={3}>Thank You!</Title>
          {petition.thankYouMessage && (
            <Paragraph style={{ fontSize: 16 }}>{petition.thankYouMessage}</Paragraph>
          )}

          {/* Share buttons */}
          <Divider>Share this petition</Divider>
          <Space wrap style={{ justifyContent: 'center' }}>
            <Button icon={<CopyOutlined />} onClick={handleCopyLink}>Copy Link</Button>
            <Button icon={<ShareAltOutlined />} onClick={handleShareTwitter}>Share on X</Button>
          </Space>

          {/* Linked Campaign CTA */}
          {linkedCampaign && linkedCampaign.status === 'ACTIVE' && (
            <>
              <Divider>Take further action</Divider>
              <Card
                hoverable
                style={{ textAlign: 'left', background: token.colorBgElevated, borderColor: token.colorPrimary, borderWidth: 2 }}
              >
                <Space direction="vertical" size={8} style={{ width: '100%' }}>
                  <Space>
                    <SendOutlined style={{ color: token.colorPrimary, fontSize: 18 }} />
                    <Text strong style={{ fontSize: 16 }}>{linkedCampaign.title}</Text>
                  </Space>
                  {linkedCampaign.description && (
                    <Paragraph type="secondary" ellipsis={{ rows: 2 }} style={{ margin: 0 }}>
                      {linkedCampaign.description}
                    </Paragraph>
                  )}
                  <Link to={`/campaign/${linkedCampaign.slug}`}>
                    <Button type="primary" icon={<ArrowRightOutlined />} style={{ marginTop: 4 }}>
                      Email Your Representatives
                    </Button>
                  </Link>
                </Space>
              </Card>
            </>
          )}
        </Card>
      )}

      {/* Call to action text */}
      {petition.callToAction && state === 'form' && (
        <Card style={{ marginBottom: 24, background: token.colorBgContainer }}>
          <Paragraph style={{ fontSize: 15, margin: 0, whiteSpace: 'pre-wrap' }}>{petition.callToAction}</Paragraph>
        </Card>
      )}

      {/* Recent-signers card removed 2026-04-12: public endpoint no longer exposes
          signer names/locations (privacy hardening). Admins can see the full list. */}

      {/* Share bar (always visible) */}
      {state === 'form' && (
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Space wrap>
            <Button icon={<CopyOutlined />} onClick={handleCopyLink}>Copy Link</Button>
            <Button icon={<ShareAltOutlined />} onClick={handleShareTwitter}>Share on X</Button>
          </Space>
        </div>
      )}
    </div>
  );
}
