import React, { useState, useEffect } from 'react';
import { t } from '@/i18n';
import Taro from '@tarojs/taro';
import { transferCoupon } from '../../services/trading';
import { getMyHoldings } from '../../services/my-coupon';
import type { CouponItem } from '../../services/coupon';
// Taro mini-program component (WeChat / Alipay)

/**
 * E2. 小程序核心页面 - 转赠页
 *
 * 两种转赠方式入口 + 最近联系人 + 转赠记录
 * 底部弹窗：输入ID / 选择券 / 确认转赠
 */

const recentRecipients = [
  { name: 'Alice', contact: 'alice@g***l.com', type: t('transfer_contact_email'), time: '3天前', expired: false },
  { name: 'Bob', contact: '138****1234', type: t('transfer_contact_phone'), time: '12天前', expired: false },
  { name: 'Charlie', contact: 'GNX-USR-7B2E', type: 'ID', time: '30天前', expired: true },
];

const transferHistory = [
  { name: '星巴克 ¥25', to: 'Alice', direction: 'out', time: '3天前' },
  { name: 'Nike ¥80', to: 'Bob', direction: 'in', time: '7天前' },
  { name: 'Walmart ¥50', to: 'Diana', direction: 'out', time: '15天前' },
];

const TransferPage: React.FC = () => {
  const [showInputModal, setShowInputModal] = useState(false);
  const [showSelectModal, setShowSelectModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [recipientInput, setRecipientInput] = useState('');
  const [selectedCouponIndex, setSelectedCouponIndex] = useState(0);
  const [selectableCoupons, setSelectableCoupons] = useState<CouponItem[]>([]);
  const [submitting, setSubmitting] = useState(false);

  // Pre-select coupon from route params if available
  const routeParams = Taro.getCurrentInstance().router?.params || {};
  const preselectedCouponId = routeParams.couponId;
  const preselectedCouponName = routeParams.couponName ? decodeURIComponent(routeParams.couponName) : '';

  useEffect(() => {
    // Load user's transferable coupons
    getMyHoldings({ status: 'active' })
      .then((data) => setSelectableCoupons(data.items.filter((c) => c.isTransferable)))
      .catch(() => {});
  }, []);

  const handleShareCard = () => {
    // WeChat native share via Taro
    Taro.showShareMenu({ withShareTicket: true });
  };

  const handleInputEntry = () => {
    setShowInputModal(true);
  };

  const handlePaste = () => {
    Taro.getClipboardData({
      success: (res) => {
        if (res.data) setRecipientInput(res.data);
      },
    });
  };

  const handleInputConfirm = () => {
    if (!recipientInput.trim()) return;
    setShowInputModal(false);

    // If we have a preselected coupon, skip coupon selection
    if (preselectedCouponId) {
      setShowConfirmModal(true);
    } else {
      setShowSelectModal(true);
    }
  };

  const handleCouponSelect = (index: number) => {
    setSelectedCouponIndex(index);
    setShowSelectModal(false);
    setShowConfirmModal(true);
  };

  const handleConfirmTransfer = () => {
    const couponId = preselectedCouponId || (selectableCoupons[selectedCouponIndex]?.id);
    if (!couponId || submitting) return;

    setSubmitting(true);
    transferCoupon(couponId, { phone: recipientInput.trim() })
      .then(() => {
        setShowConfirmModal(false);
        Taro.showToast({ title: t('transfer_success'), icon: 'success' });
      })
      .catch(() => {})
      .finally(() => setSubmitting(false));
  };

  const handleRecipientTap = (recipient: typeof recentRecipients[0]) => {
    if (recipient.expired) return;
    setRecipientInput(recipient.contact);
    if (preselectedCouponId) {
      setShowConfirmModal(true);
    } else {
      setShowSelectModal(true);
    }
  };

  const getSelectedCouponName = () => {
    if (preselectedCouponId && preselectedCouponName) return preselectedCouponName;
    return selectableCoupons[selectedCouponIndex]?.name || '--';
  };

  return (
    <view className="transfer-page">
      {/* Entry Cards */}
      <view className="entry-row">
        <view className="entry-card entry-card-gradient" onClick={handleShareCard}>
          <text className="entry-icon">🔗</text>
          <text className="entry-title">{t('transfer_share_card')}</text>
          <text className="entry-desc">{t('transfer_share_desc')}</text>
        </view>
        <view className="entry-card entry-card-white" onClick={handleInputEntry}>
          <text className="entry-icon">✏️</text>
          <text className="entry-title">{t('transfer_input')}</text>
          <text className="entry-desc">{t('transfer_input_desc')}</text>
        </view>
      </view>

      {/* Recent Recipients */}
      <view className="section">
        <view className="section-header">
          <text className="section-title">{t('transfer_recent')}</text>
          <text className="section-action">{t('transfer_manage')}</text>
        </view>
        {recentRecipients.map((r, i) => (
          <view
            key={i}
            className={`recipient-item ${r.expired ? 'recipient-expired' : ''}`}
            onClick={() => handleRecipientTap(r)}
          >
            <view className="recipient-avatar">
              <text className="recipient-avatar-text">{r.name[0]}</text>
            </view>
            <view className="recipient-info">
              <view className="recipient-name-row">
                <text className="recipient-name">{r.name}</text>
                <view className="recipient-badge">
                  <text className="recipient-badge-text">{r.type}</text>
                </view>
              </view>
              <text className="recipient-contact">{r.contact}</text>
            </view>
            <view className="recipient-right">
              {r.expired ? (
                <text className="recipient-expired-text">{t('transfer_expired')}</text>
              ) : (
                <view className="recipient-time-row">
                  <text className="recipient-time">{r.time}</text>
                  <text className="recipient-chevron">›</text>
                </view>
              )}
            </view>
          </view>
        ))}
      </view>

      {/* Transfer History */}
      <view className="section">
        <view className="section-header">
          <text className="section-title">{t('transfer_history')}</text>
        </view>
        {transferHistory.map((item, i) => (
          <view key={i} className="history-item">
            <view className={`history-arrow ${item.direction === 'out' ? 'arrow-out' : 'arrow-in'}`}>
              <text className="history-arrow-text">{item.direction === 'out' ? '↑' : '↓'}</text>
            </view>
            <view className="history-info">
              <text className="history-name">{item.name}</text>
              <text className="history-detail">
                {item.direction === 'out' ? `→ ${item.to}` : `← ${item.to}`}
              </text>
            </view>
            <text className="history-time">{item.time}</text>
          </view>
        ))}
      </view>

      {/* Input Modal (Bottom Popup) */}
      {showInputModal && (
        <view className="modal-overlay" onClick={() => setShowInputModal(false)}>
          <view className="modal-sheet" onClick={(e) => e.stopPropagation()}>
            <view className="modal-header">
              <text className="modal-title">{t('transfer_input_recipient')}</text>
              <text className="modal-close" onClick={() => setShowInputModal(false)}>✕</text>
            </view>
            <view className="modal-input-row">
              <input
                className="modal-input"
                placeholder={t('transfer_recipient_hint')}
                value={recipientInput}
                onInput={(e: any) => setRecipientInput(e.detail.value)}
              />
              <view className="modal-paste-btn" onClick={handlePaste}>
                <text className="modal-paste-text">{t('transfer_paste')}</text>
              </view>
            </view>
            <view className="modal-confirm-btn" onClick={handleInputConfirm}>
              <text className="modal-confirm-text">{t('confirm')}</text>
            </view>
          </view>
        </view>
      )}

      {/* Select Coupon Modal */}
      {showSelectModal && (
        <view className="modal-overlay" onClick={() => setShowSelectModal(false)}>
          <view className="modal-sheet modal-sheet-tall" onClick={(e) => e.stopPropagation()}>
            <view className="modal-header">
              <text className="modal-title">{t('transfer_select_coupon')}</text>
              <text className="modal-close" onClick={() => setShowSelectModal(false)}>✕</text>
            </view>
            {selectableCoupons.length === 0 ? (
              <view style={{ textAlign: 'center', padding: '40rpx 0' }}>
                <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('my_coupons_empty') || '暂无可转赠的券'}</text>
              </view>
            ) : (
              selectableCoupons.map((coupon, i) => (
                <view key={coupon.id} className="select-coupon-item" onClick={() => handleCouponSelect(i)}>
                  <view className="select-coupon-icon">
                    <text className="select-coupon-icon-text">🎫</text>
                  </view>
                  <view className="select-coupon-info">
                    <text className="select-coupon-brand">{coupon.brandName || coupon.category}</text>
                    <text className="select-coupon-name">{coupon.name}</text>
                  </view>
                  <text className="select-coupon-price">¥{coupon.currentPrice.toFixed(2)}</text>
                </view>
              ))
            )}
          </view>
        </view>
      )}

      {/* Confirm Modal */}
      {showConfirmModal && (
        <view className="modal-overlay" onClick={() => setShowConfirmModal(false)}>
          <view className="modal-sheet" onClick={(e) => e.stopPropagation()}>
            <view className="modal-header">
              <text className="modal-title">{t('transfer_confirm')}</text>
              <text className="modal-close" onClick={() => setShowConfirmModal(false)}>✕</text>
            </view>

            <view className="confirm-info">
              <view className="confirm-row">
                <text className="confirm-label">{t('transfer_select_coupon')}</text>
                <text className="confirm-value">{getSelectedCouponName()}</text>
              </view>
              <view className="confirm-row">
                <text className="confirm-label">{t('transfer_to')}</text>
                <text className="confirm-value">{recipientInput}</text>
              </view>
            </view>

            <view className="confirm-warning">
              <text className="confirm-warning-icon">⚠️</text>
              <text className="confirm-warning-text">{t('transfer_warning')}</text>
            </view>

            <view className="confirm-buttons">
              <view className="confirm-btn-cancel" onClick={() => setShowConfirmModal(false)}>
                <text className="confirm-btn-cancel-text">{t('cancel')}</text>
              </view>
              <view className="confirm-btn-ok" onClick={handleConfirmTransfer}>
                <text className="confirm-btn-ok-text">{submitting ? (t('loading') || '处理中...') : t('transfer_confirm_btn')}</text>
              </view>
            </view>
          </view>
        </view>
      )}
    </view>
  );
};

