/* eslint-disable react/display-name, react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatTime, formatAmount, Link, Table } from '@blocklet/payment-react';
import { Box, Tab, Tabs, Typography, Chip } from '@mui/material';
import { useRequest } from 'ahooks';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import CustomerLink from '../customer/link';
import SubscriptionDescription from '../subscription/description';
import SubscriptionStatus from '../subscription/status';

interface Props {
  couponId?: string;
  promotionCodeId?: string;
}

// Type guard to ensure at least one ID is provided
function validateProps(props: Props): asserts props is Props & ({ couponId: string } | { promotionCodeId: string }) {
  if ((!props.couponId || props.couponId === '') && (!props.promotionCodeId || props.promotionCodeId === '')) {
    throw new Error('Either couponId or promotionCodeId must be provided');
  }
}

interface PaginationParams {
  page: number;
  pageSize: number;
}

const fetchActiveRedemptions = (
  id: string,
  params: PaginationParams,
  type?: 'customer' | 'subscription',
  entityType: 'coupon' | 'promotion-code' = 'coupon'
): Promise<any> => {
  const query = new URLSearchParams({
    page: params.page.toString(),
    pageSize: params.pageSize.toString(),
  });

  if (type) {
    query.append('type', type);
  }

  const endpoint =
    entityType === 'coupon' ? `/api/coupons/${id}/redemptions` : `/api/promotion-codes/${id}/redemptions`;
  return api.get(`${endpoint}?${query}`).then((res: any) => res.data);
};

export default function ActiveRedemptions({ couponId = '', promotionCodeId = '' }: Props) {
  // Validate props at the beginning
  const props = { couponId, promotionCodeId };
  validateProps(props);
  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const [tabValue, setTabValue] = useState(0);
  const [customerPagination, setCustomerPagination] = useState({ page: 0, pageSize: 10 });
  const [subscriptionPagination, setSubscriptionPagination] = useState({ page: 0, pageSize: 10 });

  // Determine which ID and entity type to use
  const id = couponId && couponId !== '' ? couponId : promotionCodeId!; // Safe to use ! after validation
  const entityType: 'coupon' | 'promotion-code' = couponId && couponId !== '' ? 'coupon' : 'promotion-code';

  // Fetch data based on current tab and pagination
  const currentPagination = tabValue === 0 ? customerPagination : subscriptionPagination;
  const currentType = tabValue === 0 ? 'customer' : 'subscription';

  const { data = { customers: [], subscriptions: [], count: 0 }, loading } = useRequest(
    () =>
      fetchActiveRedemptions(
        id,
        {
          page: currentPagination.page + 1, // API pages start from 1, table pages start from 0
          pageSize: currentPagination.pageSize,
        },
        currentType,
        entityType
      ),
    {
      refreshDeps: [id, currentPagination.page, currentPagination.pageSize, tabValue],
    }
  );

  const handleTabChange = (_: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
    // Reset pagination when switching tabs
    if (newValue === 0) {
      setCustomerPagination({ page: 0, pageSize: 10 });
    } else {
      setSubscriptionPagination({ page: 0, pageSize: 10 });
    }
  };

  const handleCustomerTableChange = ({ page, rowsPerPage }: any) => {
    setCustomerPagination({ page, pageSize: rowsPerPage });
  };

  const handleSubscriptionTableChange = ({ page, rowsPerPage }: any) => {
    setSubscriptionPagination({ page, pageSize: rowsPerPage });
  };

  // Build customer columns dynamically based on entity type
  const buildCustomerColumns = () => {
    const baseColumns = [
      {
        label: t('common.name'),
        name: 'name',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            return <CustomerLink customer={customer} size="small" />;
          },
        },
      },
      {
        label: t('common.email'),
        name: 'email',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            return customer?.email || '—';
          },
        },
      },
      {
        label: t('admin.coupon.usageStats'),
        name: 'usage_stats',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            const stats = customer?.coupon_usage_stats;
            if (!stats) return '—';
            return <Typography variant="body2">{stats.total_discount_records}</Typography>;
          },
        },
      },
    ];

    // Only show promotion codes column when in coupon mode (not in promotion code detail page)
    if (entityType === 'coupon') {
      baseColumns.push({
        label: t('admin.coupon.promotionCodesUsed'),
        name: 'promotion_codes',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            const promoCodes = customer?.coupon_usage_stats?.promotion_codes_used || [];
            const discountRecords = customer?.discount_records || [];

            if (promoCodes.length === 0) return '—';

            // Calculate usage count for each promotion code from actual discount records
            const promoUsageMap = new Map();
            discountRecords.forEach((record: any) => {
              if (record.promotion_code) {
                const key = record.promotion_code.id || record.promotion_code.code;
                promoUsageMap.set(key, (promoUsageMap.get(key) || 0) + 1);
              }
            });

            return (
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, maxWidth: '200px' }}>
                {promoCodes.map((promo: any) => {
                  // Use actual discount record count instead of promo.times_redeemed
                  const actualUsageCount = promoUsageMap.get(promo.id || promo.code) || 0;
                  return (
                    <Chip
                      key={`${promo.id || promo.code}`}
                      label={`${promo.code} (${actualUsageCount})`}
                      size="small"
                      variant="outlined"
                      onClick={() => navigate(`/admin/products/promotion-codes/${promo.id}`)}
                      sx={{
                        cursor: 'pointer',
                        '&:hover': {
                          backgroundColor: 'action.hover',
                        },
                      }}
                    />
                  );
                })}
              </Box>
            );
          },
        },
      });
    }

    // Add total savings and usage period columns
    baseColumns.push(
      {
        label: t('admin.coupon.totalSavings'),
        name: 'total_savings',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            const totalSavingsByCurrency = (customer?.coupon_usage_stats?.total_savings || {}) as Record<
              string,
              { formattedAmount: string }
            >;

            // If no savings data, return dash
            if (Object.keys(totalSavingsByCurrency).length === 0) {
              return <Typography variant="body2">—</Typography>;
            }

            // Display savings by currency
            return (
              <Box>
                {Object.entries(totalSavingsByCurrency).map(([currencyId, value], i) => {
                  if (!value) {
                    return null;
                  }
                  const v = value as any;
                  return (
                    <Typography key={currencyId} variant="body2" sx={{ display: 'inline-flex' }}>
                      {i > 0 && '、'}
                      {formatAmount(v.amount, v.currency?.decimal || 18)} {v.currency?.symbol || ''}
                    </Typography>
                  );
                })}
              </Box>
            );
          },
        },
      },
      {
        label: t('admin.coupon.usagePeriod'),
        name: 'usage_period',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const customer = data.customers?.[index];
            const stats = customer?.coupon_usage_stats;
            if (!stats) return '—';
            return (
              <Box>
                <Typography variant="body2">
                  {t('admin.coupon.firstUsed')}: {formatTime(stats.first_used)}
                </Typography>
                {stats.first_used !== stats.last_used && (
                  <Typography
                    variant="body2"
                    sx={{
                      color: 'text.secondary',
                    }}>
                    {t('admin.coupon.lastUsed')}: {formatTime(stats.last_used)}
                  </Typography>
                )}
              </Box>
            );
          },
        },
      }
    );

    return baseColumns;
  };

  const customerColumns = buildCustomerColumns();

  // Build subscription columns dynamically based on entity type
  const buildSubscriptionColumns = () => {
    const baseColumns = [
      {
        label: t('admin.subscription.product'),
        name: 'id',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            return (
              <Link to={`/admin/billing/${subscription.id}`}>
                <SubscriptionDescription subscription={subscription} />
              </Link>
            );
          },
        },
      },
      {
        label: t('common.status'),
        name: 'status',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            return (
              <Link to={`/admin/billing/${subscription.id}`}>
                <SubscriptionStatus subscription={subscription} />
              </Link>
            );
          },
        },
      },
      {
        label: t('common.customer'),
        name: 'customer_info',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            const customer = subscription?.customer;
            return <CustomerLink customer={customer} size="small" />;
          },
        },
      },
    ];

    // Only show promotion codes column when in coupon mode
    if (entityType === 'coupon') {
      baseColumns.push({
        label: t('admin.coupon.promotionCodesUsed'),
        name: 'promotion_code_info',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            const promoCode = subscription?.discount_info?.promotion_code;
            if (!promoCode) {
              return (
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.directCouponUsage')}
                </Typography>
              );
            }
            return (
              <Box>
                <Chip
                  label={promoCode.code}
                  size="small"
                  variant="outlined"
                  onClick={() => navigate(`/admin/products/promotion-codes/${promoCode.id}`)}
                  sx={{
                    cursor: 'pointer',
                    mb: 0.5,
                    '&:hover': {
                      backgroundColor: 'action.hover',
                    },
                  }}
                />
              </Box>
            );
          },
        },
      });
    }

    // Add total savings, discount info, and created columns
    baseColumns.push(
      {
        label: t('admin.coupon.totalSavings'),
        name: 'total_savings',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            const totalSavingsByCurrency = (subscription?.discount_info?.total_savings || {}) as Record<
              string,
              { formattedAmount: string }
            >;

            // If no savings data, return dash
            if (Object.keys(totalSavingsByCurrency).length === 0) {
              return (
                <Typography variant="body2" sx={{ color: 'text.lighter' }}>
                  —
                </Typography>
              );
            }

            // Display savings by currency
            return (
              <Box>
                {Object.entries(totalSavingsByCurrency).map(([currencyId, value], i) => {
                  if (!value) {
                    return null;
                  }
                  const v = value as any;
                  return (
                    <Typography key={currencyId} variant="body2" sx={{ lineHeight: 1.2 }}>
                      {i > 0 && ', '}
                      {formatAmount(v.amount, v.currency?.decimal || 18)} {v.currency?.symbol || ''}
                    </Typography>
                  );
                })}
              </Box>
            );
          },
        },
      },
      {
        label: t('admin.coupon.discountInfo'),
        name: 'discount_info',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            const discountInfo = subscription?.discount_info;
            if (!discountInfo) return <Typography variant="body2">—</Typography>;

            const couponInfo = discountInfo.coupon_info;
            return (
              <Box>
                <Typography variant="body2">
                  {t('admin.coupon.discountPeriod')}: {formatTime(discountInfo.discount_start * 1000)}
                  {discountInfo.discount_end && ` - ${formatTime(discountInfo.discount_end * 1000)}`}
                </Typography>
                <Typography
                  variant="caption"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.duration')}:{' '}
                  {t(`admin.coupon.couponTermsDuration.${couponInfo.duration}`, {
                    months: couponInfo.duration_in_months,
                  })}
                </Typography>
              </Box>
            );
          },
        },
      },
      {
        label: t('common.created'),
        name: 'created_at',
        options: {
          customBodyRenderLite: (_: string, index: number) => {
            const subscription = data.subscriptions?.[index];
            return formatTime(subscription?.created_at);
          },
        },
      }
    );

    return baseColumns;
  };

  const subscriptionColumns = buildSubscriptionColumns();

  return (
    <Box>
      <Tabs
        value={tabValue}
        onChange={handleTabChange}
        sx={{
          flex: '1 0 auto',
          maxWidth: '100%',
          fontSize: 14,
          borderBottom: 1,
          borderColor: 'divider',
          '.Mui-selected': {
            fontSize: '14px !important',
            color: 'primary.main',
          },
        }}>
        <Tab label={t('admin.coupon.customers')} />
        <Tab label={t('admin.coupon.subscriptions')} />
      </Tabs>
      {tabValue === 0 && (
        <Box sx={{ mt: 2 }}>
          {data.customers?.length > 0 ? (
            <Table
              data={data.customers}
              columns={customerColumns}
              loading={loading}
              toolbar={false}
              options={{
                selectableRows: 'none',
                serverSide: true,
                count: data.count || 0,
                page: customerPagination.page,
                rowsPerPage: customerPagination.pageSize,
                rowsPerPageOptions: [5, 10, 25, 50],
              }}
              onChange={handleCustomerTableChange}
            />
          ) : (
            !loading && (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <Typography
                  variant="h6"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.noCustomersFound')}
                </Typography>
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.noCustomersRedeem')}
                </Typography>
              </Box>
            )
          )}
        </Box>
      )}
      {tabValue === 1 && (
        <Box>
          {data.subscriptions?.length > 0 ? (
            <Table
              data={data.subscriptions}
              columns={subscriptionColumns}
              loading={loading}
              options={{
                selectableRows: 'none',
                serverSide: true,
                count: data.count || 0,
                page: subscriptionPagination.page,
                rowsPerPage: subscriptionPagination.pageSize,
                rowsPerPageOptions: [5, 10, 25, 50],
              }}
              onChange={handleSubscriptionTableChange}
            />
          ) : (
            !loading && (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <Typography
                  variant="h6"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.noSubscriptionsFound')}
                </Typography>
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {t('admin.coupon.noSubscriptionsRedeem')}
                </Typography>
              </Box>
            )
          )}
        </Box>
      )}
    </Box>
  );
}
