import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Badge } from '@/client/components/ui/badge';
import { Skeleton } from '@/client/components/ui/skeleton';
import { Alert, AlertDescription } from '@/client/components/ui/alert';
import { Clock, History, AlertCircle } from 'lucide-react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useAuth } from '@/client/home-shadcn/hooks/AuthProvider';

interface PaymentRecord {
  id: string;
  amount: number;
  count: number;
  status: string;
  createdAt: string;
  expireAt?: string;
  paymentMethod?: string;
  transactionId?: string;
}

interface RechargeRecordsProps {
  userId: number;
}

export default function RechargeRecords({ userId }: RechargeRecordsProps) {
  const { token } = useAuth();
  const [records, setRecords] = useState<PaymentRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchRechargeRecords();
  }, [userId]);

  const fetchRechargeRecords = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 这里应该调用实际的API获取充值记录
      // 暂时使用模拟数据
      const mockRecords: PaymentRecord[] = [
        {
          id: '1',
          amount: 99.9,
          count: 500,
          status: 'completed',
          createdAt: '2024-08-15T10:30:00Z',
          expireAt: '2025-08-15T23:59:59Z',
          paymentMethod: 'alipay',
          transactionId: '202408151030001234'
        },
        {
          id: '2',
          amount: 29.9,
          count: 100,
          status: 'completed',
          createdAt: '2024-08-01T14:20:00Z',
          paymentMethod: 'wechat',
          transactionId: '202408011420005678'
        },
        {
          id: '3',
          amount: 299.9,
          count: 2000,
          status: 'completed',
          createdAt: '2024-07-20T09:15:00Z',
          expireAt: '2025-07-20T23:59:59Z',
          paymentMethod: 'alipay',
          transactionId: '202407200915003210'
        }
      ];

      // 模拟API延迟
      setTimeout(() => {
        setRecords(mockRecords);
        setLoading(false);
      }, 800);
      
    } catch (err) {
      setError('获取充值记录失败，请稍后重试');
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <Badge className="bg-green-100 text-green-800">已完成</Badge>;
      case 'pending':
        return <Badge className="bg-yellow-100 text-yellow-800">处理中</Badge>;
      case 'failed':
        return <Badge className="bg-red-100 text-red-800">失败</Badge>;
      case 'refunded':
        return <Badge className="bg-gray-100 text-gray-800">已退款</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getPaymentMethodText = (method?: string) => {
    switch (method) {
      case 'alipay':
        return '支付宝';
      case 'wechat':
        return '微信支付';
      case 'bank':
        return '银行转账';
      default:
        return '未知方式';
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <Card key={i} className="border-0 shadow-sm">
            <CardContent className="p-4">
              <div className="space-y-2">
                <Skeleton className="h-4 w-1/3" />
                <Skeleton className="h-3 w-1/4" />
                <Skeleton className="h-3 w-1/5" />
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    );
  }

  if (records.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        <History className="h-12 w-12 mx-auto mb-2 text-gray-300" />
        <p>暂无充值记录</p>
        <p className="text-sm text-gray-400 mt-1">您还没有进行过充值</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {records.map((record) => (
        <Card key={record.id} className="border-0 shadow-sm hover:shadow-md transition-shadow">
          <CardContent className="p-4 space-y-3">
            <div className="flex justify-between items-start">
              <div className="flex-1">
                <div className="flex items-center space-x-2 mb-1">
                  <p className="font-semibold text-lg">充值 {record.count} 次</p>
                  {getStatusBadge(record.status)}
                </div>
                <p className="text-sm text-gray-500">
                  {format(new Date(record.createdAt), 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}
                </p>
                <p className="text-sm text-gray-500">
                  支付方式：{getPaymentMethodText(record.paymentMethod)}
                </p>
                {record.transactionId && (
                  <p className="text-xs text-gray-400">
                    订单号：{record.transactionId}
                  </p>
                )}
              </div>
              <div className="text-right">
                <p className="text-xl font-bold text-blue-600">¥{record.amount}</p>
              </div>
            </div>
            
            {record.expireAt && (
              <div className="flex items-center space-x-2 text-sm text-gray-600 bg-blue-50 p-2 rounded">
                <Clock className="h-4 w-4 text-blue-600" />
                <span>有效期至：{format(new Date(record.expireAt), 'yyyy年MM月dd日', { locale: zhCN })}</span>
              </div>
            )}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}