import { useState, useEffect, useCallback } from 'react';
import {
  Card, Table, Button, Space, Tag, Input, Select, Typography, message,
  Statistic, Row, Col, Grid, Popconfirm,
} from 'antd';
import {
  SearchOutlined, ReloadOutlined, DownloadOutlined, ArrowLeftOutlined,
  CheckCircleOutlined, CloseCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useParams, useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { Petition, PetitionSignature, PetitionSignatureStatus, PetitionStats } from '@/types/api';

const { Text } = Typography;

const STATUS_COLORS: Record<PetitionSignatureStatus, string> = {
  PENDING_VERIFICATION: 'orange',
  VERIFIED: 'green',
  UNVERIFIED: 'blue',
  REJECTED: 'red',
};

export default function PetitionSignaturesPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [petition, setPetition] = useState<Petition | null>(null);
  const [signatures, setSignatures] = useState<PetitionSignature[]>([]);
  const [stats, setStats] = useState<PetitionStats | null>(null);
  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<string | undefined>(undefined);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const fetchPetition = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get(`/petitions/${id}/admin`);
      setPetition(data);
    } catch {
      message.error('Failed to load petition');
    }
  }, [id]);

  const fetchSignatures = useCallback(async () => {
    if (!id) return;
    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(`/petitions/${id}/signatures`, { params });
      setSignatures(data.signatures);
      setTotal(data.pagination.total);
    } catch {
      message.error('Failed to load signatures');
    } finally {
      setLoading(false);
    }
  }, [id, page, pageSize, search, statusFilter]);

  const fetchStats = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get<PetitionStats>(`/petitions/${id}/stats`);
      setStats(data);
    } catch { /* non-critical */ }
  }, [id]);

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

  const handleBulkAction = async (status: PetitionSignatureStatus) => {
    if (!id || selectedIds.length === 0) return;
    try {
      await api.post(`/petitions/${id}/signatures/bulk-status`, { ids: selectedIds, status });
      message.success(`${selectedIds.length} signatures updated`);
      setSelectedIds([]);
      fetchSignatures();
      fetchStats();
    } catch {
      message.error('Failed to update signatures');
    }
  };

  const handleDelete = async (sigId: string) => {
    if (!id) return;
    try {
      await api.delete(`/petitions/${id}/signatures/${sigId}`);
      message.success('Signature deleted');
      fetchSignatures();
      fetchStats();
    } catch {
      message.error('Failed to delete signature');
    }
  };

  const handleExport = async (format: 'csv' | 'json') => {
    if (!id) return;
    try {
      const { data } = await api.get(`/petitions/${id}/export`, {
        params: { format },
        responseType: format === 'csv' ? 'blob' : 'json',
      });

      const blob = format === 'csv' ? data : new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `petition-signatures.${format}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      message.error('Failed to export signatures');
    }
  };

  const columns: ColumnsType<PetitionSignature> = [
    {
      title: 'Name',
      dataIndex: 'signerName',
      key: 'name',
      ellipsis: true,
      render: (name: string | null, record: PetitionSignature) => (
        <Space direction="vertical" size={0}>
          <Text>{name || <Text type="secondary">Anonymous</Text>}</Text>
          {record.signerEmail && <Text type="secondary" style={{ fontSize: 11 }}>{record.signerEmail}</Text>}
        </Space>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: PetitionSignatureStatus) => (
        <Tag color={STATUS_COLORS[status]}>{status.replace(/_/g, ' ')}</Tag>
      ),
    },
    ...(isMobile ? [] : [{
      title: 'Location',
      key: 'location',
      width: 150,
      render: (_: unknown, record: PetitionSignature) => {
        const parts = [record.geoCity, record.geoRegion, record.geoCountry].filter(Boolean);
        return parts.length ? <Text type="secondary">{parts.join(', ')}</Text> : <Text type="secondary">-</Text>;
      },
    } as any]),
    ...(isMobile ? [] : [{
      title: 'Postal Code',
      dataIndex: 'signerPostalCode',
      key: 'postalCode',
      width: 100,
      render: (v: string | null) => v || '-',
    } as any]),
    ...(isMobile ? [] : [{
      title: 'Comment',
      dataIndex: 'signerComment',
      key: 'comment',
      width: 200,
      ellipsis: true,
      render: (v: string | null) => v || <Text type="secondary">-</Text>,
    } as any]),
    {
      title: 'Date',
      dataIndex: 'createdAt',
      key: 'date',
      width: 100,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 120,
      render: (_: unknown, record: PetitionSignature) => (
        <Space size={4}>
          {record.status !== 'VERIFIED' && (
            <Button size="small" type="link" icon={<CheckCircleOutlined />}
              onClick={async () => {
                await api.patch(`/petitions/${id}/signatures/${record.id}/status`, { status: 'VERIFIED' });
                fetchSignatures(); fetchStats();
              }}
            />
          )}
          {record.status !== 'REJECTED' && (
            <Button size="small" type="link" danger icon={<CloseCircleOutlined />}
              onClick={async () => {
                await api.patch(`/petitions/${id}/signatures/${record.id}/status`, { status: 'REJECTED' });
                fetchSignatures(); fetchStats();
              }}
            />
          )}
          <Popconfirm title="Delete signature?" onConfirm={() => handleDelete(record.id)} okText="Delete" okButtonProps={{ danger: true }}>
            <Button size="small" type="link" danger>Del</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const topCountries = stats ? Object.entries(stats.byCountry).sort((a, b) => b[1] - a[1]).slice(0, 5) : [];

  return (
    <div style={{ padding: isMobile ? 12 : 24 }}>
      <Button icon={<ArrowLeftOutlined />} type="link" onClick={() => navigate('/app/influence/petitions')} style={{ marginBottom: 12, paddingLeft: 0 }}>
        Back to Petitions
      </Button>

      {petition && (
        <Typography.Title level={4} style={{ marginBottom: 16 }}>{petition.title}</Typography.Title>
      )}

      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={8}><Card size="small"><Statistic title="Total" value={stats?.total ?? 0} /></Card></Col>
        <Col xs={8}><Card size="small"><Statistic title="Verified" value={stats?.verified ?? 0} valueStyle={{ color: '#52c41a' }} /></Card></Col>
        <Col xs={8}><Card size="small"><Statistic title="Goal" value={stats?.goal ? `${stats.percentComplete}%` : 'N/A'} /></Card></Col>
      </Row>

      {topCountries.length > 0 && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <Text strong>Top Countries: </Text>
          {topCountries.map(([country, count]) => (
            <Tag key={country}>{country}: {count}</Tag>
          ))}
        </Card>
      )}

      <Card
        title="Signatures"
        extra={
          <Space wrap>
            <Input placeholder="Search..." prefix={<SearchOutlined />} allowClear value={search} onChange={e => { setSearch(e.target.value); setPage(1); }} style={{ width: isMobile ? 120 : 180 }} />
            <Select placeholder="Status" allowClear value={statusFilter} onChange={v => { setStatusFilter(v); setPage(1); }} style={{ width: 140 }}
              options={['PENDING_VERIFICATION', 'VERIFIED', 'UNVERIFIED', 'REJECTED'].map(s => ({ label: s.replace(/_/g, ' '), value: s }))}
            />
            {selectedIds.length > 0 && (
              <>
                <Button size="small" type="primary" onClick={() => handleBulkAction('VERIFIED')}>Approve ({selectedIds.length})</Button>
                <Button size="small" danger onClick={() => handleBulkAction('REJECTED')}>Reject ({selectedIds.length})</Button>
              </>
            )}
            <Button icon={<DownloadOutlined />} onClick={() => handleExport('csv')}>CSV</Button>
            <Button icon={<ReloadOutlined />} onClick={() => { fetchSignatures(); fetchStats(); }} />
          </Space>
        }
      >
        <Table
          dataSource={signatures}
          columns={columns}
          rowKey="id"
          loading={loading}
          rowSelection={{
            selectedRowKeys: selectedIds,
            onChange: (keys) => setSelectedIds(keys as string[]),
          }}
          pagination={{
            current: page,
            pageSize,
            total,
            onChange: setPage,
            showSizeChanger: false,
            size: 'small',
          }}
          size="small"
          scroll={{ x: 700 }}
        />
      </Card>
    </div>
  );
}
