import { useState, useEffect, useCallback } from 'react';
import {
  Card, Table, Button, Space, Tag, Typography, Popconfirm, App, Grid,
} from 'antd';
import {
  PlusOutlined, ReloadOutlined, EditOutlined, DeleteOutlined,
  PlayCircleOutlined, PauseCircleOutlined, TrophyOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';

interface ActionCampaignRow {
  id: string;
  slug: string;
  title: string;
  description: string | null;
  rewardText: string | null;
  isActive: boolean;
  startsAt: string | null;
  endsAt: string | null;
  createdAt: string;
  _count?: { steps: number };
  stepCount?: number;
}

export default function ActionCampaignsPage() {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [campaigns, setCampaigns] = useState<ActionCampaignRow[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchCampaigns = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<{ items: ActionCampaignRow[] }>('/admin/action-campaigns');
      setCampaigns(data.items || []);
    } catch {
      message.error('Failed to load action campaigns');
    } finally {
      setLoading(false);
    }
  }, [message]);

  useEffect(() => {
    fetchCampaigns();
  }, [fetchCampaigns]);

  const handleToggleActive = async (row: ActionCampaignRow) => {
    try {
      if (row.isActive) {
        await api.put(`/admin/action-campaigns/${row.id}`, { isActive: false });
        message.success('Campaign deactivated');
      } else {
        await api.post(`/admin/action-campaigns/${row.id}/activate`);
        message.success('Campaign activated');
      }
      fetchCampaigns();
    } catch {
      message.error('Failed to update campaign');
    }
  };

  const handleDelete = async (row: ActionCampaignRow) => {
    try {
      await api.delete(`/admin/action-campaigns/${row.id}`);
      message.success('Campaign deleted');
      fetchCampaigns();
    } catch {
      message.error('Failed to delete campaign');
    }
  };

  const columns: ColumnsType<ActionCampaignRow> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, row) => (
        <div>
          <Typography.Text strong>{title}</Typography.Text>
          {row.description && (
            <div>
              <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {row.description}
              </Typography.Text>
            </div>
          )}
        </div>
      ),
    },
    {
      title: 'Slug',
      dataIndex: 'slug',
      key: 'slug',
      responsive: ['md'],
      render: (slug: string) => <Typography.Text code>{slug}</Typography.Text>,
    },
    {
      title: 'Status',
      key: 'status',
      render: (_, row) =>
        row.isActive ? (
          <Tag color="green">Active</Tag>
        ) : (
          <Tag color="default">Inactive</Tag>
        ),
    },
    {
      title: 'Steps',
      key: 'stepCount',
      render: (_, row) => row.stepCount ?? row._count?.steps ?? 0,
    },
    {
      title: 'Reward',
      dataIndex: 'rewardText',
      key: 'rewardText',
      responsive: ['lg'],
      render: (reward: string | null) =>
        reward ? (
          <Space>
            <TrophyOutlined style={{ color: '#faad14' }} />
            <Typography.Text>{reward}</Typography.Text>
          </Space>
        ) : (
          <Typography.Text type="secondary">None</Typography.Text>
        ),
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      responsive: ['lg'],
      render: (createdAt: string) => dayjs(createdAt).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_, row) => (
        <Space size="small" wrap>
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => navigate(`/app/influence/action-campaigns/${row.id}`)}
          >
            Edit
          </Button>
          <Button
            size="small"
            icon={row.isActive ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
            onClick={() => handleToggleActive(row)}
          >
            {row.isActive ? 'Deactivate' : 'Activate'}
          </Button>
          <Popconfirm
            title="Delete this action campaign?"
            description="This cannot be undone."
            onConfirm={() => handleDelete(row)}
            okText="Delete"
            okButtonProps={{ danger: true }}
          >
            <Button size="small" danger icon={<DeleteOutlined />}>
              Delete
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: isMobile ? 16 : 24 }}>
      <Card
        title="Action Campaigns"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchCampaigns} loading={loading}>
              Refresh
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/app/influence/action-campaigns/new')}
            >
              New Action Campaign
            </Button>
          </Space>
        }
      >
        <Table
          rowKey="id"
          dataSource={campaigns}
          columns={columns}
          loading={loading}
          pagination={{ pageSize: 20 }}
          scroll={{ x: 'max-content' }}
          locale={{ emptyText: 'No action campaigns yet. Create one to get started.' }}
        />
      </Card>
    </div>
  );
}
