import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import type { TPayoutExpanded } from '@blocklet/payment-types';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { LiteralUnion } from 'type-fest';
import Dialog from '@arcblock/ux/lib/Dialog';
import { Box, Button, Stack, TextField, Typography } from '@mui/material';

import Actions from '../actions';
import ClickBoundary from '../click-boundary';

type Props = {
  data: TPayoutExpanded;
  variant?: LiteralUnion<'compact' | 'normal', string>;
  isCanceledSubscription?: boolean;
};

export default function PayoutActions({ data, variant = 'compact', isCanceledSubscription = false }: Props) {
  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [showRefundDialog, setShowRefundDialog] = useState(false);
  const [refundReason, setRefundReason] = useState('');
  const [refundReasonError, setRefundReasonError] = useState('');

  const MIN_REASON_LENGTH = 5;

  const validateRefundReason = (value: string) => {
    const trimmed = value.trim();
    if (!trimmed) {
      setRefundReasonError(t('admin.payout.refundReasonRequired'));
      return false;
    }
    if (trimmed.length < MIN_REASON_LENGTH) {
      setRefundReasonError(t('admin.payout.refundReasonMinLength', { min: MIN_REASON_LENGTH }));
      return false;
    }
    setRefundReasonError('');
    return true;
  };

  const handleRefundReasonChange = (value: string) => {
    setRefundReason(value);
    if (refundReasonError) {
      validateRefundReason(value);
    }
  };

  const handleRequestRefund = async () => {
    if (!validateRefundReason(refundReason)) {
      return;
    }

    setLoading(true);
    try {
      const { data: refundData } = await api.post(`/api/vendors/refund/${data.id}`, {
        reason: refundReason.trim(),
      });

      if (!refundData.error) {
        Toast.success(t('admin.payout.refundRequested'));
        setShowRefundDialog(false);
        setRefundReason('');
        setRefundReasonError('');
        // Optionally refresh the page or update the UI
        window.location.reload();
      } else {
        throw new Error(refundData.error || 'Failed to request refund');
      }
    } catch (error: any) {
      Toast.error(formatError(error as any));
    } finally {
      setLoading(false);
    }
  };

  const handleCloseDialog = () => {
    setShowRefundDialog(false);
    setRefundReason('');
    setRefundReasonError('');
  };

  const isRefundReasonValid = refundReason.trim().length >= MIN_REASON_LENGTH;

  const actions = [
    {
      label: t('admin.customer.view'),
      handler: () => navigate(`/admin/customers/${data.customer_id}`),
      color: 'primary',
      disabled: false,
    },
  ];

  // Add Request Refund button if payout is paid and has vendor info
  if (isCanceledSubscription && data.status === 'paid' && data.vendor_info?.vendor_id && data.vendor_info?.order_id) {
    actions.push({
      label: t('admin.payout.requestRefund'),
      handler: () => setShowRefundDialog(true),
      color: 'warning',
      disabled: loading || data.metadata?.refund_requested,
    });
  }

  if (variant === 'compact') {
    actions.push({
      label: t('admin.paymentIntent.view'),
      handler: () => navigate(`/admin/payments/${data.id}`),
      color: 'primary',
      disabled: false,
    });
  }

  return (
    <ClickBoundary>
      <Actions variant={variant} actions={actions} />
      <Dialog
        open={showRefundDialog}
        onClose={handleCloseDialog}
        title={t('admin.payout.requestRefund')}
        fullWidth
        actions={
          <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
            <Button onClick={handleCloseDialog} disabled={loading} size="small" variant="outlined">
              {t('common.cancel')}
            </Button>
            <Button
              onClick={handleRequestRefund}
              disabled={loading || !isRefundReasonValid}
              variant="contained"
              color="warning"
              size="small">
              {t('common.confirm')}
            </Button>
          </Box>
        }>
        <Stack spacing={2}>
          <Typography variant="body2" color="text.secondary" sx={{ lineHeight: 1.6 }}>
            {t('admin.payout.confirmRefund')}
          </Typography>
          <TextField
            value={refundReason}
            onChange={(e) => handleRefundReasonChange(e.target.value)}
            onBlur={() => validateRefundReason(refundReason)}
            label={t('admin.payout.refundReason')}
            placeholder={t('admin.payout.refundReasonPlaceholder')}
            multiline
            minRows={4}
            maxRows={8}
            fullWidth
            required
            disabled={loading}
            error={!!refundReasonError}
            helperText={refundReasonError || t('admin.payout.refundReasonHelper', { min: MIN_REASON_LENGTH })}
            slotProps={{ htmlInput: { maxLength: 500 } }}
          />
        </Stack>
      </Dialog>
    </ClickBoundary>
  );
}
