import { useState, useEffect, useCallback } from 'react';
import {
  Card, Table, Button, Space, Tag, Input, Select, Drawer, Typography, message,
  Statistic, Row, Col, Form, InputNumber, Switch, Grid, Popconfirm,
} from 'antd';
import {
  PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined,
  DeleteOutlined, EyeOutlined, FileTextOutlined,
} 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';
import { VideoPickerModal } from '@/components/media/VideoPickerModal';
import { PhotoPickerModal } from '@/components/media/PhotoPickerModal';
import type { Video } from '@/components/media/VideoPickerModal';
import type { Photo } from '@/components/media/PhotoPickerModal';
import { useSettingsStore } from '@/stores/settings.store';
import type { Petition, PetitionsListResponse, PetitionStatus } from '@/types/api';

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

const STATUS_COLORS: Record<PetitionStatus, string> = {
  DRAFT: 'default',
  ACTIVE: 'green',
  PAUSED: 'orange',
  CLOSED: 'red',
  ARCHIVED: 'purple',
};

export default function PetitionsPage() {
  const navigate = useNavigate();
  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<PetitionStatus | undefined>(undefined);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editingPetition, setEditingPetition] = useState<Petition | null>(null);
  const [saving, setSaving] = useState(false);
  const [campaigns, setCampaigns] = useState<{ id: string; title: string; slug: string }[]>([]);
  const [form] = Form.useForm();
  const { settings: siteSettings } = useSettingsStore();
  const [selectedVideo, setSelectedVideo] = useState<Video | null>(null);
  const [videoPickerOpen, setVideoPickerOpen] = useState(false);
  const [selectedPhoto, setSelectedPhoto] = useState<Photo | null>(null);
  const [photoPickerOpen, setPhotoPickerOpen] = useState(false);

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

  const fetchCampaigns = useCallback(async () => {
    try {
      const { data } = await api.get('/campaigns', { params: { limit: 100, status: 'ACTIVE' } });
      setCampaigns(data.campaigns?.map((c: any) => ({ id: c.id, title: c.title, slug: c.slug })) || []);
    } catch { /* non-critical */ }
  }, []);

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

  const openCreate = () => {
    setEditingPetition(null);
    form.resetFields();
    form.setFieldsValue({
      status: 'DRAFT',
      showProgress: true,
      showSignatureCount: true,
      showSignerNames: true,
      requireName: true,
      requireEmail: true,
      allowComment: true,
    });
    setSelectedVideo(null);
    setSelectedPhoto(null);
    setDrawerOpen(true);
  };

  const openEdit = async (petition: Petition) => {
    try {
      const { data } = await api.get(`/petitions/${petition.id}/admin`);
      setEditingPetition(data);
      form.setFieldsValue(data);
      setSelectedVideo(data.coverVideoId ? { id: data.coverVideoId, title: `Video #${data.coverVideoId}` } as Video : null);
      setSelectedPhoto(data.coverPhoto ? { id: 0, title: 'Current cover', thumbnailUrl: data.coverPhoto } as unknown as Photo : null);
      setDrawerOpen(true);
    } catch {
      message.error('Failed to load petition details');
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);

      const payload = { ...values, coverVideoId: selectedVideo?.id ?? null };

      if (editingPetition) {
        await api.put(`/petitions/${editingPetition.id}`, payload);
        message.success('Petition updated');
      } else {
        await api.post('/petitions', payload);
        message.success('Petition created');
      }

      setDrawerOpen(false);
      fetchPetitions();
    } catch (err: any) {
      if (err?.errorFields) return; // form validation
      message.error('Failed to save petition');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/petitions/${id}`);
      message.success('Petition deleted');
      fetchPetitions();
    } catch {
      message.error('Failed to delete petition');
    }
  };

  const columns: ColumnsType<Petition> = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (title: string, record: Petition) => (
        <Space direction="vertical" size={0}>
          <Text strong>{title}</Text>
          <a href={`/petition/${record.slug}`} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12 }}>/petition/{record.slug}</a>
        </Space>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: PetitionStatus) => (
        <Tag color={STATUS_COLORS[status]}>{status}</Tag>
      ),
    },
    {
      title: 'Signatures',
      key: 'signatures',
      width: 140,
      render: (_: unknown, record: Petition) => {
        const count = record._count.signatures + record.signatureCountOffset;
        const goal = record.signatureGoal;
        if (goal) {
          const pct = Math.min(100, Math.round((count / goal) * 100));
          return (
            <Space direction="vertical" size={0}>
              <Text strong>{count.toLocaleString()} / {goal.toLocaleString()}</Text>
              <div style={{ width: 80, height: 4, background: '#333', borderRadius: 2 }}>
                <div style={{ width: `${pct}%`, height: '100%', background: '#52c41a', borderRadius: 2 }} />
              </div>
            </Space>
          );
        }
        return <Text strong>{count.toLocaleString()}</Text>;
      },
    },
    ...(isMobile ? [] : [{
      title: 'Linked Campaign',
      dataIndex: 'linkedCampaignId',
      key: 'linkedCampaign',
      width: 160,
      render: (_: unknown, record: Petition) => {
        if (!record.linkedCampaignId) return <Text type="secondary">None</Text>;
        const campaign = campaigns.find(c => c.id === record.linkedCampaignId);
        return campaign ? <Tag color="blue">{campaign.title}</Tag> : <Text type="secondary">Unknown</Text>;
      },
    } as any]),
    ...(isMobile ? [] : [{
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 110,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    } as any]),
    {
      title: 'Actions',
      key: 'actions',
      width: 200,
      render: (_: unknown, record: Petition) => (
        <Space wrap size={4}>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>Edit</Button>
          <Button size="small" icon={<EyeOutlined />} onClick={() => navigate(`/app/influence/petitions/${record.id}/signatures`)}>Signatures</Button>
          <Popconfirm title="Delete this petition?" onConfirm={() => handleDelete(record.id)} okText="Delete" okButtonProps={{ danger: true }}>
            <Button size="small" icon={<DeleteOutlined />} danger />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const activeDrawerWidth = !isMobile && drawerOpen ? 600 : 0;

  return (
    <>
      <div
        style={{
          padding: isMobile ? 12 : 24,
          marginRight: activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={8}><Card size="small"><Statistic title="Total" value={total} /></Card></Col>
        <Col xs={8}><Card size="small"><Statistic title="Active" value={petitions.filter(p => p.status === 'ACTIVE').length} valueStyle={{ color: '#52c41a' }} /></Card></Col>
        <Col xs={8}><Card size="small"><Statistic title="Signatures" value={petitions.reduce((sum, p) => sum + p._count.signatures + p.signatureCountOffset, 0)} /></Card></Col>
      </Row>

      <Card
        title={<Space><FileTextOutlined />Petitions</Space>}
        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: 120 }} options={['DRAFT', 'ACTIVE', 'PAUSED', 'CLOSED', 'ARCHIVED'].map(s => ({ label: s, value: s }))} />
            <Button icon={<ReloadOutlined />} onClick={fetchPetitions} />
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>New Petition</Button>
          </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: 700 }}
        />
      </Card>

      </div>

      <Drawer
        title={editingPetition ? 'Edit Petition' : 'New Petition'}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={isMobile ? '100%' : 600}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        extra={
          <Space>
            <Button onClick={() => setDrawerOpen(false)}>Cancel</Button>
            <Button type="primary" loading={saving} onClick={handleSave}>Save</Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="Title" rules={[{ required: true, message: 'Title is required' }]}>
            <Input maxLength={200} />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <TextArea rows={4} maxLength={5000} />
          </Form.Item>
          <Form.Item name="status" label="Status">
            <Select options={['DRAFT', 'ACTIVE', 'PAUSED', 'CLOSED', 'ARCHIVED'].map(s => ({ label: s, value: s }))} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="signatureGoal" label="Signature Goal">
                <InputNumber min={1} style={{ width: '100%' }} placeholder="No goal" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="signatureCountOffset" label="Count Offset">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="linkedCampaignId" label="Link to Campaign (post-sign CTA)">
            <Select
              allowClear
              placeholder="Select a campaign to link..."
              options={campaigns.map(c => ({ label: c.title, value: c.id }))}
            />
          </Form.Item>

          <Form.Item label="Cover Image">
            {selectedPhoto ? (
              <Space>
                <img src={selectedPhoto.thumbnailUrl || form.getFieldValue('coverPhoto')} alt="Cover" style={{ height: 48, borderRadius: 4 }} />
                <Tag color="blue">{selectedPhoto.title || 'Selected'}</Tag>
                <Button size="small" danger onClick={() => { setSelectedPhoto(null); form.setFieldsValue({ coverPhoto: null }); }}>Remove</Button>
              </Space>
            ) : (
              <Space>
                <Button size="small" onClick={() => setPhotoPickerOpen(true)}>Choose from Gallery</Button>
                <Form.Item name="coverPhoto" noStyle>
                  <Input placeholder="or paste URL..." style={{ width: 220 }} />
                </Form.Item>
              </Space>
            )}
          </Form.Item>

          {siteSettings?.enableMediaFeatures !== false && (
            <Form.Item label="Cover Video">
              {selectedVideo ? (
                <Space>
                  <Tag color="blue">Video #{selectedVideo.id}: {selectedVideo.title}</Tag>
                  <Button size="small" danger onClick={() => setSelectedVideo(null)}>Remove</Button>
                </Space>
              ) : (
                <Button size="small" onClick={() => setVideoPickerOpen(true)}>Choose Cover Video</Button>
              )}
            </Form.Item>
          )}

          <Form.Item name="callToAction" label="Call to Action Text">
            <TextArea rows={2} maxLength={2000} />
          </Form.Item>

          <Form.Item name="thankYouMessage" label="Thank You Message (after signing)">
            <TextArea rows={2} maxLength={2000} />
          </Form.Item>

          <Form.Item name="commentLabel" label="Comment Label">
            <Input placeholder="e.g. Why do you support this?" maxLength={200} />
          </Form.Item>

          <Card size="small" title="Form Fields" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={12}><Form.Item name="requireName" label="Require Name" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="requireEmail" label="Require Email" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="requirePostalCode" label="Require Postal Code" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="requirePhone" label="Require Phone" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="allowComment" label="Allow Comments" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="requireEmailConfirmation" label="Email Confirmation" valuePropName="checked"><Switch /></Form.Item></Col>
            </Row>
          </Card>

          <Card size="small" title="Display Options" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={12}><Form.Item name="showProgress" label="Show Progress Bar" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="showSignatureCount" label="Show Signature Count" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="showSignerNames" label="Show Signer Names" valuePropName="checked"><Switch /></Form.Item></Col>
              <Col span={12}><Form.Item name="highlightPetition" label="Highlight Petition" valuePropName="checked"><Switch /></Form.Item></Col>
            </Row>
          </Card>
        </Form>
      </Drawer>

      <VideoPickerModal
        open={videoPickerOpen}
        onClose={() => setVideoPickerOpen(false)}
        onSelect={(video: Video) => {
          setSelectedVideo(video);
          setVideoPickerOpen(false);
        }}
        title="Select Cover Video"
      />

      <PhotoPickerModal
        open={photoPickerOpen}
        onClose={() => setPhotoPickerOpen(false)}
        onSelect={(photo: Photo) => {
          const url = photo.thumbnailUrl || `/media/photos/${photo.id}/file`;
          setSelectedPhoto(photo);
          form.setFieldsValue({ coverPhoto: url });
          setPhotoPickerOpen(false);
        }}
        title="Select Cover Image"
      />
    </>
  );
}
