'use client';

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

export default function BookDetailPage() {
  const params = useParams();
  const router = useRouter();
  const bookId = params.id as string;
  const [book, setBook] = useState<Book | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

    if (bookId) {
      fetchBook();
    }
  }, [bookId]);

  const handleDelete = async () => {
    if (!book || !confirm('确定要删除这本书吗？')) return;

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

      if (response.ok) {
        router.push('/admin/books');
      } 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 (!book) {
    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/books/${bookId}/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>

        {/* Book Info Card */}
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Book Cover */}
            <div className="flex flex-col items-center">
              <div className="w-48 h-64 bg-gray-200 rounded-lg flex items-center justify-center mb-4">
                <BookOpen size={48} className="text-gray-400" />
              </div>
              <div className="text-center">
                <div className={`inline-block px-3 py-1 rounded-full text-sm ${
                  book.status === 'normal' 
                    ? 'bg-green-100 text-green-800' 
                    : book.status === 'damaged'
                    ? 'bg-yellow-100 text-yellow-800'
                    : 'bg-red-100 text-red-800'
                }`}>
                  {book.status === 'normal' ? '正常' : book.status === 'damaged' ? '损坏' : '已移除'}
                </div>
              </div>
            </div>

            {/* Book Details */}
            <div className="md:col-span-2 space-y-4">
              <div>
                <h2 className="text-2xl font-bold text-gray-900 mb-2">{book.title}</h2>
                <p className="text-lg text-gray-600">{book.authors.join(', ')}</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">ISBN</label>
                  <p className="text-gray-900">{book.isbn}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">出版社</label>
                  <p className="text-gray-900">{book.publisher}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">分类号</label>
                  <p className="text-gray-900">{book.classificationNo || '-'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">位置</label>
                  <p className="text-gray-900">{book.location}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">出版日期</label>
                  <p className="text-gray-900">
                    {book.publishDate ? new Date(book.publishDate).toLocaleDateString('zh-CN') : '-'}
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">添加时间</label>
                  <p className="text-gray-900">
                    {new Date(book.createdAt).toLocaleDateString('zh-CN')}
                  </p>
                </div>
              </div>

              {book.description && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">描述</label>
                  <p className="text-gray-900 bg-gray-50 p-3 rounded-lg">{book.description}</p>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Borrowing History */}
        <div className="bg-white rounded-lg shadow-sm border p-6 mt-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Calendar size={20} />
            借阅历史
          </h3>
          <div className="text-gray-500 text-center py-8">
            暂无借阅记录
          </div>
        </div>
      </div>
    </div>
  );
}
