import { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Button,
  Drawer,
  Form,
  Input,
  Select,
  Tag,
  Space,
  Tabs,
  message,
  Popconfirm,
  InputNumber,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  StopOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import { useMobile } from '@/hooks/useMobile';
import axios from 'axios';

const { TextArea } = Input;

interface Campaign {
  id: string;
  title: string;
}

interface ImpactStory {
  id: string;
  campaignId: string;
  type: 'MILESTONE' | 'VICTORY' | 'RESPONSE' | 'CUSTOM';
  status: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED';
  title: string;
  body: string;
  coverImageUrl: string | null;
  milestoneValue: number | null;
  milestoneMetric: string | null;
  publishedAt: string | null;
  createdAt: string;
  campaign: { title: string };
  createdBy: { name: string | null; email: string } | null;
}

const typeColors: Record<string, string> = {
  MILESTONE: 'gold',
  VICTORY: 'green',
  RESPONSE: 'blue',
  CUSTOM: 'default',
};

const statusColors: Record<string, string> = {
  DRAFT: 'default',
  PUBLISHED: 'green',
  ARCHIVED: 'red',
};

export default function ImpactStoriesPage() {
  const { isMobile } = useMobile();
  const [stories, setStories] = useState<ImpactStory[]>([]);
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });
  const [selectedCampaignId, setSelectedCampaignId] = useState<string | undefined>();
  const [statusFilter, setStatusFilter] = useState<string | undefined>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editingStory, setEditingStory] = useState<ImpactStory | null>(null);
  const [form] = Form.useForm();

  const fetchCampaigns = useCallback(async () => {
    try {
      const { data } = await api.get('/influence/campaigns', { params: { limit: 100 } });
      setCampaigns(data.campaigns || []);
    } catch {
      // ignore
    }
  }, []);

  const fetchStories = useCallback(async (page = 1, limit = 20) => {
    setLoading(true);
    try {
      const params: Record<string, unknown> = { page, limit };
      if (selectedCampaignId) params.campaignId = selectedCampaignId;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get('/social/stories', { params });
      setStories(data.stories || []);
      setPagination({
        current: data.pagination?.page || 1,
        pageSize: data.pagination?.limit || 20,
        total: data.pagination?.total || 0,
      });
    } catch {
      message.error('Failed to load stories');
    } finally {
      setLoading(false);
    }
  }, [selectedCampaignId, statusFilter]);

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

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

  const handleTableChange = (pag: TablePaginationConfig) => {
    fetchStories(pag.current, pag.pageSize);
  };

  const openCreate = () => {
    setEditingStory(null);
    form.resetFields();
    if (selectedCampaignId) {
      form.setFieldsValue({ campaignId: selectedCampaignId });
    }
    setModalOpen(true);
  };

  const openEdit = (story: ImpactStory) => {
    setEditingStory(story);
    form.setFieldsValue({
      campaignId: story.campaignId,
      type: story.type,
      title: story.title,
      body: story.body,
      coverImageUrl: story.coverImageUrl || undefined,
      milestoneValue: story.milestoneValue,
      milestoneMetric: story.milestoneMetric,
    });
    setModalOpen(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      if (editingStory) {
        await api.put(`/social/stories/${editingStory.id}`, values);
        message.success('Story updated');
      } else {
        await api.post('/social/stories', values);
        message.success('Story created');
      }
      setModalOpen(false);
      fetchStories(pagination.current, pagination.pageSize);
    } catch (err: unknown) {
      if (axios.isAxiosError(err) && err.response?.data?.error?.message) {
        message.error(err.response.data.error.message);
      }
    }
  };

  const handlePublish = async (id: string) => {
    try {
      await api.post(`/social/stories/${id}/publish`);
      message.success('Story published and participants notified');
      fetchStories(pagination.current, pagination.pageSize);
    } catch {
      message.error('Failed to publish story');
    }
  };

  const handleArchive = async (id: string) => {
    try {
      await api.post(`/social/stories/${id}/archive`);
      message.success('Story archived');
      fetchStories(pagination.current, pagination.pageSize);
    } catch {
      message.error('Failed to archive story');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/social/stories/${id}`);
      message.success('Story deleted');
      fetchStories(pagination.current, pagination.pageSize);
    } catch {
      message.error('Failed to delete story');
    }
  };

  const storyType = Form.useWatch('type', form);

  const columns: ColumnsType<ImpactStory> = [
    {
      title: 'Title',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: 'Campaign',
      dataIndex: ['campaign', 'title'],
      ellipsis: true,
      responsive: ['md'] as any,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      width: 120,
      render: (type: string) => <Tag color={typeColors[type]}>{type}</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      width: 110,
      render: (status: string) => <Tag color={statusColors[status]}>{status}</Tag>,
    },
    {
      title: 'Milestone',
      dataIndex: 'milestoneValue',
      width: 100,
      responsive: ['lg'] as any,
      render: (val: number | null) => val ? <Tag color="gold">{val}</Tag> : '-',
    },
    {
      title: 'Published',
      dataIndex: 'publishedAt',
      width: 140,
      responsive: ['md'] as any,
      render: (date: string | null) => date ? dayjs(date).format('MMM D, YYYY') : '-',
    },
    {
      title: 'Actions',
      width: 200,
      render: (_: unknown, record: ImpactStory) => (
        <Space size="small">
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)} />
          {record.status === 'DRAFT' && (
            <Popconfirm
              title="Publish this story?"
              description="This will notify campaign participants."
              onConfirm={() => handlePublish(record.id)}
            >
              <Button size="small" type="primary" icon={<CheckCircleOutlined />} />
            </Popconfirm>
          )}
          {record.status === 'PUBLISHED' && (
            <Popconfirm title="Archive this story?" onConfirm={() => handleArchive(record.id)}>
              <Button size="small" icon={<StopOutlined />} />
            </Popconfirm>
          )}
          <Popconfirm title="Delete this story?" onConfirm={() => handleDelete(record.id)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const tabItems = [
    { key: 'all', label: 'All' },
    { key: 'DRAFT', label: 'Draft' },
    { key: 'PUBLISHED', label: 'Published' },
    { key: 'ARCHIVED', label: 'Archived' },
  ];

  const drawerWidth = 540;
  const activeDrawerWidth = !isMobile && modalOpen ? drawerWidth : 0;

  return (
    <>
      <div
        style={{
          marginRight: activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <Space wrap>
            <Select
              placeholder="Filter by campaign"
              allowClear
              style={{ width: 260 }}
              value={selectedCampaignId}
              onChange={(val) => setSelectedCampaignId(val)}
              options={campaigns.map((c) => ({ value: c.id, label: c.title }))}
            />
          </Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            New Story
          </Button>
        </div>

        <Tabs
          activeKey={statusFilter || 'all'}
          onChange={(key) => setStatusFilter(key === 'all' ? undefined : key)}
          items={tabItems}
        />

        <Table
          scroll={{ x: 'max-content' }}
          rowKey="id"
          columns={columns}
          dataSource={stories}
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `${total} stories`,
          }}
          onChange={handleTableChange}
          size="small"
        />
      </div>

      <Drawer
        title={editingStory ? 'Edit Story' : 'Create Story'}
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        placement="right"
        width={isMobile ? '100%' : drawerWidth}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        destroyOnHidden
        extra={
          <Button type="primary" onClick={handleSave}>
            {editingStory ? 'Save' : 'Create'}
          </Button>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="campaignId" label="Campaign" rules={[{ required: true }]}>
            <Select
              placeholder="Select campaign"
              options={campaigns.map((c) => ({ value: c.id, label: c.title }))}
            />
          </Form.Item>
          <Form.Item name="type" label="Type" rules={[{ required: true }]}>
            <Select
              options={[
                { value: 'MILESTONE', label: 'Milestone' },
                { value: 'VICTORY', label: 'Victory' },
                { value: 'RESPONSE', label: 'Response' },
                { value: 'CUSTOM', label: 'Custom' },
              ]}
            />
          </Form.Item>
          <Form.Item name="title" label="Title" rules={[{ required: true, max: 200 }]}>
            <Input />
          </Form.Item>
          <Form.Item name="body" label="Body" rules={[{ required: true, max: 5000 }]}>
            <TextArea rows={5} />
          </Form.Item>
          <Form.Item name="coverImageUrl" label="Cover Image URL">
            <Input placeholder="https://..." />
          </Form.Item>
          {storyType === 'MILESTONE' && (
            <>
              <Form.Item name="milestoneValue" label="Milestone Value">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name="milestoneMetric" label="Milestone Metric">
                <Input placeholder="e.g. emails_sent" />
              </Form.Item>
            </>
          )}
        </Form>
      </Drawer>
    </>
  );
}
