import { useState, useEffect, useCallback } from 'react';
import {
  Card, Table, Button, Space, Tag, Input, Select, Drawer, Typography, message,
  Statistic, Row, Col, Grid,
} from 'antd';
import {
  CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined,
  SearchOutlined, ReloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { Petition, PetitionsListResponse, CampaignModerationStatus } from '@/types/api';

const { Text, Paragraph } = Typography;
const { TextArea } = Input;

const MODERATION_STATUS_COLORS: Record<CampaignModerationStatus, string> = {
  PENDING_REVIEW: 'orange',
  APPROVED: 'green',
  REJECTED: 'red',
  CHANGES_REQUESTED: 'gold',
};

export default function PetitionModerationPage() {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [petitions, setPetitions] = useState<Petition[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<CampaignModerationStatus | undefined>(undefined);
  const [stats, setStats] = useState<{ pending: number; approved: number; rejected: number; changesRequested: number } | null>(null);
  const [selectedPetition, setSelectedPetition] = useState<Petition | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [actionModalOpen, setActionModalOpen] = useState(false);
  const [actionType, setActionType] = useState<'reject' | 'request_changes' | null>(null);
  const [actionReason, setActionReason] = useState('');
  const [actionLoading, setActionLoading] = useState(false);

  const fetchQueue = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = { page, limit: pageSize };
      if (search) params.search = search;
      if (statusFilter) params.moderationStatus = statusFilter;
      const { data } = await api.get<PetitionsListResponse>('/petitions/moderation/queue', { params });
      setPetitions(data.petitions);
      setTotal(data.pagination.total);
    } catch {
      message.error('Failed to load moderation queue');
    } finally {
      setLoading(false);
    }
  }, [page, pageSize, search, statusFilter]);

  const fetchStats = useCallback(async () => {
    try {
      const { data } = await api.get('/petitions/moderation/stats');
      setStats(data);
    } catch { /* non-critical */ }
  }, []);

  useEffect(() => { fetchQueue(); }, [fetchQueue]);
  useEffect(() => { fetchStats(); }, [fetchStats]);

  const handleApprove = async (petition: Petition) => {
    try {
      await api.patch(`/petitions/moderation/${petition.id}`, { action: 'approve' });
      message.success('Petition approved');
      fetchQueue();
      fetchStats();
      setDrawerOpen(false);
    } catch {
      message.error('Failed to approve petition');
    }
  };

  const handleActionSubmit = async () => {
    if (!selectedPetition || !actionType) return;
    setActionLoading(true);
    try {
      await api.patch(`/petitions/moderation/${selectedPetition.id}`, {
        action: actionType,
        reason: actionReason,
      });
      message.success(actionType === 'reject' ? 'Petition rejected' : 'Changes requested');
      setActionModalOpen(false);
      setActionReason('');
      setActionType(null);
      setDrawerOpen(false);
      fetchQueue();
      fetchStats();
    } catch {
      message.error('Failed to update petition');
    } finally {
      setActionLoading(false);
    }
  };

  const columns: ColumnsType<Petition> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (title: string, record: Petition) => (
        <Button type="link" onClick={() => { setSelectedPetition(record); setDrawerOpen(true); }} style={{ padding: 0 }}>
          {title}
        </Button>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'moderationStatus',
      key: 'status',
      width: 130,
      render: (status: CampaignModerationStatus | null) =>
        status ? <Tag color={MODERATION_STATUS_COLORS[status]}>{status.replace(/_/g, ' ')}</Tag> : '-',
    },
    {
      title: 'Submitted By',
      dataIndex: 'createdByUserName',
      key: 'submitter',
      width: 150,
      ellipsis: true,
    },
    ...(isMobile ? [] : [{
      title: 'Date',
      dataIndex: 'createdAt',
      key: 'date',
      width: 110,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    } as any]),
    {
      title: 'Actions',
      key: 'actions',
      width: 200,
      render: (_: unknown, record: Petition) => (
        <Space size={4}>
          <Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(record)}>Approve</Button>
          <Button size="small" danger icon={<CloseCircleOutlined />}
            onClick={() => { setSelectedPetition(record); setActionType('reject'); setActionModalOpen(true); }}
          >Reject</Button>
        </Space>
      ),
    },
  ];

  const activeDrawerWidth = !isMobile
    ? (drawerOpen ? 500 : actionModalOpen ? 480 : 0)
    : 0;

  return (
    <>
    <div
      style={{
        padding: isMobile ? 12 : 24,
        marginRight: activeDrawerWidth,
        transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
      }}
    >
      {stats && (
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={6}><Card size="small"><Statistic title="Pending" value={stats.pending} valueStyle={{ color: '#faad14' }} /></Card></Col>
          <Col xs={6}><Card size="small"><Statistic title="Approved" value={stats.approved} valueStyle={{ color: '#52c41a' }} /></Card></Col>
          <Col xs={6}><Card size="small"><Statistic title="Rejected" value={stats.rejected} valueStyle={{ color: '#ff4d4f' }} /></Card></Col>
          <Col xs={6}><Card size="small"><Statistic title="Changes" value={stats.changesRequested} /></Card></Col>
        </Row>
      )}

      <Card
        title="Petition Moderation Queue"
        extra={
          <Space wrap>
            <Input placeholder="Search..." prefix={<SearchOutlined />} allowClear value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} style={{ width: isMobile ? 140 : 200 }} />
            <Select placeholder="Status" allowClear value={statusFilter} onChange={v => { setStatusFilter(v); setPage(1); }} style={{ width: 160 }}
              options={['PENDING_REVIEW', 'APPROVED', 'REJECTED', 'CHANGES_REQUESTED'].map(s => ({ label: s.replace(/_/g, ' '), value: s }))}
            />
            <Button icon={<ReloadOutlined />} onClick={fetchQueue} />
          </Space>
        }
      >
        <Table
          dataSource={petitions}
          columns={columns}
          rowKey="id"
          loading={loading}
          pagination={{ current: page, pageSize, total, onChange: setPage, showSizeChanger: false, size: 'small' }}
          size="small"
          scroll={{ x: 600 }}
        />
      </Card>

      </div>

      <Drawer
        title="Review Petition"
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={isMobile ? '100%' : 500}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      >
        {selectedPetition && (
          <Space direction="vertical" size={16} style={{ width: '100%' }}>
            <div>
              <Text strong style={{ fontSize: 18 }}>{selectedPetition.title}</Text>
              <br />
              <Text type="secondary">by {selectedPetition.createdByUserName || 'Unknown'} on {dayjs(selectedPetition.createdAt).format('MMM D, YYYY')}</Text>
            </div>

            {selectedPetition.description && (
              <Card size="small" title="Description">
                <Paragraph>{selectedPetition.description}</Paragraph>
              </Card>
            )}

            {selectedPetition.callToAction && (
              <Card size="small" title="Call to Action">
                <Paragraph>{selectedPetition.callToAction}</Paragraph>
              </Card>
            )}

            <Space>
              <Button type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(selectedPetition)}>Approve</Button>
              <Button danger icon={<CloseCircleOutlined />}
                onClick={() => { setActionType('reject'); setActionModalOpen(true); }}
              >Reject</Button>
              <Button icon={<ExclamationCircleOutlined />}
                onClick={() => { setActionType('request_changes'); setActionModalOpen(true); }}
              >Request Changes</Button>
            </Space>
          </Space>
        )}
      </Drawer>

      <Drawer
        title={actionType === 'reject' ? 'Reject Petition' : 'Request Changes'}
        open={actionModalOpen}
        onClose={() => { setActionModalOpen(false); setActionReason(''); }}
        placement="right"
        width={isMobile ? '100%' : 480}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Button
            type="primary"
            danger={actionType === 'reject'}
            loading={actionLoading}
            onClick={handleActionSubmit}
          >
            {actionType === 'reject' ? 'Reject' : 'Send'}
          </Button>
        }
      >
        <TextArea
          rows={4}
          value={actionReason}
          onChange={e => setActionReason(e.target.value)}
          placeholder={actionType === 'reject' ? 'Reason for rejection...' : 'What changes are needed...'}
        />
      </Drawer>
    </>
  );
}
