import { useState, useEffect, useCallback } from 'react';
import { Table, Card, Input, Select, Button, Tag, Space, Typography, App, Popconfirm, Drawer, Grid } from 'antd';
import { SearchOutlined, StopOutlined, DownloadOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { UserSubscription, PaginationMeta, AppOutletContext } from '@/types/api';

const { Text } = Typography;

export default function SubscribersPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [subscriptions, setSubscriptions] = useState<UserSubscription[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [pagination, setPagination] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>();
  const [selectedSub, setSelectedSub] = useState<UserSubscription | null>(null);
  const { message } = App.useApp();

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

  const fetchData = useCallback(async (page = 1) => {
    setLoading(true);
    try {
      const params: Record<string, string | number> = { page, limit: 20 };
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;

      const { data: subData } = await api.get('/payments/admin/subscriptions', { params });
      setSubscriptions(subData.subscriptions);
      setPagination(subData.pagination);
    } catch {
      message.error('Failed to load subscribers');
    } finally {
      setLoading(false);
    }
  }, [search, statusFilter, message]);

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

  const handleCancel = async (id: number, immediate: boolean) => {
    try {
      await api.post(`/payments/admin/subscriptions/${id}/cancel`, { immediate });
      message.success('Subscription cancelled');
      fetchData(pagination.page);
    } catch {
      message.error('Failed to cancel subscription');
    }
  };

  const handleExport = async () => {
    try {
      const params: Record<string, string> = {};
      if (search) params.search = search;
      if (statusFilter) params.status = statusFilter;
      const { data } = await api.get('/payments/admin/subscriptions/export', {
        params,
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement('a');
      a.href = url;
      a.download = `subscriptions-${new Date().toISOString().slice(0, 10)}.csv`;
      a.click();
      window.URL.revokeObjectURL(url);
    } catch {
      message.error('Failed to export subscriptions');
    }
  };

  const statusColors: Record<string, string> = {
    active: 'green',
    cancelled: 'red',
    grace_period: 'orange',
    delinquent: 'volcano',
    none: 'default',
    lifetime: 'blue',
  };

  const columns = [
    {
      title: 'User',
      key: 'user',
      render: (_: unknown, r: UserSubscription) => (
        <div>
          <div>{r.user?.name || 'Unknown'}</div>
          <Text type="secondary" style={{ fontSize: 12 }}>{r.user?.email}</Text>
        </div>
      ),
    },
    { title: 'Plan', key: 'plan', render: (_: unknown, r: UserSubscription) => r.plan?.name || `Plan #${r.planId}` },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (s: string) => <Tag color={statusColors[s] || 'default'}>{s}</Tag>,
    },
    {
      title: 'Started',
      dataIndex: 'startDate',
      key: 'start',
      render: (v: string) => new Date(v).toLocaleDateString(),
    },
    {
      title: 'Renews',
      key: 'renews',
      render: (_: unknown, r: UserSubscription) => {
        if (r.cancelAtPeriodEnd) return <Tag color="orange">Cancelling</Tag>;
        return r.currentPeriodEnd ? new Date(r.currentPeriodEnd).toLocaleDateString() : '-';
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, r: UserSubscription) => (
        <Space>
          <Button size="small" onClick={() => setSelectedSub(r)}>Details</Button>
          {r.status === 'active' && (
            <Popconfirm title="Cancel this subscription?" onConfirm={() => handleCancel(r.id, false)}>
              <Button size="small" danger icon={<StopOutlined />}>Cancel</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Space wrap>
          <Input
            placeholder="Search by name or email"
            prefix={<SearchOutlined />}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onPressEnter={() => fetchData(1)}
            style={{ width: 250 }}
          />
          <Select
            placeholder="Status"
            allowClear
            value={statusFilter}
            onChange={(v) => { setStatusFilter(v); }}
            style={{ width: 150 }}
            options={[
              { value: 'active', label: 'Active' },
              { value: 'cancelled', label: 'Cancelled' },
              { value: 'grace_period', label: 'Grace Period' },
              { value: 'delinquent', label: 'Delinquent' },
            ]}
          />
          <Button type="primary" onClick={() => fetchData(1)}>Search</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>Export CSV</Button>
        </Space>
      </Card>

      <Table
        dataSource={subscriptions}
        columns={columns}
        rowKey="id"
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{
          current: pagination.page,
          pageSize: pagination.limit,
          total: pagination.total,
          onChange: (p) => fetchData(p),
        }}
      />

      <Drawer
        title="Subscription Details"
        open={!!selectedSub}
        onClose={() => setSelectedSub(null)}
        width={isMobile ? '100%' : 400}
      >
        {selectedSub && (
          <div>
            <p><strong>User:</strong> {selectedSub.user?.name || selectedSub.user?.email}</p>
            <p><strong>Plan:</strong> {selectedSub.plan?.name}</p>
            <p><strong>Status:</strong> <Tag color={statusColors[selectedSub.status]}>{selectedSub.status}</Tag></p>
            <p><strong>Started:</strong> {new Date(selectedSub.startDate).toLocaleString()}</p>
            <p><strong>Current Period End:</strong> {selectedSub.currentPeriodEnd ? new Date(selectedSub.currentPeriodEnd).toLocaleString() : '-'}</p>
            <p><strong>Cancel at Period End:</strong> {selectedSub.cancelAtPeriodEnd ? 'Yes' : 'No'}</p>
            <p><strong>Stripe Subscription ID:</strong> {selectedSub.stripeSubscriptionId || '-'}</p>
            <p><strong>Stripe Customer ID:</strong> {selectedSub.stripeCustomerId || '-'}</p>
          </div>
        )}
      </Drawer>
    </div>
  );
}
