'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { 
  Search, 
  DollarSign,
  AlertTriangle,
  CheckCircle,
  CreditCard,
  Clock
} from 'lucide-react';
import { FineWithDetails } from '@/lib/types';

// Mock data - replace with actual API
async function fetchFines() {
  // Mock data for demonstration
  return {
    success: true,
    data: [
      {
        fineId: 1,
        fineType: 'overdue',
        amount: '15.00',
        reason: '逾期归还：5天',
        status: 'unpaid',
        createdAt: '2025-01-10',
        student: {
          studentId: 1,
          stuNo: 'S2023001',
          name: '张三',
          department: '计算机科学与技术'
        },
        borrowRecord: {
          borrowId: 1,
          book: {
            title: '深入理解计算机系统',
            isbn: '9787111544937'
          }
        }
      },
      {
        fineId: 2,
        fineType: 'damage',
        amount: '50.00',
        reason: '图书损坏',
        status: 'paid',
        createdAt: '2025-01-08',
        paymentDate: '2025-01-09',
        paymentMethod: 'cash',
        student: {
          studentId: 2,
          stuNo: 'S2023002',
          name: '李四',
          department: '软件工程'
        }
      }
    ]
  };
}

export default function AdminFinesPage() {
  const [statusFilter, setStatusFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');

  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['admin-fines', statusFilter, typeFilter],
    queryFn: fetchFines,
  });

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

  const getStatusBadge = (status: string) => {
    if (status === 'paid') {
      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>
      );
    }
    
    return (
      <span className="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">
        <Clock className="h-3 w-3 mr-1" />
        未缴费
      </span>
    );
  };

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'overdue':
        return '逾期罚款';
      case 'damage':
        return '损坏赔偿';
      case 'lost':
        return '丢失赔偿';
      default:
        return '其他';
    }
  };

  const getTotalUnpaidAmount = () => {
    if (!data?.data) return 0;
    return data.data
      .filter((fine: any) => fine.status === 'unpaid')
      .reduce((total: number, fine: any) => total + parseFloat(fine.amount), 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>

        {/* Statistics */}
        <div className="grid grid-cols-1 md:grid-cols-3 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">
                  {data?.data?.length || 0}
                </p>
              </div>
              <DollarSign 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-red-600">
                  ¥{getTotalUnpaidAmount().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 text-green-600">
                  {data?.data?.filter((fine: any) => fine.status === 'paid').length || 0}
                </p>
              </div>
              <CheckCircle className="h-8 w-8 text-green-600" />
            </div>
          </div>
        </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="unpaid">未缴费</option>
                  <option value="paid">已缴费</option>
                </select>
              </div>
              
              <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={typeFilter}
                  onChange={(e) => setTypeFilter(e.target.value)}
                >
                  <option value="">全部类型</option>
                  <option value="overdue">逾期罚款</option>
                  <option value="damage">损坏赔偿</option>
                  <option value="lost">丢失赔偿</option>
                </select>
              </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>
        ) : (
          <>
            {/* Fines 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((fine: any) => (
                    <tr key={fine.fineId} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {fine.student?.name}
                          </div>
                          <div className="text-sm text-gray-500">
                            学号: {fine.student?.stuNo}
                          </div>
                          <div className="text-sm text-gray-500">
                            {fine.student?.department}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {getTypeLabel(fine.fineType)}
                          </div>
                          <div className="text-sm text-gray-500">
                            {fine.reason}
                          </div>
                          {fine.borrowRecord && (
                            <div className="text-sm text-gray-500">
                              图书: {fine.borrowRecord.book?.title}
                            </div>
                          )}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-lg font-bold text-red-600">
                          ¥{parseFloat(fine.amount).toFixed(2)}
                        </div>
                        <div className="text-sm text-gray-500">
                          {new Date(fine.createdAt).toLocaleDateString('zh-CN')}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {getStatusBadge(fine.status)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {fine.status === 'paid' ? (
                          <div>
                            <div className="text-sm text-gray-900">
                              {new Date(fine.paymentDate).toLocaleDateString('zh-CN')}
                            </div>
                            <div className="text-sm text-gray-500">
                              {fine.paymentMethod === 'cash' ? '现金' : 
                               fine.paymentMethod === 'card' ? '银行卡' : '其他'}
                            </div>
                          </div>
                        ) : (
                          <div className="text-sm text-gray-500">
                            未缴费
                          </div>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        {fine.status === 'unpaid' && (
                          <button
                            onClick={() => {
                              // TODO: Implement payment functionality
                              console.log('Process payment for fine:', fine.fineId);
                            }}
                            className="text-green-600 hover:text-green-900 flex items-center gap-1"
                            title="处理缴费"
                          >
                            <CreditCard className="h-4 w-4" />
                            缴费
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

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