'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Student } from '@/lib/types';
import { ArrowLeft, Edit, Trash2, User, BookOpen } from 'lucide-react';

export default function StudentDetailPage() {
  const params = useParams();
  const router = useRouter();
  const studentId = params.id as string;
  const [student, setStudent] = useState<Student | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchStudent = async () => {
      try {
        const response = await fetch(`/api/students/${studentId}`);
        if (!response.ok) {
          throw new Error('Failed to fetch student');
        }
        const data = await response.json();
        setStudent(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    };

    if (studentId) {
      fetchStudent();
    }
  }, [studentId]);

  const handleDelete = async () => {
    if (!student || !confirm('确定要删除这个学生账户吗？')) return;

    try {
      const response = await fetch(`/api/students/${studentId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        router.push('/admin/students');
      } else {
        alert('删除失败');
      }
    } catch (error) {
      console.error('Delete error:', error);
      alert('删除失败');
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-lg">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-red-600">错误: {error}</div>
      </div>
    );
  }

  if (!student) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div>未找到学生</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto p-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <button
              onClick={() => router.back()}
              className="flex items-center gap-2 text-gray-600 hover:text-gray-900"
            >
              <ArrowLeft size={20} />
              返回
            </button>
            <h1 className="text-2xl font-bold text-gray-900">学生详情</h1>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => router.push(`/admin/students/${studentId}/edit`)}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              <Edit size={16} />
              编辑
            </button>
            <button
              onClick={handleDelete}
              className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
            >
              <Trash2 size={16} />
              删除
            </button>
          </div>
        </div>

        {/* Student Info Card */}
        <div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Avatar */}
            <div className="flex flex-col items-center">
              <div className="w-32 h-32 bg-gray-200 rounded-full flex items-center justify-center mb-4">
                <User size={48} className="text-gray-400" />
              </div>
              <div className="text-center">
                <div className={`inline-block px-3 py-1 rounded-full text-sm ${
                  student.accountStatus === 'active' 
                    ? 'bg-green-100 text-green-800' 
                    : student.accountStatus === 'frozen'
                    ? 'bg-yellow-100 text-yellow-800'
                    : 'bg-red-100 text-red-800'
                }`}>
                  {student.accountStatus === 'active' ? '正常' : 
                   student.accountStatus === 'frozen' ? '冻结' : '挂失'}
                </div>
              </div>
            </div>

            {/* Student Details */}
            <div className="md:col-span-2 space-y-4">
              <div>
                <h2 className="text-2xl font-bold text-gray-900 mb-2">{student.name}</h2>
                <p className="text-lg text-gray-600">学号: {student.stuNo}</p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">性别</label>
                  <p className="text-gray-900">{student.gender === 'M' ? '男' : student.gender === 'F' ? '女' : '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">院系</label>
                  <p className="text-gray-900">{student.department || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">专业</label>
                  <p className="text-gray-900">{student.major || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">年级</label>
                  <p className="text-gray-900">{student.grade || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">班级</label>
                  <p className="text-gray-900">{student.class || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">电话</label>
                  <p className="text-gray-900">{student.phone || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">邮箱</label>
                  <p className="text-gray-900">{student.email || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">账户状态</label>
                  <p className="text-gray-900">
                    {student.accountStatus === 'active' ? '正常' : 
                     student.accountStatus === 'frozen' ? '冻结' : '挂失'}
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">最大借阅数</label>
                  <p className="text-gray-900">{student.maxBorrow}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">当前借阅数</label>
                  <p className="text-gray-900">{student.currentBorrow}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">注册时间</label>
                  <p className="text-gray-900">
                    {student.createdAt ? new Date(student.createdAt).toLocaleDateString('zh-CN') : '-'}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Borrowing Statistics */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
          <div className="bg-white rounded-lg shadow-sm border 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-blue-600">{student.currentBorrow}</p>
              </div>
              <BookOpen className="h-8 w-8 text-blue-600" />
            </div>
          </div>
          
          <div className="bg-white rounded-lg shadow-sm border 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">{student.maxBorrow - student.currentBorrow}</p>
              </div>
              <BookOpen className="h-8 w-8 text-green-600" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border 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-600">0</p>
              </div>
              <BookOpen className="h-8 w-8 text-gray-600" />
            </div>
          </div>
        </div>

        {/* Recent Activities */}
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">最近活动</h3>
          <div className="text-gray-500 text-center py-8">
            暂无活动记录
          </div>
        </div>
      </div>
    </div>
  );
}
