import React, { useCallback } from 'react';
import { FormGeneratorTable, type ColumnConfig } from '../../components/FormGenerator/FormGeneratorTable';
import { useAdminSubscriptions } from '../../hooks/useAdminSubscriptions';
import { useConfirm } from '../../hooks/useConfirm';
import api from '../../api';
import styles from './Billing.module.css';

const _TERMINAL_STATUSES = new Set(['EXPIRED']);

const _COLUMNS: ColumnConfig[] = [
  { key: 'mandateName', label: 'Mandant', type: 'text', sortable: true, filterable: true, width: 180 },
  { key: 'planTitle', label: 'Plan', type: 'text', sortable: true, filterable: true, width: 180 },
  { key: 'status', label: 'Status', type: 'text', sortable: true, filterable: true, width: 110 },
  { key: 'recurring', label: 'Wiederkehrend', type: 'boolean', sortable: true, filterable: true, width: 120 },
  { key: 'activeUsers', label: 'User', type: 'number', sortable: true, width: 70 },
  { key: 'activeInstances', label: 'Instanzen', type: 'number', sortable: true, width: 90 },
  { key: 'monthlyRevenueCHF', label: 'Revenue/Mt (CHF)', type: 'number', sortable: true, width: 140 },
  { key: 'startedAt', label: 'Gestartet', type: 'date', sortable: true, filterable: true, width: 130 },
  { key: 'currentPeriodEnd', label: 'Periodenende', type: 'date', sortable: true, filterable: true, width: 130 },
  { key: 'snapshotPricePerUserCHF', label: 'Preis/User', type: 'number', sortable: true, width: 100 },
  { key: 'snapshotPricePerInstanceCHF', label: 'Preis/Instanz', type: 'number', sortable: true, width: 110 },
];

const AdminSubscriptionsPage: React.FC = () => {
  const { confirm, ConfirmDialog } = useConfirm();
  const { data: subscriptions, pagination, loading, refetch } = useAdminSubscriptions();

  const _handleForceCancel = useCallback(async (row: any) => {
    const ok = await confirm(
      `Subscription «${row.planTitle}» für Mandant «${row.mandateName}» sofort kündigen? Dies wird auch auf Stripe sofort storniert.`,
      { confirmLabel: 'Sofort kündigen', cancelLabel: 'Abbrechen', variant: 'danger' },
    );
    if (!ok) return;

    try {
      await api.post('/api/subscription/force-cancel', { subscriptionId: row.id });
      await refetch();
    } catch (err) {
      console.error('Force cancel failed:', err);
    }
  }, [confirm, refetch]);

  return (
    <div className={styles.billingDashboard} style={{ minHeight: 0 }}>
      <header className={styles.pageHeader} style={{ flexShrink: 0 }}>
        <h1>Subscription-Übersicht</h1>
        <p className={styles.subtitle}>Alle Abonnements aller Mandanten</p>
      </header>

      <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
        <FormGeneratorTable
          data={subscriptions}
          columns={_COLUMNS}
          apiEndpoint="/api/subscription/admin/all"
          loading={loading}
          pagination={true}
          pageSize={50}
          selectable={false}
          hookData={{ refetch, pagination }}
          customActions={[
            {
              id: 'forceCancel',
              title: 'Sofort kündigen',
              icon: '✕',
              onClick: (row: any) => _handleForceCancel(row),
              visible: (row: any) => !_TERMINAL_STATUSES.has(row._rawStatus),
            },
          ]}
          emptyMessage="Keine Subscriptions vorhanden."
        />
      </div>

      <ConfirmDialog />
    </div>
  );
};

export default AdminSubscriptionsPage;
