'use client';

import { useQuery } from '@tanstack/react-query';
import { 
  BookOpen, 
  Calendar, 
  Clock, 
  Star, 
  AlertTriangle,
  RefreshCw,
  Search
} from 'lucide-react';
import Link from 'next/link';

// Mock student data
const mockStudent = {
  stuNo: 'S2023001',
  name: '张三',
  department: '计算机科学与技术',
  currentBorrow: 3,
  maxBorrow: 10,
  totalFines: 5.00,
  accountStatus: 'active'
};

// Mock data fetching functions
async function fetchStudentDashboard() {
  return {
    student: mockStudent,
    currentBorrows: [
      {
        borrowId: 1,
        book: { title: '深入理解计算机系统', authors: ['Randal E. Bryant'] },
        borrowDate: '2025-01-01',
        dueDate: '2025-01-31',
        renewTimes: 0,
        status: 'borrowed'
      },
      {
        borrowId: 2,
        book: { title: 'Python编程实战', authors: ['Mark Lutz'] },
        borrowDate: '2025-01-05',
        dueDate: '2025-02-04',
        renewTimes: 1,
        status: 'borrowed'
      },
      {
        borrowId: 3,
        book: { title: '数据结构与算法', authors: ['Thomas H. Cormen'] },
        borrowDate: '2024-12-20',
        dueDate: '2025-01-19',
        renewTimes: 0,
        status: 'overdue'
      }
    ],
    reservations: [
      {
        reservationId: 1,
        book: { title: '人工智能导论', authors: ['Stuart Russell'] },
        reserveDate: '2025-01-10',
        status: 'waiting'
      }
    ]
  };
}

