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 {
  Campaign,
  CampaignModerationStatus,
  CampaignModerationStats,
  CampaignsListResponse,
  GovernmentLevel,
} from '@/types/api';
import {
  CAMPAIGN_MODERATION_STATUS_COLORS,
  CAMPAIGN_MODERATION_STATUS_LABELS,
  GOVERNMENT_LEVEL_LABELS,
  GOVERNMENT_LEVEL_COLORS,
} from '@/types/api';

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

export default function CampaignModerationPage() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  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<CampaignModerationStats | null>(null);
  const [selectedCampaign, setSelectedCampaign] = useState<Campaign | 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 [actionNotes, setActionNotes] = 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<CampaignsListResponse>('/campaigns/moderation/queue', { params });
      setCampaigns(data.campaigns);
      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<CampaignModerationStats>('/campaigns/moderation/stats');
      setStats(data);
    } catch {
      // non-critical
    }
  }, []);

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

  const handleModerate = async (campaignId: string, action: 'approve' | 'reject' | 'request_changes', reason?: string, notes?: string) => {
    setActionLoading(true);
    try {
      await api.patch(`/campaigns/moderation/${campaignId}`, { action, reason, notes });
      message.success(
        action === 'approve' ? 'Campaign approved and activated' :
        action === 'reject' ? 'Campaign rejected' : 'Changes requested'
      );
      setDrawerOpen(false);
      setActionModalOpen(false);
      setSelectedCampaign(null);
      setActionReason('');
      setActionNotes('');
      fetchQueue();
      fetchStats();
    } catch {
      message.error('Failed to moderate campaign');
    } finally {
      setActionLoading(false);
    }
  };

  const openActionModal = (type: 'reject' | 'request_changes') => {
    setActionType(type);
    setActionReason('');
    setActionModalOpen(true);
  };

  const columns: ColumnsType<Campaign> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record) => (
        <Button type="link" style={{ padding: 0, textAlign: 'left', whiteSpace: 'normal' }} onClick={() => { setSelectedCampaign(record); setDrawerOpen(true); }}>
          {title}
        </Button>
      ),
    },
    {
      title: 'Creator',
      key: 'creator',
      responsive: ['md'] as any,
      render: (_, record) => (
        <div>
          <Text style={{ display: 'block' }}>{record.createdByUserName || 'Unknown'}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.createdByUserEmail}</Text>
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'moderationStatus',
      key: 'moderationStatus',
      render: (status: CampaignModerationStatus) => (
        <Tag color={CAMPAIGN_MODERATION_STATUS_COLORS[status]}>
          {CAMPAIGN_MODERATION_STATUS_LABELS[status]}
        </Tag>
      ),
    },
    {
      title: 'Levels',
      dataIndex: 'targetGovernmentLevels',
      key: 'levels',
      responsive: ['lg'] as any,
      render: (levels: GovernmentLevel[]) => (
        <Space size={4} wrap>
          {levels.map(l => <Tag key={l} color={GOVERNMENT_LEVEL_COLORS[l]} style={{ fontSize: 11 }}>{GOVERNMENT_LEVEL_LABELS[l]}</Tag>)}
        </Space>
      ),
    },
    {
      title: 'Submitted',
      dataIndex: 'createdAt',
      key: 'createdAt',
      responsive: ['md'] as any,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_, record) => (
        <Space size={4}>
          {record.moderationStatus === 'PENDING_REVIEW' && (
            <>
              <Button
                type="primary"
                size="small"
                icon={<CheckCircleOutlined />}
                style={{ background: '#52c41a', borderColor: '#52c41a' }}
                onClick={() => handleModerate(record.id, 'approve')}
              >
                {!isMobile && 'Approve'}
              </Button>
              <Button
                size="small"
                danger
                icon={<CloseCircleOutlined />}
                onClick={() => { setSelectedCampaign(record); openActionModal('reject'); }}
              >
                {!isMobile && 'Reject'}
              </Button>
              <Button
                size="small"
                icon={<ExclamationCircleOutlined />}
                onClick={() => { setSelectedCampaign(record); openActionModal('request_changes'); }}
              >
                {!isMobile && 'Request Changes'}
              </Button>
            </>
          )}
          {record.moderationStatus !== 'PENDING_REVIEW' && (
            <Button
              size="small"
              onClick={() => { setSelectedCampaign(record); setDrawerOpen(true); }}
            >
              View
            </Button>
          )}
        </Space>
      ),
    },
  ];

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

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

      {/* Filters */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <Input
            placeholder="Search by title, name, or email"
            prefix={<SearchOutlined />}
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            onPressEnter={fetchQueue}
            style={{ width: 280 }}
            allowClear
          />
          <Select
            placeholder="Moderation Status"
            value={statusFilter}
            onChange={(v) => { setStatusFilter(v); setPage(1); }}
            allowClear
            style={{ width: 180 }}
            options={[
              { label: 'Pending Review', value: 'PENDING_REVIEW' },
              { label: 'Approved', value: 'APPROVED' },
              { label: 'Rejected', value: 'REJECTED' },
              { label: 'Changes Requested', value: 'CHANGES_REQUESTED' },
            ]}
          />
          <Button icon={<ReloadOutlined />} onClick={() => { fetchQueue(); fetchStats(); }}>
            Refresh
          </Button>
        </Space>
      </Card>

      {/* Table */}
      <Table
        columns={columns}
        dataSource={campaigns}
        rowKey="id"
        loading={loading}
        pagination={{
          current: page,
          total,
          pageSize,
          onChange: setPage,
          showSizeChanger: false,
          showTotal: (t) => `${t} campaigns`,
        }}
        scroll={{ x: 'max-content' }}
      />

      </div>

      {/* Detail Drawer */}
      <Drawer
        title="Campaign Details"
        open={drawerOpen}
        onClose={() => { setDrawerOpen(false); setSelectedCampaign(null); }}
        width={isMobile ? '100%' : 600}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      >
        {selectedCampaign && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ fontSize: 18 }}>{selectedCampaign.title}</Text>
              {selectedCampaign.moderationStatus && (
                <Tag color={CAMPAIGN_MODERATION_STATUS_COLORS[selectedCampaign.moderationStatus]} style={{ marginLeft: 8 }}>
                  {CAMPAIGN_MODERATION_STATUS_LABELS[selectedCampaign.moderationStatus]}
                </Tag>
              )}
            </div>

            {selectedCampaign.description && (
              <div style={{ marginBottom: 16 }}>
                <Text type="secondary">Description</Text>
                <Paragraph>{selectedCampaign.description}</Paragraph>
              </div>
            )}

            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">Government Levels</Text>
              <div style={{ marginTop: 4 }}>
                {selectedCampaign.targetGovernmentLevels.map(l => (
                  <Tag key={l} color={GOVERNMENT_LEVEL_COLORS[l]}>{GOVERNMENT_LEVEL_LABELS[l]}</Tag>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">Creator</Text>
              <div>{selectedCampaign.createdByUserName || 'Unknown'} ({selectedCampaign.createdByUserEmail})</div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">Submitted</Text>
              <div>{dayjs(selectedCampaign.createdAt).format('MMM D, YYYY h:mm A')}</div>
            </div>

            <Card size="small" title="Email Template" style={{ marginBottom: 16 }}>
              <div style={{ marginBottom: 8 }}>
                <Text strong>Subject: </Text>
                <Text>{selectedCampaign.emailSubject}</Text>
              </div>
              <div style={{ whiteSpace: 'pre-wrap', background: '#f5f5f5', padding: 12, borderRadius: 6, maxHeight: 300, overflow: 'auto' }}>
                {selectedCampaign.emailBody}
              </div>
            </Card>

            {selectedCampaign.callToAction && (
              <div style={{ marginBottom: 16 }}>
                <Text type="secondary">Call to Action</Text>
                <Paragraph>{selectedCampaign.callToAction}</Paragraph>
              </div>
            )}

            {selectedCampaign.rejectionReason && (
              <Card size="small" title="Rejection/Change Reason" style={{ marginBottom: 16, borderColor: '#ff4d4f' }}>
                <Text>{selectedCampaign.rejectionReason}</Text>
              </Card>
            )}

            {selectedCampaign.moderationNotes && (
              <div style={{ marginBottom: 16 }}>
                <Text type="secondary">Moderation Notes</Text>
                <Paragraph>{selectedCampaign.moderationNotes}</Paragraph>
              </div>
            )}

            {selectedCampaign.moderationStatus === 'PENDING_REVIEW' && (
              <Space style={{ marginTop: 16 }}>
                <Button
                  type="primary"
                  icon={<CheckCircleOutlined />}
                  style={{ background: '#52c41a', borderColor: '#52c41a' }}
                  onClick={() => handleModerate(selectedCampaign.id, 'approve')}
                  loading={actionLoading}
                >
                  Approve
                </Button>
                <Button
                  danger
                  icon={<CloseCircleOutlined />}
                  onClick={() => openActionModal('reject')}
                >
                  Reject
                </Button>
                <Button
                  icon={<ExclamationCircleOutlined />}
                  onClick={() => openActionModal('request_changes')}
                >
                  Request Changes
                </Button>
              </Space>
            )}
          </div>
        )}
      </Drawer>

      {/* Action Drawer (for rejection reason / change request) */}
      <Drawer
        title={actionType === 'reject' ? 'Reject Campaign' : 'Request Changes'}
        open={actionModalOpen}
        onClose={() => { setActionModalOpen(false); setActionType(null); }}
        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={() => {
              if (selectedCampaign && actionType) {
                handleModerate(selectedCampaign.id, actionType, actionReason, actionNotes);
              }
            }}
          >
            {actionType === 'reject' ? 'Reject' : 'Send Request'}
          </Button>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Text strong style={{ display: 'block', marginBottom: 4 }}>Reason</Text>
          <TextArea
            rows={3}
            value={actionReason}
            onChange={(e) => setActionReason(e.target.value)}
            placeholder={actionType === 'reject' ? 'Why is this campaign being rejected?' : 'What changes are needed?'}
          />
        </div>
        <div>
          <Text strong style={{ display: 'block', marginBottom: 4 }}>Internal Notes (optional)</Text>
          <TextArea
            rows={2}
            value={actionNotes}
            onChange={(e) => setActionNotes(e.target.value)}
            placeholder="Notes for other admins"
          />
        </div>
      </Drawer>
    </>
  );
}
