import { useState } from 'react';
import { Link } from 'react-router-dom';
import {
  Typography,
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Steps,
  Result,
  message,
  Grid,
  theme,
} from 'antd';
import {
  EditOutlined,
  MailOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { GovernmentLevel, CreateUserCampaignPayload } from '@/types/api';
import { GOVERNMENT_LEVEL_LABELS } from '@/types/api';

const { Title, Text, Paragraph } = Typography;

const GOV_LEVEL_OPTIONS: { value: GovernmentLevel; label: string }[] = [
  { value: 'FEDERAL', label: GOVERNMENT_LEVEL_LABELS.FEDERAL },
  { value: 'PROVINCIAL', label: GOVERNMENT_LEVEL_LABELS.PROVINCIAL },
  { value: 'MUNICIPAL', label: GOVERNMENT_LEVEL_LABELS.MUNICIPAL },
  { value: 'SCHOOL_BOARD', label: GOVERNMENT_LEVEL_LABELS.SCHOOL_BOARD },
];

export default function CreateCampaignPage() {
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [form] = Form.useForm();
  const [step, setStep] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const handleNext = async () => {
    try {
      if (step === 0) {
        await form.validateFields(['title', 'description', 'targetGovernmentLevels']);
      } else if (step === 1) {
        await form.validateFields(['emailSubject', 'emailBody']);
      }
      setStep(step + 1);
    } catch {
      // validation error
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);
      const payload: CreateUserCampaignPayload = {
        title: values.title,
        description: values.description || undefined,
        emailSubject: values.emailSubject,
        emailBody: values.emailBody,
        callToAction: values.callToAction || undefined,
        targetGovernmentLevels: values.targetGovernmentLevels,
      };
      await api.post('/campaigns/user/submit', payload);
      setSubmitted(true);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })
        ?.response?.data?.error?.message || 'Failed to submit campaign';
      message.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <Result
        status="success"
        title="Campaign Submitted for Review!"
        subTitle="An admin will review your campaign. You'll be able to see its status on your My Campaigns page."
        extra={[
          <Link key="mine" to="/campaigns/mine">
            <Button type="primary">View My Campaigns</Button>
          </Link>,
          <Link key="home" to="/campaigns">
            <Button>Back to Campaigns</Button>
          </Link>,
        ]}
      />
    );
  }

  const formValues = form.getFieldsValue(true);

  return (
    <div>
      <Title level={3} style={{ color: '#fff', textAlign: 'center', marginBottom: 4 }}>
        Create a Campaign
      </Title>
      <Paragraph style={{ color: 'rgba(255,255,255,0.55)', textAlign: 'center', marginBottom: 24 }}>
        Submit your campaign for review. Once approved, others can use it to contact their representatives.
      </Paragraph>

      <Steps
        current={step}
        size={isMobile ? 'small' : 'default'}
        style={{ marginBottom: 24 }}
        items={[
          { title: 'Campaign Info', icon: <EditOutlined /> },
          { title: 'Email Template', icon: <MailOutlined /> },
          { title: 'Review & Submit', icon: <CheckCircleOutlined /> },
        ]}
      />

      <Form form={form} layout="vertical" size="large">
        {step === 0 && (
          <Card style={{ background: token.colorBgContainer, border: '1px solid rgba(255,255,255,0.08)' }}>
            <Form.Item
              name="title"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Campaign Title</Text>}
              rules={[
                { required: true, message: 'Title is required' },
                { min: 3, message: 'At least 3 characters' },
                { max: 200, message: 'Maximum 200 characters' },
              ]}
            >
              <Input placeholder="e.g. Protect Our Green Spaces" />
            </Form.Item>

            <Form.Item
              name="description"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Description (optional)</Text>}
              rules={[{ max: 2000, message: 'Maximum 2000 characters' }]}
            >
              <Input.TextArea rows={3} placeholder="Briefly describe the purpose of this campaign" />
            </Form.Item>

            <Form.Item
              name="targetGovernmentLevels"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Target Government Levels</Text>}
              rules={[{ required: true, message: 'Select at least one government level' }]}
            >
              <Checkbox.Group options={GOV_LEVEL_OPTIONS} />
            </Form.Item>

            <Button type="primary" onClick={handleNext}>
              Next: Email Template
            </Button>
          </Card>
        )}

        {step === 1 && (
          <Card style={{ background: token.colorBgContainer, border: '1px solid rgba(255,255,255,0.08)' }}>
            <Form.Item
              name="emailSubject"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Email Subject Line</Text>}
              rules={[
                { required: true, message: 'Subject is required' },
                { min: 3, message: 'At least 3 characters' },
                { max: 200, message: 'Maximum 200 characters' },
              ]}
            >
              <Input placeholder="e.g. Urgent: Protect Our Local Parks" />
            </Form.Item>

            <Form.Item
              name="emailBody"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Email Body</Text>}
              rules={[
                { required: true, message: 'Email body is required' },
                { min: 10, message: 'At least 10 characters' },
                { max: 5000, message: 'Maximum 5000 characters' },
              ]}
            >
              <Input.TextArea
                rows={10}
                placeholder="Write the email that will be sent to representatives..."
                showCount
                maxLength={5000}
              />
            </Form.Item>

            <Form.Item
              name="callToAction"
              label={<Text style={{ color: 'rgba(255,255,255,0.85)' }}>Call to Action (optional)</Text>}
              rules={[{ max: 500, message: 'Maximum 500 characters' }]}
            >
              <Input placeholder="e.g. Stand up for our community's future!" />
            </Form.Item>

            <div style={{ display: 'flex', gap: 12 }}>
              <Button onClick={() => setStep(0)}>Back</Button>
              <Button type="primary" onClick={handleNext}>
                Next: Review
              </Button>
            </div>
          </Card>
        )}

        {step === 2 && (
          <Card style={{ background: token.colorBgContainer, border: '1px solid rgba(255,255,255,0.08)' }}>
            <Title level={4} style={{ color: '#fff', marginBottom: 16 }}>Review Your Campaign</Title>

            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ color: 'rgba(255,255,255,0.85)' }}>Title: </Text>
              <Text style={{ color: 'rgba(255,255,255,0.7)' }}>{formValues.title}</Text>
            </div>

            {formValues.description && (
              <div style={{ marginBottom: 16 }}>
                <Text strong style={{ color: 'rgba(255,255,255,0.85)' }}>Description: </Text>
                <Text style={{ color: 'rgba(255,255,255,0.7)' }}>{formValues.description}</Text>
              </div>
            )}

            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ color: 'rgba(255,255,255,0.85)' }}>Government Levels: </Text>
              <Text style={{ color: 'rgba(255,255,255,0.7)' }}>
                {(formValues.targetGovernmentLevels || []).map((l: GovernmentLevel) => GOVERNMENT_LEVEL_LABELS[l]).join(', ')}
              </Text>
            </div>

            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ color: 'rgba(255,255,255,0.85)' }}>Email Subject: </Text>
              <Text style={{ color: 'rgba(255,255,255,0.7)' }}>{formValues.emailSubject}</Text>
            </div>

            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ color: 'rgba(255,255,255,0.85)', display: 'block', marginBottom: 4 }}>Email Body:</Text>
              <div style={{
                padding: 12,
                background: 'rgba(0,0,0,0.2)',
                borderRadius: 6,
                border: '1px solid rgba(255,255,255,0.06)',
                whiteSpace: 'pre-wrap',
                color: 'rgba(255,255,255,0.7)',
                maxHeight: 200,
                overflow: 'auto',
              }}>
                {formValues.emailBody}
              </div>
            </div>

            {formValues.callToAction && (
              <div style={{ marginBottom: 16 }}>
                <Text strong style={{ color: 'rgba(255,255,255,0.85)' }}>Call to Action: </Text>
                <Text style={{ color: 'rgba(255,255,255,0.7)' }}>{formValues.callToAction}</Text>
              </div>
            )}

            <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
              <Button onClick={() => setStep(1)}>Back</Button>
              <Button type="primary" loading={submitting} onClick={handleSubmit}>
                Submit for Review
              </Button>
            </div>
          </Card>
        )}
      </Form>
    </div>
  );
}