export default function StudentDashboard() {
  const { data } = useQuery({
    queryKey: ['student-dashboard'],
    queryFn: fetchStudentDashboard,
  });

  const student = data?.student || mockStudent;
  const currentBorrows = data?.currentBorrows || [];
  const reservations = data?.reservations || [];

  const isOverdue = (dueDate: string) => {
    return new Date(dueDate) < new Date();
  };

  const getDaysUntilDue = (dueDate: string) => {
    const today = new Date();
    const due = new Date(dueDate);
    const diffTime = due.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">
            欢迎回来, {student.name}
          </h1>
          <p className="text-gray-600">学号: {student.stuNo} | {student.department}</p>
        </div>

        {/* Account Status */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">当前借阅</p>
                <p className="text-2xl font-bold text-gray-900">
                  {student.currentBorrow}/{student.maxBorrow}
                </p>
              </div>
              <BookOpen className="h-8 w-8 text-blue-600" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">预约数量</p>
                <p className="text-2xl font-bold text-gray-900">
                  {reservations.length}
                </p>
              </div>
              <Clock className="h-8 w-8 text-orange-600" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">未缴罚款</p>
                <p className="text-2xl font-bold text-red-600">
                  ¥{student.totalFines.toFixed(2)}
                </p>
              </div>
              <AlertTriangle className="h-8 w-8 text-red-600" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">账户状态</p>
                <p className={`text-2xl font-bold ${
                  student.accountStatus === 'active' ? 'text-green-600' : 'text-red-600'
                }`}>
                  {student.accountStatus === 'active' ? '正常' : '冻结'}
                </p>
              </div>
              <div className={`h-8 w-8 rounded-full flex items-center justify-center ${
                student.accountStatus === 'active' ? 'bg-green-100' : 'bg-red-100'
              }`}>
                <div className={`h-4 w-4 rounded-full ${
                  student.accountStatus === 'active' ? 'bg-green-600' : 'bg-red-600'
                }`} />
              </div>
            </div>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          <Link
            href="/books"
            className="bg-blue-600 hover:bg-blue-700 text-white p-6 rounded-lg shadow-md transition-colors group"
          >
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold mb-2">图书检索</h3>
                <p className="text-blue-100 text-sm">搜索和浏览图书</p>
              </div>
              <Search className="h-8 w-8 group-hover:scale-110 transition-transform" />
            </div>
          </Link>

          <Link
            href="/student/history"
            className="bg-green-600 hover:bg-green-700 text-white p-6 rounded-lg shadow-md transition-colors group"
          >
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold mb-2">借阅历史</h3>
                <p className="text-green-100 text-sm">查看历史记录</p>
              </div>
              <Calendar className="h-8 w-8 group-hover:scale-110 transition-transform" />
            </div>
          </Link>

          <Link
            href="/student/reviews"
            className="bg-purple-600 hover:bg-purple-700 text-white p-6 rounded-lg shadow-md transition-colors group"
          >
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold mb-2">我的评价</h3>
                <p className="text-purple-100 text-sm">图书评价和推荐</p>
              </div>
              <Star className="h-8 w-8 group-hover:scale-110 transition-transform" />
            </div>
          </Link>
        </div>

        {/* Current Borrows & Reservations */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Current Borrows */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-lg font-semibold mb-4">当前借阅</h3>
            
            {currentBorrows.length === 0 ? (
              <p className="text-gray-500 text-center py-8">暂无借阅图书</p>
            ) : (
              <div className="space-y-4">
                {currentBorrows.map((borrow: {
                  borrowId: number;
                  book: { title: string; authors: string[] };
                  borrowDate: string;
                  dueDate: string;
                  renewTimes: number;
                  status: string;
                }) => (
                  <div key={borrow.borrowId} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex justify-between items-start mb-2">
                      <h4 className="font-medium text-gray-900">{borrow.book.title}</h4>
                      <span className={`px-2 py-1 rounded-full text-xs ${
                        borrow.status === 'overdue' 
                          ? 'bg-red-100 text-red-800' 
                          : isOverdue(borrow.dueDate)
                          ? 'bg-yellow-100 text-yellow-800'
                          : 'bg-green-100 text-green-800'
                      }`}>
                        {borrow.status === 'overdue' ? '逾期' : 
                         isOverdue(borrow.dueDate) ? '即将逾期' : '正常'}
                      </span>
                    </div>
                    
                    <p className="text-sm text-gray-600 mb-2">
                      作者: {borrow.book.authors.join(', ')}
                    </p>
                    
                    <div className="flex justify-between items-center text-sm">
                      <div>
                        <p className="text-gray-500">
                          借阅日期: {new Date(borrow.borrowDate).toLocaleDateString('zh-CN')}
                        </p>
                        <p className={`${isOverdue(borrow.dueDate) ? 'text-red-600' : 'text-gray-500'}`}>
                          到期日期: {new Date(borrow.dueDate).toLocaleDateString('zh-CN')}
                          {!isOverdue(borrow.dueDate) && ` (${getDaysUntilDue(borrow.dueDate)}天后)`}
                        </p>
                        <p className="text-gray-500">
                          续借次数: {borrow.renewTimes}/2
                        </p>
                      </div>
                      
                      {borrow.renewTimes < 2 && borrow.status !== 'overdue' && (
                        <button className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-xs flex items-center gap-1">
                          <RefreshCw className="h-3 w-3" />
                          续借
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Reservations */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-lg font-semibold mb-4">预约图书</h3>
            
            {reservations.length === 0 ? (
              <p className="text-gray-500 text-center py-8">暂无预约图书</p>
            ) : (
              <div className="space-y-4">
                {reservations.map((reservation: {
                  reservationId: number;
                  book: { title: string; authors: string[] };
                  reserveDate: string;
                  status: string;
                }) => (
                  <div key={reservation.reservationId} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex justify-between items-start mb-2">
                      <h4 className="font-medium text-gray-900">{reservation.book.title}</h4>
                      <span className="px-2 py-1 rounded-full text-xs bg-orange-100 text-orange-800">
                        {reservation.status === 'waiting' ? '等待中' : 
                         reservation.status === 'available' ? '可取书' : '已过期'}
                      </span>
                    </div>
                    
                    <p className="text-sm text-gray-600 mb-2">
                      作者: {reservation.book.authors.join(', ')}
                    </p>
                    
                    <p className="text-sm text-gray-500">
                      预约日期: {new Date(reservation.reserveDate).toLocaleDateString('zh-CN')}
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