export default TransferPage;

/*
CSS (index.scss):

.transfer-page { background: #F8F9FC; min-height: 100vh; padding: 24rpx 32rpx 40rpx; }

.entry-row { display: flex; gap: 20rpx; margin-bottom: 24rpx; }
.entry-card {
  flex: 1; padding: 28rpx 20rpx; border-radius: 16rpx;
  display: flex; flex-direction: column; align-items: center;
}
.entry-card-gradient {
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
}
.entry-card-gradient .entry-title { color: white; }
.entry-card-gradient .entry-desc { color: rgba(255,255,255,0.7); }
.entry-card-white {
  background: white; border: 1rpx solid #F1F3F8;
}
.entry-card-white .entry-title { color: #141723; }
.entry-card-white .entry-desc { color: #A0A8BE; }
.entry-icon { font-size: 40rpx; margin-bottom: 12rpx; }
.entry-title { font-size: 28rpx; font-weight: 600; margin-bottom: 4rpx; }
.entry-desc { font-size: 22rpx; text-align: center; }

.section { margin-bottom: 24rpx; }
.section-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 16rpx;
}
.section-title { font-size: 30rpx; font-weight: 600; color: #141723; }
.section-action { font-size: 24rpx; color: #6C5CE7; }

.recipient-item {
  display: flex; align-items: center;
  background: white; border-radius: 16rpx; padding: 20rpx;
  border: 1rpx solid #F1F3F8; margin-bottom: 12rpx;
}
.recipient-expired { opacity: 0.5; }
.recipient-avatar {
  width: 72rpx; height: 72rpx; border-radius: 50%;
  background: #F3F1FF; display: flex;
  align-items: center; justify-content: center; flex-shrink: 0;
}
.recipient-avatar-text { font-size: 28rpx; font-weight: 700; color: #6C5CE7; }
.recipient-info { flex: 1; margin-left: 16rpx; }
.recipient-name-row { display: flex; align-items: center; }
.recipient-name { font-size: 28rpx; font-weight: 500; color: #141723; }
.recipient-badge {
  margin-left: 8rpx; padding: 2rpx 10rpx;
  background: #F3F1FF; border-radius: 999rpx;
}
.recipient-badge-text { font-size: 20rpx; color: #6C5CE7; }
.recipient-contact { font-size: 24rpx; color: #A0A8BE; margin-top: 4rpx; }
.recipient-right { margin-left: 12rpx; flex-shrink: 0; }
.recipient-expired-text { font-size: 22rpx; color: #A0A8BE; }
.recipient-time-row { display: flex; align-items: center; }
.recipient-time { font-size: 22rpx; color: #A0A8BE; }
.recipient-chevron { font-size: 28rpx; color: #A0A8BE; margin-left: 4rpx; }

.history-item {
  display: flex; align-items: center;
  background: white; border-radius: 16rpx; padding: 20rpx;
  border: 1rpx solid #F1F3F8; margin-bottom: 12rpx;
}
.history-arrow {
  width: 56rpx; height: 56rpx; border-radius: 12rpx;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0; margin-right: 16rpx;
}
.arrow-out { background: #FFF0E6; }
.arrow-in { background: #E6FAF3; }
.history-arrow-text { font-size: 28rpx; font-weight: 700; }
.arrow-out .history-arrow-text { color: #FF8C42; }
.arrow-in .history-arrow-text { color: #00C48C; }
.history-info { flex: 1; }
.history-name { font-size: 28rpx; font-weight: 500; color: #141723; }
.history-detail { font-size: 24rpx; color: #A0A8BE; margin-top: 4rpx; }
.history-time { font-size: 22rpx; color: #A0A8BE; flex-shrink: 0; }

/* Modal Overlay & Sheet */
.modal-overlay {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5); z-index: 1000;
  display: flex; align-items: flex-end; justify-content: center;
}
.modal-sheet {
  width: 100%; background: white; border-radius: 32rpx 32rpx 0 0;
  padding: 32rpx; padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}
