import { useEffect, useMemo, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import {
  createPayment,
  loadOrderDetail,
  loadOrderStatus,
  type OrderDetail,
  type OrderStatus,
  type PaymentCreateResult,
} from '@/services/commerce';
import { getTenantContext } from '@/services/api';
import '../student.css';

function centsToYuan(value?: number | null) {
  return ((value || 0) / 100).toFixed(2);
}

function recordText(record: Record<string, unknown>, keys: string[], fallback = '-') {
  for (const key of keys) {
    const value = record[key];
    if (typeof value === 'string' && value) return value;
    if (typeof value === 'number') return String(value);
  }
  return fallback;
}

function encodeQuery(input: Record<string, string | undefined>) {
  return Object.entries(input)
    .filter(([, value]) => value)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)
    .join('&');
}

function paymentUrl(result?: PaymentCreateResult | null) {
  const params = result?.paymentParams || {};
  const direct = params.url || params.payUrl || params.paymentUrl || params.qrCodeUrl;
  if (typeof direct === 'string' && direct) return direct;
  const gateway = params.gateway;
  const query = params.query;
  if (typeof gateway === 'string' && query && typeof query === 'object' && !Array.isArray(query)) {
    const queryString = encodeQuery(query as Record<string, string | undefined>);
    return queryString ? `${gateway}?${queryString}` : gateway;
  }
  return '';
}

