'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { 
  Search, 
  RefreshCw, 
  RotateCcw,
  Calendar,
  AlertTriangle,
  CheckCircle,
  Clock
} from 'lucide-react';
import { BorrowRecordWithDetails } from '@/lib/types';

async function fetchBorrowRecords(params: { status?: string; studentId?: string; page: number; pageSize: number }) {
  const searchParams = new URLSearchParams();
  
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== '') {
      searchParams.append(key, value.toString());
    }
  });

  const response = await fetch(`/api/borrow?${searchParams}`);
  if (!response.ok) {
    throw new Error('Failed to fetch borrow records');
  }
  return response.json();
}

export default function AdminBorrowsPage() {
  const [statusFilter, setStatusFilter] = useState('');
  const [studentIdFilter, setStudentIdFilter] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 20;

  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['admin-borrows', statusFilter, studentIdFilter, page, pageSize],
    queryFn: () => fetchBorrowRecords({ 
      status: statusFilter || undefined, 
      studentId: studentIdFilter || undefined, 
      page, 
      pageSize 
    }),
  });

  const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setPage(1);
    refetch();
  };

  const getStatusBadge = (status: string, dueDate: string) => {
    const isOverdue = new Date(dueDate) < new Date();
    
    if (status === 'returned') {
      return (
        <span className="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
          <CheckCircle className="h-3 w-3 mr-1" />
          已归还
        </span>
      );
    }
    
    if (status === 'overdue' || (status === 'borrowed' && isOverdue)) {
      return (
        <span className="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
          <AlertTriangle className="h-3 w-3 mr-1" />
          逾期
        </span>
      );
    }
    
    return (
      <span className="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
        <Clock className="h-3 w-3 mr-1" />
        借阅中
      </span>
    );
  };

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

  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">借阅管理</h1>
          <p className="text-gray-600">管理图书借阅、归还和续借操作</p>
        </div>

        {/* Search and Filters */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-8">
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  借阅状态
                </label>
                <select
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                >
                  <option value="">全部状态</option>
                  <option value="borrowed">借阅中</option>
                  <option value="returned">已归还</option>
                  <option value="overdue">逾期</option>
                </select>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  学生ID
                </label>
                <input
                  type="text"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="输入学生ID"
                  value={studentIdFilter}
                  onChange={(e) => setStudentIdFilter(e.target.value)}
                />
              </div>
              
              <div className="flex items-end">
                <button
                  type="submit"
                  className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-md flex items-center gap-2 transition-colors"
                >
                  <Search className="h-4 w-4" />
                  搜索
                </button>
              </div>
            </div>
          </form>
        </div>

        {/* Results */}
        {isLoading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">加载中...</p>
          </div>
        ) : error ? (
          <div className="text-center py-12">
            <p className="text-red-600">加载失败，请重试</p>
          </div>
        ) : (
          <>
            {/* Results Header */}
            <div className="flex justify-between items-center mb-6">
              <p className="text-gray-600">
                找到 {data?.data?.length || 0} 条借阅记录
              </p>
            </div>

            {/* Borrow Records Table */}
            <div className="bg-white rounded-lg shadow-md overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      图书信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      学生信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      借阅日期
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      归还日期
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {data?.data?.map((record: BorrowRecordWithDetails) => (
                    <tr key={record.borrowId} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {record.book?.title}
                          </div>
                          <div className="text-sm text-gray-500">
                            ISBN: {record.book?.isbn}
                          </div>
                          <div className="text-sm text-gray-500">
                            作者: {record.book?.authors?.join(', ')}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {record.student?.name}
                          </div>
                          <div className="text-sm text-gray-500">
                            学号: {record.student?.stuNo}
                          </div>
                          <div className="text-sm text-gray-500">
                            {record.student?.department}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-900">
                          {new Date(record.borrowDate).toLocaleDateString('zh-CN')}
                        </div>
                        <div className="text-sm text-gray-500">
                          续借: {record.renewTimes}/2 次
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-900">
                          应还: {new Date(record.dueDate).toLocaleDateString('zh-CN')}
                        </div>
                        {record.returnDate && (
                          <div className="text-sm text-gray-500">
                            实还: {new Date(record.returnDate).toLocaleDateString('zh-CN')}
                          </div>
                        )}
                        {!record.returnDate && getDaysOverdue(record.dueDate) > 0 && (
                          <div className="text-sm text-red-600">
                            逾期 {getDaysOverdue(record.dueDate)} 天
                          </div>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {getStatusBadge(record.status, record.dueDate)}
                        {record.fineAmount && parseFloat(record.fineAmount) > 0 && (
                          <div className="text-sm text-red-600 mt-1">
                            罚款: ¥{parseFloat(record.fineAmount).toFixed(2)}
                          </div>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <div className="flex justify-end space-x-2">
                          {record.status === 'borrowed' && (
                            <>
                              {(record.renewTimes || 0) < 2 && (
                                <button
                                  onClick={() => {
                                    // TODO: Implement renew functionality
                                    console.log('Renew book:', record.borrowId);
                                  }}
                                  className="text-blue-600 hover:text-blue-900 flex items-center gap-1"
                                  title="续借"
                                >
                                  <RefreshCw className="h-4 w-4" />
                                </button>
                              )}
                              <button
                                onClick={() => {
                                  // TODO: Implement return functionality
                                  console.log('Return book:', record.borrowId);
                                }}
                                className="text-green-600 hover:text-green-900 flex items-center gap-1"
                                title="归还"
                              >
                                <RotateCcw className="h-4 w-4" />
                              </button>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* No results */}
            {data?.data?.length === 0 && (
              <div className="text-center py-12">
                <Calendar className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">暂无借阅记录</p>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