.modal-sheet-tall { max-height: 70vh; }
.modal-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 28rpx;
}
.modal-title { font-size: 32rpx; font-weight: 600; color: #141723; }
.modal-close { font-size: 28rpx; color: #A0A8BE; padding: 8rpx; }

.modal-input-row {
  display: flex; align-items: center; gap: 16rpx; margin-bottom: 24rpx;
}
.modal-input {
  flex: 1; height: 80rpx; padding: 0 24rpx;
  background: #F1F3F8; border-radius: 12rpx;
  font-size: 28rpx; color: #141723;
}
.modal-paste-btn {
  padding: 0 24rpx; height: 80rpx; border-radius: 12rpx;
  background: #F3F1FF; display: flex; align-items: center;
}
.modal-paste-text { font-size: 26rpx; color: #6C5CE7; font-weight: 500; }

.modal-confirm-btn {
  height: 88rpx; border-radius: 16rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  display: flex; align-items: center; justify-content: center;
}
.modal-confirm-text { color: white; font-size: 30rpx; font-weight: 600; }

.select-coupon-item {
  display: flex; align-items: center; padding: 20rpx;
  border-bottom: 1rpx solid #F1F3F8;
}
.select-coupon-icon {
  width: 80rpx; height: 80rpx; background: #F3F1FF;
  border-radius: 12rpx; display: flex;
  align-items: center; justify-content: center; flex-shrink: 0;
}
.select-coupon-icon-text { font-size: 32rpx; }
.select-coupon-info { flex: 1; margin-left: 16rpx; }
.select-coupon-brand { font-size: 22rpx; color: #A0A8BE; }
.select-coupon-name { font-size: 28rpx; font-weight: 500; color: #141723; margin-top: 4rpx; }
.select-coupon-price { font-size: 28rpx; font-weight: 700; color: #6C5CE7; flex-shrink: 0; }

.confirm-info {
  background: #F8F9FC; border-radius: 12rpx; padding: 20rpx; margin-bottom: 20rpx;
}
.confirm-row {
  display: flex; justify-content: space-between; padding: 12rpx 0;
}
.confirm-label { font-size: 26rpx; color: #5C6478; }
.confirm-value { font-size: 26rpx; color: #141723; font-weight: 500; }

.confirm-warning {
  display: flex; align-items: center; padding: 16rpx 20rpx;
  background: #FFF8E6; border-radius: 12rpx; margin-bottom: 24rpx;
}
.confirm-warning-icon { font-size: 28rpx; margin-right: 12rpx; }
.confirm-warning-text { font-size: 24rpx; color: #B8860B; }

.confirm-buttons { display: flex; gap: 20rpx; }
.confirm-btn-cancel {
  flex: 1; height: 88rpx; border-radius: 16rpx;
  background: #F1F3F8; display: flex;
  align-items: center; justify-content: center;
}
.confirm-btn-cancel-text { font-size: 28rpx; color: #5C6478; font-weight: 600; }
.confirm-btn-ok {
  flex: 1; height: 88rpx; border-radius: 16rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  display: flex; align-items: center; justify-content: center;
}
.confirm-btn-ok-text { color: white; font-size: 28rpx; font-weight: 600; }
*/