export default function StudentOrderDetailPage() {
  const router = useRouter();
  const orderNo = router.params?.orderNo || '';
  const tenant = getTenantContext();
  const [detail, setDetail] = useState<OrderDetail | null>(null);
  const [status, setStatus] = useState<OrderStatus | null>(null);
  const [payment, setPayment] = useState<PaymentCreateResult | null>(null);
  const [busy, setBusy] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');

  const items = useMemo(() => detail?.items || [], [detail]);
  const payments = useMemo(() => detail?.payments || [], [detail]);
  const redemptions = useMemo(() => detail?.couponRedemptions || [], [detail]);
  const payUrl = paymentUrl(payment);
  const canContinuePay = detail?.status === 'pending' || status?.status === 'pending';

  function reload() {
    if (!orderNo) {
      setError('缺少订单号。');
      return;
    }
    setBusy('load');
    setError('');
    Promise.all([
      loadOrderDetail(orderNo),
      loadOrderStatus(orderNo),
    ])
      .then(([detailPayload, statusPayload]) => {
        setDetail(detailPayload.item || null);
        setStatus(statusPayload.item || null);
      })
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '订单加载失败'))
      .finally(() => setBusy(''));
  }

  useEffect(() => {
    reload();
  }, [orderNo]);

  async function handleContinuePay(provider?: string | null) {
    if (!orderNo) return;
    setBusy('pay');
    setError('');
    setMessage('');
    try {
      const payload = await createPayment({
        orderNo,
        provider: provider || detail?.payProvider || status?.payProvider || 'alipay',
        returnUrl: process.env.TARO_ENV === 'h5' && typeof window !== 'undefined' ? window.location.href : undefined,
        quitUrl: process.env.TARO_ENV === 'h5' && typeof window !== 'undefined' ? window.location.href : undefined,
      });
      const nextPayment = payload.item || null;
      setPayment(nextPayment);
      const url = paymentUrl(nextPayment);
      if (url && process.env.TARO_ENV === 'h5' && typeof window !== 'undefined') {
        window.location.href = url;
      } else if (url) {
        await Taro.setClipboardData({ data: url });
        setMessage('支付链接已复制。');
      } else {
        setMessage(nextPayment?.provider === 'manual' ? '线下支付订单已生成，请联系教务或客服确认。' : '支付参数已生成。');
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '继续支付失败');
    } finally {
      setBusy('');
    }
  }

  async function copyAfterSalesInfo() {
    const serviceText = tenant?.branding?.slogan || tenant?.branding?.brandName || '请联系当前租户客服处理售后';
    await Taro.setClipboardData({
      data: `订单号：${orderNo}\n售后说明：${serviceText}`,
    });
    setMessage('订单售后信息已复制。');
  }

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Order</Text>
          <Text className='student-title'>订单详情</Text>
          <Text className='student-subtitle'>学生端只查看订单和售后入口，退款审核与确认在租户后台完成。</Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateBack()}>返回</Button>
      </View>

      <View className='section-block'>
        <View className='quiet-panel'>
          <View className='amount-row'>
            <Text className='row-meta'>{detail?.orderNo || orderNo}</Text>
            <Text className='status-badge'>{status?.status || detail?.status || '加载中'}</Text>
          </View>
          <Text className='row-main'>{detail?.productName || '会员订单'}</Text>
          <Text className='amount-text'>¥{centsToYuan(detail?.amountCents ?? status?.amountCents)}</Text>
          <Text className='row-meta'>已退金额 ¥{centsToYuan(detail?.refundedAmountCents ?? status?.refundedAmountCents)} · 支付方式 {detail?.payProvider || status?.payProvider || '-'}</Text>
          <Text className='row-meta'>创建时间 {detail?.createdAt || '-'} · 支付时间 {detail?.paidAt || status?.paidAt || '-'}</Text>
          <View className='toolbar wrap checkout-actions'>
            <Button className='secondary-button' loading={busy === 'load'} onClick={reload}>刷新</Button>
            {canContinuePay ? <Button className='primary-button' loading={busy === 'pay'} onClick={() => handleContinuePay(detail?.payProvider)}>继续支付</Button> : null}
            <Button className='secondary-button' onClick={copyAfterSalesInfo}>售后入口</Button>
          </View>
          {payUrl ? <Text className='row-meta break-text'>支付链接：{payUrl}</Text> : null}
        </View>
      </View>

      <View className='section-block'>
        <Text className='section-heading'>订单项目</Text>
        <View className='list-stack'>
          {items.map((item, index) => (
            <View className='list-row' key={recordText(item, ['id', 'itemId'], `item-${index}`)}>
              <Text className='row-main'>{recordText(item, ['name', 'itemType'])}</Text>
              <Text className='row-meta'>数量 {recordText(item, ['quantity'])} · 小计 ¥{centsToYuan(Number(item.totalAmountCents || 0))}</Text>
            </View>
          ))}
        </View>
        {!items.length ? <View className='empty-state'>暂无订单项目。</View> : null}
      </View>

      <View className='section-block'>
        <Text className='section-heading'>支付记录</Text>
        <View className='list-stack'>
          {payments.map((item, index) => (
            <View className='list-row' key={recordText(item, ['id', 'providerTradeNo'], `payment-${index}`)}>
              <Text className='row-main'>{recordText(item, ['provider'])} · {recordText(item, ['status'])}</Text>
              <Text className='row-meta'>{recordText(item, ['method'])} · ¥{centsToYuan(Number(item.amountCents || 0))}</Text>
              <Text className='row-meta'>交易号 {recordText(item, ['providerTradeNo'])}</Text>
            </View>
          ))}
        </View>
        {!payments.length ? <View className='empty-state'>暂无支付记录。</View> : null}
      </View>

      <View className='section-block'>
        <Text className='section-heading'>优惠记录</Text>
        <View className='list-stack'>
          {redemptions.map((item, index) => (
            <View className='list-row' key={recordText(item, ['id', 'couponCode'], `coupon-${index}`)}>
              <Text className='row-main'>{recordText(item, ['couponCode'])}</Text>
              <Text className='row-meta'>{recordText(item, ['status'])} · 抵扣 ¥{centsToYuan(Number(item.discountAppliedCents || 0))}</Text>
            </View>
          ))}
        </View>
        {!redemptions.length ? <View className='empty-state'>暂无优惠记录。</View> : null}
      </View>

      {message ? <Text className='success-text'>{message}</Text> : null}
      {error ? <Text className='error-text'>{error}</Text> : null}
    </View>
  );
}
