import { useState, useEffect, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
  Typography,
  Card,
  Button,
  Space,
  Tag,
  Row,
  Col,
  Select,
  Statistic,
  Spin,
  Result,
  Modal,
  Form,
  Input,
  Checkbox,
  message,
  Pagination,
  Divider,
  Grid,
  Tooltip,
  theme,
} from 'antd';
import {
  LikeOutlined,
  LikeFilled,
  SafetyCertificateOutlined,
  ArrowLeftOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import type {
  Campaign,
  RepresentativeResponse,
  ResponseStats,
  GovernmentLevel,
} from '@/types/api';
import {
  GOVERNMENT_LEVEL_COLORS,
  GOVERNMENT_LEVEL_LABELS,
  RESPONSE_TYPE_LABELS,
} from '@/types/api';
import dayjs from 'dayjs';
import { useSettingsStore } from '@/stores/settings.store';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Title, Text, Paragraph } = Typography;

const apiBase = '/api';

export default function ResponseWallPage() {
  const { slug } = useParams<{ slug: string }>();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { token } = theme.useToken();
  const { settings: siteSettings } = useSettingsStore();

  const [campaign, setCampaign] = useState<Campaign | null>(null);
  const [responses, setResponses] = useState<RepresentativeResponse[]>([]);
  const [stats, setStats] = useState<ResponseStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [sort, setSort] = useState<'recent' | 'upvotes' | 'verified'>('recent');
  const [levelFilter, setLevelFilter] = useState<GovernmentLevel | undefined>();
  const [submitModalOpen, setSubmitModalOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [upvotedIds, setUpvotedIds] = useState<Set<string>>(new Set());
  const [upvotingId, setUpvotingId] = useState<string | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    if (campaign) {
      document.title = `Response Wall - ${campaign.title} | ${siteSettings?.organizationName || 'Changemaker'}`;
    }
  }, [campaign, siteSettings?.organizationName]);

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

  const fetchCampaign = async () => {
    try {
      const { data } = await axios.get<Campaign>(`${apiBase}/campaigns/${slug}/details`);
      setCampaign(data);
    } catch {
      setError('Campaign not found or is no longer active.');
    }
  };

  const fetchStats = async () => {
    try {
      const { data } = await axios.get<ResponseStats>(`${apiBase}/campaigns/${slug}/response-stats`);
      setStats(data);
    } catch {
      // Non-critical
    }
  };

  const fetchResponses = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = { page, limit: 20, sort };
      if (levelFilter) params.level = levelFilter;

      const { data } = await axios.get(`${apiBase}/campaigns/${slug}/responses`, { params });
      setResponses(data.responses);
      setTotal(data.pagination.total);
    } catch {
      message.error('Failed to load responses');
    } finally {
      setLoading(false);
    }
  }, [slug, page, sort, levelFilter]);

  useEffect(() => {
    if (slug) fetchResponses();
  }, [fetchResponses, slug]);

  const handleUpvote = async (responseId: string) => {
    setUpvotingId(responseId);
    if (upvotedIds.has(responseId)) {
      // Remove upvote
      try {
        await axios.delete(`${apiBase}/responses/${responseId}/upvote`);
        setUpvotedIds((prev) => {
          const next = new Set(prev);
          next.delete(responseId);
          return next;
        });
        setResponses((prev) =>
          prev.map((r) =>
            r.id === responseId ? { ...r, upvoteCount: Math.max(0, r.upvoteCount - 1) } : r
          )
        );
      } catch {
        // Ignore
      } finally {
        setUpvotingId(null);
      }
    } else {
      try {
        const { data } = await axios.post(`${apiBase}/responses/${responseId}/upvote`);
        if (data.alreadyUpvoted) {
          message.info('You have already upvoted this response');
          setUpvotedIds((prev) => new Set(prev).add(responseId));
        } else {
          setUpvotedIds((prev) => new Set(prev).add(responseId));
          setResponses((prev) =>
            prev.map((r) =>
              r.id === responseId ? { ...r, upvoteCount: r.upvoteCount + 1 } : r
            )
          );
        }
      } catch {
        // Ignore
      } finally {
        setUpvotingId(null);
      }
    }
  };

  const handleSubmit = async (values: any) => {
    setSubmitting(true);
    try {
      await axios.post(`${apiBase}/campaigns/${slug}/responses`, {
        representativeName: values.representativeName,
        representativeLevel: values.representativeLevel,
        responseType: values.responseType,
        responseText: values.responseText,
        representativeTitle: values.representativeTitle || undefined,
        representativeEmail: values.representativeEmail || undefined,
        userComment: values.userComment || undefined,
        submittedByName: values.submittedByName || undefined,
        submittedByEmail: values.submittedByEmail || undefined,
        isAnonymous: values.isAnonymous || false,
        sendVerification: values.sendVerification || false,
      });
      message.success('Response submitted! It will appear after moderation.');
      setSubmitModalOpen(false);
      form.resetFields();
      fetchResponses();
      fetchStats();
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to submit response'));
    } finally {
      setSubmitting(false);
    }
  };

  if (error) {
    return <Result status="404" title="Campaign Not Found" subTitle={error} />;
  }

  return (
    <div>
      {/* Back link + Header */}
      <Link to={`/campaign/${slug}`}>
        <Button type="link" icon={<ArrowLeftOutlined />} style={{ padding: 0, marginBottom: 16 }}>
          Back to Campaign
        </Button>
      </Link>

      {campaign && (
        <Link to={`/campaign/${slug}`} style={{ textDecoration: 'none' }}>
          <div
            style={{
              background: 'linear-gradient(135deg, #3498db, #2c3e50)',
              borderRadius: 12,
              padding: isMobile ? '24px 16px' : '32px 24px',
              textAlign: 'center',
              marginBottom: 24,
              cursor: 'pointer',
            }}
          >
            <Title level={3} style={{ color: '#fff', margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.2)' }}>
              {campaign.title}
            </Title>
            <Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 15 }}>Community Response Wall</Text>
            <br />
            <Text style={{ color: 'rgba(255,255,255,0.55)', fontSize: 13 }}>
              See how elected representatives have responded to this campaign — and share responses you've received.
            </Text>
          </div>
        </Link>
      )}

      {/* Stats Banner */}
      {stats && (
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic title="Responses" value={stats.total} />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic
                title="Verified"
                value={stats.verified}
                prefix={<SafetyCertificateOutlined style={{ color: token.colorSuccess }} />}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic title="Upvotes" value={stats.totalUpvotes} prefix={<LikeOutlined />} />
            </Card>
          </Col>
        </Row>
      )}

      {/* Controls */}
      <Row gutter={[12, 12]} align="middle" style={{ marginBottom: 16 }}>
        <Col xs={12} sm={6}>
          <Select
            value={sort}
            onChange={(v) => { setSort(v); setPage(1); }}
            style={{ width: '100%' }}
            aria-label="Sort responses"
            options={[
              { value: 'recent', label: 'Most Recent' },
              { value: 'upvotes', label: 'Most Upvotes' },
              { value: 'verified', label: 'Verified First' },
            ]}
          />
        </Col>
        <Col xs={12} sm={6}>
          <Select
            placeholder="Filter by level"
            allowClear
            value={levelFilter}
            onChange={(v) => { setLevelFilter(v); setPage(1); }}
            style={{ width: '100%' }}
            aria-label="Filter by government level"
            options={Object.entries(GOVERNMENT_LEVEL_LABELS).map(([value, label]) => ({
              value,
              label,
            }))}
          />
        </Col>
        <Col xs={24} sm={12} style={{ textAlign: 'right' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setSubmitModalOpen(true)}
          >
            Share a Response
          </Button>
        </Col>
      </Row>

      {/* Response Cards */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: 60 }}>
          <Spin size="large" />
        </div>
      ) : responses.length === 0 ? (
        <Result
          status="info"
          title="No Responses Yet"
          subTitle="Be the first to share a representative's response!"
          extra={
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setSubmitModalOpen(true)}>
              Share a Response
            </Button>
          }
        />
      ) : (
        <>
          <Space direction="vertical" size={16} style={{ width: '100%' }}>
            {responses.map((response) => (
              <Card key={response.id} size="small">
                <Row justify="space-between" align="top">
                  <Col flex="1">
                    <Space wrap>
                      <Text strong style={{ fontSize: 15 }}>
                        {response.representativeName}
                      </Text>
                      {response.representativeTitle && (
                        <Text type="secondary">
                          {response.representativeTitle}
                        </Text>
                      )}
                    </Space>
                    <br />
                    <Space size={4} style={{ marginTop: 4 }}>
                      <Tag color={GOVERNMENT_LEVEL_COLORS[response.representativeLevel]}>
                        {GOVERNMENT_LEVEL_LABELS[response.representativeLevel]}
                      </Tag>
                      <Tag>{RESPONSE_TYPE_LABELS[response.responseType]}</Tag>
                      {response.isVerified && (
                        <Tooltip title="This response was verified by emailing the representative">
                          <Tag icon={<SafetyCertificateOutlined />} color="success">
                            Verified
                          </Tag>
                        </Tooltip>
                      )}
                    </Space>
                  </Col>
                  <Col>
                    <Button
                      type={upvotedIds.has(response.id) ? 'primary' : 'default'}
                      size="small"
                      icon={upvotedIds.has(response.id) ? <LikeFilled /> : <LikeOutlined />}
                      onClick={() => handleUpvote(response.id)}
                      loading={upvotingId === response.id}
                      aria-label={upvotedIds.has(response.id) ? `Remove upvote (${response.upvoteCount} total)` : `Upvote response (${response.upvoteCount} total)`}
                    >
                      {response.upvoteCount}
                    </Button>
                  </Col>
                </Row>

                <Divider style={{ margin: '12px 0' }} />

                <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                  {response.responseText}
                </Paragraph>

                {/* userComment + submittedByName removed from public response wall
                    on 2026-04-12 (privacy hardening). Admin moderation UI still shows them. */}

                <div style={{ marginTop: 12 }}>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {dayjs(response.createdAt).format('MMM D, YYYY')}
                  </Text>
                </div>
              </Card>
            ))}
          </Space>

          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Pagination
              current={page}
              total={total}
              pageSize={20}
              onChange={(p) => setPage(p)}
              showSizeChanger={false}
            />
          </div>
        </>
      )}

      {/* Submit Response Modal */}
      <Modal
        title="Share a Representative's Response"
        open={submitModalOpen}
        onCancel={() => setSubmitModalOpen(false)}
        footer={null}
        width={isMobile ? '100%' : 560}
        style={{ maxWidth: '95vw' }}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="representativeName"
            label="Representative Name"
            rules={[{ required: true, message: 'Required' }]}
          >
            <Input placeholder="e.g. John Smith" autoFocus />
          </Form.Item>

          <Row gutter={12}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="representativeLevel"
                label="Government Level"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select
                  placeholder="Select level"
                  options={Object.entries(GOVERNMENT_LEVEL_LABELS).map(([value, label]) => ({
                    value,
                    label,
                  }))}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name="responseType"
                label="Response Type"
                rules={[{ required: true, message: 'Required' }]}
              >
                <Select
                  placeholder="How did they respond?"
                  options={Object.entries(RESPONSE_TYPE_LABELS).map(([value, label]) => ({
                    value,
                    label,
                  }))}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="representativeTitle" label="Representative Title">
            <Input placeholder="e.g. MP, MPP, City Councillor" />
          </Form.Item>

          <Form.Item
            name="responseText"
            label="Response Text"
            rules={[{ required: true, message: 'Required' }]}
          >
            <Input.TextArea
              rows={5}
              placeholder="What did the representative say or write?"
            />
          </Form.Item>

          <Form.Item name="userComment" label="Your Comment (optional)">
            <Input.TextArea rows={2} placeholder="Any additional context?" />
          </Form.Item>

          <Divider style={{ margin: '12px 0' }} />

          <Row gutter={12}>
            <Col xs={24} sm={12}>
              <Form.Item name="submittedByName" label="Your Name">
                <Input placeholder="Optional" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item name="submittedByEmail" label="Your Email">
                <Input placeholder="Optional" type="email" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="representativeEmail" label="Representative's Email">
            <Input placeholder="For verification (optional)" type="email" />
          </Form.Item>

          <Space>
            <Form.Item name="isAnonymous" valuePropName="checked" noStyle>
              <Checkbox>Submit anonymously</Checkbox>
            </Form.Item>
            <Form.Item name="sendVerification" valuePropName="checked" noStyle>
              <Checkbox>Send verification to representative</Checkbox>
            </Form.Item>
          </Space>

          <div style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setSubmitModalOpen(false)}>Cancel</Button>
              <Button type="primary" htmlType="submit" loading={submitting}>
                Submit Response
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  );
}
