'use client';

import { useEffect, useState, useCallback } from 'react';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
import { toast } from 'sonner';

interface Order {
  id: number;
  orderNo: string;
  amount: number;
  planType: string;
  status: string;
  payChannel: string | null;
  transactionId: string | null;
  paidAt: string | null;
  createdAt: string;
  user?: { id: number; nickname: string; phone?: string; email?: string };
}

export default function AdminOrders() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [search, setSearch] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [channelFilter, setChannelFilter] = useState('');
  const [refundModal, setRefundModal] = useState<{ open: boolean; order: Order | null; reason: string; loading: boolean }>({
    open: false, order: null, reason: '', loading: false,
  });

  const token = typeof window !== 'undefined' ? localStorage.getItem('adminToken') : null;

  const loadOrders = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      params.set('page', String(page));
      params.set('pageSize', String(pageSize));
      if (search) params.set('search', search);
      if (statusFilter) params.set('status', statusFilter);
      if (channelFilter) params.set('payChannel', channelFilter);

      const res = await fetch(`${API_BASE}/admin/orders?${params}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setOrders(data.items || []);
        setTotal(data.total || 0);
      }
    } catch {}
    setLoading(false);
  }, [page, pageSize, search, statusFilter, channelFilter, token]);

  useEffect(() => { loadOrders(); }, [loadOrders]);

  function handleSearch() {
    setSearch(searchInput);
    setPage(1);
  }

  function handleRefund(order: Order) {
    setRefundModal({ open: true, order, reason: '用户申请退款', loading: false });
  }

  async function confirmRefund() {
    const order = refundModal.order;
    if (!order) return;
    setRefundModal(prev => ({ ...prev, loading: true }));
    try {
      const res = await fetch(`${API_BASE}/admin/orders/${order.orderNo}/refund`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ amount: order.amount, reason: refundModal.reason }),
      });
      if (res.ok) {
        toast.success('退款成功');
        setRefundModal({ open: false, order: null, reason: '', loading: false });
        loadOrders();
      } else {
        const err = await res.json();
        toast.error(err.message || '退款失败');
      }
    } catch {
      toast.error('退款失败，请重试');
    }
  }

  async function handleSyncOrder(orderNo: string) {
    try {
      const res = await fetch(`${API_BASE}/payment/gateway/sync/${orderNo}`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        if (data.updated) {
          toast.success('订单状态已同步更新为已支付');
        } else {
          toast.info(`状态同步完成：当前状态 ${data.status}`);
        }
        loadOrders();
      } else {
        const err = await res.json();
        toast.error(err.message || '同步失败');
      }
    } catch { toast.error('同步失败，请重试'); }
  }

  async function handleMarkPaid(orderNo: string) {
    if (!confirm('确认要将此订单标记为已支付吗？')) return;
    try {
      const res = await fetch(`${API_BASE}/admin/orders/${orderNo}/mark-paid`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        toast.success('已标记为已支付');
        loadOrders();
      } else {
        const err = await res.json();
        toast.error(err.message || '操作失败');
      }
    } catch {
      toast.error('操作失败');
    }
  }

  const totalPages = Math.ceil(total / pageSize);

  if (loading) return (
    <div className="space-y-4 p-6">
      <Skeleton className="h-8 w-48" />
      <Skeleton className="h-10 w-full" />
      <Skeleton className="h-10 w-full" />
      <Skeleton className="h-10 w-3/4" />
    </div>
  );

  return (
    <>
      <div className="bg-card border-b border-border px-4 py-4">
        <h1 className="text-2xl font-bold text-foreground">订单管理</h1>
      </div>

      <div className="p-6">
        <div className="flex flex-wrap gap-3 mb-4 items-center">
          <div className="flex gap-2">
            <input
              type="text"
              value={searchInput}
              onChange={e => setSearchInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              placeholder="搜索订单号/用户/手机号..."
              className="px-3 py-2 text-sm bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-600"
            />
            <button
              onClick={handleSearch}
              className="px-4 py-2 text-sm bg-brand-600 text-white rounded-lg hover:bg-brand-700"
            >
              搜索
            </button>
          </div>
          <select
            value={statusFilter}
            onChange={e => { setStatusFilter(e.target.value); setPage(1); }}
            className="px-3 py-2 text-sm bg-background border border-border rounded-lg"
          >
            <option value="">全部状态</option>
            <option value="PENDING">待支付</option>
            <option value="PAID">已支付</option>
            <option value="CANCELLED">已取消</option>
            <option value="REFUNDED">已退款</option>
          </select>
          <select
            value={channelFilter}
            onChange={e => { setChannelFilter(e.target.value); setPage(1); }}
            className="px-3 py-2 text-sm bg-background border border-border rounded-lg"
          >
            <option value="">全部渠道</option>
            <option value="wxpay">微信支付</option>
            <option value="alipay">支付宝</option>
          </select>
          <span className="text-sm text-muted-foreground">共 {total} 条</span>
        </div>

        <div className="bg-card rounded-xl border border-border overflow-hidden">
          <table className="w-full">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">订单号</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">用户</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">金额</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">类型</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">渠道</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">状态</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">时间</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {orders.map(order => (
                <tr key={order.id} className="hover:bg-accent/50">
                  <td className="px-6 py-4 text-sm text-foreground font-mono max-w-[160px] truncate" title={order.orderNo}>
                    {order.orderNo}
                  </td>
                  <td className="px-6 py-4 text-sm text-foreground">{order.user?.nickname || '-'}
                    {order.user?.phone && <span className="text-xs text-muted-foreground ml-1">({order.user.phone})</span>}
                  </td>
                  <td className="px-6 py-4 text-sm text-foreground font-medium">¥{order.amount}</td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      order.planType === 'YEARLY' ? 'bg-purple-100 text-purple-700' : 
                      order.planType === 'MONTHLY' ? 'bg-blue-100 text-blue-700' :
                      'bg-muted text-muted-foreground'
                    }`}>
                      {order.planType === 'YEARLY' ? '年卡' : order.planType === 'MONTHLY' ? '月卡' : order.planType}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      order.payChannel === 'alipay'
                        ? 'bg-blue-100 text-blue-700'
                        : order.payChannel === 'wxpay'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-muted text-muted-foreground'
                    }`}>
                      {order.payChannel === 'alipay' ? '支付宝' : order.payChannel === 'wxpay' ? '微信' : '-'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      order.status === 'PAID' ? 'bg-green-100 text-green-700' : 
                      order.status === 'PENDING' ? 'bg-yellow-100 text-yellow-700' :
                      order.status === 'REFUNDED' ? 'bg-red-100 text-red-700' :
                      'bg-muted text-muted-foreground'
                    }`}>
                      {order.status === 'PAID' ? '已支付' : order.status === 'PENDING' ? '待支付' : order.status === 'REFUNDED' ? '已退款' : '已取消'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">
                    {new Date(order.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      {order.status === 'PAID' && (
                        <button onClick={() => handleRefund(order)} className="text-xs text-red-600 hover:text-red-800">
                          退款
                        </button>
                      )}
                      {order.status === 'PENDING' && (
                        <>
                          <button onClick={() => handleSyncOrder(order.orderNo)} className="text-xs text-blue-600 hover:text-blue-800">
                            同步状态
                          </button>
                          <button onClick={() => handleMarkPaid(order.orderNo)} className="text-xs text-green-600 hover:text-green-800">
                            标记已付
                          </button>
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {orders.length === 0 && (
            <div className="text-center py-20 text-muted-foreground">暂无订单数据</div>
          )}

          {totalPages > 1 && (
            <div className="flex items-center justify-between px-6 py-4 border-t border-border">
              <span className="text-sm text-muted-foreground">第 {page}/{totalPages} 页</span>
              <div className="flex gap-2">
                <button
                  disabled={page <= 1}
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  className="px-3 py-1.5 text-sm border border-border rounded-lg disabled:opacity-30 hover:bg-accent"
                >
                  上一页
                </button>
                <button
                  disabled={page >= totalPages}
                  onClick={() => setPage(p => p + 1)}
                  className="px-3 py-1.5 text-sm border border-border rounded-lg disabled:opacity-30 hover:bg-accent"
                >
                  下一页
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {refundModal.open && refundModal.order && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => setRefundModal({ ...refundModal, open: false })}>
          <div className="bg-card rounded-2xl p-6 w-full max-w-md mx-4 shadow-xl border border-border" onClick={e => e.stopPropagation()}>
            <h3 className="text-lg font-semibold text-foreground mb-2">确认退款</h3>
            <p className="text-sm text-muted-foreground mb-4">
              订单号: {refundModal.order.orderNo}<br />
              金额: ¥{refundModal.order.amount}
            </p>
            <div className="mb-4">
              <label className="text-sm text-foreground block mb-1">退款原因</label>
              <input
                type="text"
                value={refundModal.reason}
                onChange={e => setRefundModal(prev => ({ ...prev, reason: e.target.value }))}
                className="w-full px-3 py-2 text-sm bg-background border border-border rounded-lg"
                placeholder="请输入退款原因"
              />
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setRefundModal({ open: false, order: null, reason: '', loading: false })}
                className="flex-1 py-2 text-sm border border-border rounded-xl hover:bg-accent"
              >
                取消
              </button>
              <button
                onClick={confirmRefund}
                disabled={refundModal.loading}
                className="flex-1 py-2 text-sm bg-red-600 text-white rounded-xl hover:bg-red-700 disabled:opacity-50"
              >
                {refundModal.loading ? '处理中...' : '确认退款'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
