import { useState, useEffect, useCallback } from 'react';
import { Card, Statistic, Row, Col, Button, Space, Tag, message, Popconfirm } from 'antd';
import {
  PauseCircleOutlined,
  PlayCircleOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { QueueStats } from '@/types/api';

export default function EmailQueuePage() {
  const [stats, setStats] = useState<QueueStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  const fetchStats = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<QueueStats>('/email-queue/stats');
      setStats(data);
    } catch {
      message.error('Failed to load queue stats');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 10_000);
    return () => clearInterval(interval);
  }, [fetchStats]);

  const handlePauseResume = useCallback(async () => {
    if (!stats) return;
    setActionLoading(true);
    try {
      const action = stats.paused ? 'resume' : 'pause';
      await api.post(`/email-queue/${action}`);
      message.success(`Queue ${action}d`);
      fetchStats();
    } catch {
      message.error('Action failed');
    } finally {
      setActionLoading(false);
    }
  }, [stats, fetchStats]);

  const handleClean = useCallback(async () => {
    setActionLoading(true);
    try {
      const { data } = await api.post<{ cleaned: number }>('/email-queue/clean');
      message.success(`Cleaned ${data.cleaned} completed jobs`);
      fetchStats();
    } catch {
      message.error('Clean failed');
    } finally {
      setActionLoading(false);
    }
  }, [fetchStats]);

  const { setPageHeader } = useOutletContext<AppOutletContext>();

  useEffect(() => {
    setPageHeader({ title: 'Email Queue' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  return (
    <>
      <Row style={{ marginBottom: 16 }} align="middle">
        <Col flex="auto">
          <Space wrap>
            {stats && (
              <Tag color={stats.paused ? 'orange' : 'green'} style={{ marginInlineEnd: 0 }}>
                {stats.paused ? 'PAUSED' : 'RUNNING'}
              </Tag>
            )}
            <Button icon={<ReloadOutlined />} onClick={fetchStats} loading={loading}>
              Refresh
            </Button>
            <Popconfirm
              title={stats?.paused ? 'Resume email queue?' : 'Pause email queue?'}
              onConfirm={handlePauseResume}
            >
              <Button
                icon={stats?.paused ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
                loading={actionLoading}
              >
                {stats?.paused ? 'Resume' : 'Pause'}
              </Button>
            </Popconfirm>
            <Popconfirm
              title="Clean completed jobs?"
              description="This permanently deletes job records."
              onConfirm={handleClean}
            >
              <Button
                icon={<DeleteOutlined />}
                loading={actionLoading}
              >
                Clean Old Jobs
              </Button>
            </Popconfirm>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Waiting"
              value={stats?.waiting ?? 0}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Active"
              value={stats?.active ?? 0}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Completed"
              value={stats?.completed ?? 0}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Failed"
              value={stats?.failed ?? 0}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>
    </>
  );
}
