import { useEffect, useState } from 'react'
import useStore from '../store.js'

function Borrows() {
  const { borrows, getBorrows, addBorrow, updateBorrow, deleteBorrow, books, getBooks, members, getMembers, authRole, authId, returnBook } = useStore()
  const [showForm, setShowForm] = useState(false)
  const [editingId, setEditingId] = useState(null)
  const [formData, setFormData] = useState({ bookId: '', clientId: '', dueDate: '' })
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    getBorrows()
    getBooks()
    getMembers()
  }, [])

  const handleSubmit = async (e) => {
    e.preventDefault()
    setLoading(true)
    if (editingId) {
      await updateBorrow(editingId, formData.bookId, formData.clientId, formData.dueDate)
    } else {
      await addBorrow(formData.bookId, formData.clientId, formData.dueDate)
    }
    setFormData({ bookId: '', clientId: '', dueDate: '' })
    setShowForm(false)
    setEditingId(null)
    setLoading(false)
  }

  const handleEdit = (borrow) => {
    setFormData({
      bookId: borrow.bookId?._id || borrow.bookId || '',
      clientId: borrow.clientId?._id || borrow.clientId || '',
      dueDate: borrow.dueDate ? new Date(borrow.dueDate).toISOString().split('T')[0] : ''
    })
    setEditingId(borrow._id)
    setShowForm(true)
  }

  const handleDelete = async (id) => {
    if (window.confirm('Are you sure you want to delete this borrow record?')) {
      await deleteBorrow(id)
    }
  }

  const handleReturn = async (borrowId) => {
    if (window.confirm('Are you sure you want to return this book?')) {
      await returnBook(borrowId)
    }
  }

  const handleCancel = () => {
    setFormData({ bookId: '', clientId: '', dueDate: '' })
    setShowForm(false)
    setEditingId(null)
  }

  const isLibrarian = authRole === 'librarian'

  // Filter borrows based on role
  // - Librarians see all borrows
  // - Students see only their own borrows
  const getFilteredBorrows = () => {
    if (isLibrarian) {
      return borrows
    }
    // For students, filter by their user ID
    return borrows.filter(borrow => {
      const clientId = borrow.clientId?._id || borrow.clientId
      return clientId === authId
    })
  }

  const getDueDateStatus = (dueDate) => {
    const now = new Date()
    const due = new Date(dueDate)
    const daysLeft = Math.ceil((due - now) / (1000 * 60 * 60 * 24))
    if (daysLeft < 0) return { label: 'Overdue', color: 'bg-red-100 text-red-700' }
    if (daysLeft === 0) return { label: 'Due Today', color: 'bg-amber-100 text-amber-700' }
    if (daysLeft <= 3) return { label: 'Due Soon', color: 'bg-amber-100 text-amber-700' }
    return { label: 'Active', color: 'bg-green-100 text-green-700' }
  }

  const getMemberName = (borrow) => {
    if (borrow.clientId && typeof borrow.clientId === 'object') {
      return borrow.clientId.username
    }
    return null
  }

  const filteredBorrows = getFilteredBorrows()

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 sticky top-16 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {isLibrarian ? 'Borrow Records' : 'My Borrowed Books'}
              </h1>
              <p className="text-sm text-gray-500 mt-0.5">{filteredBorrows.length} record{filteredBorrows.length !== 1 ? 's' : ''}</p>
            </div>
            {isLibrarian && !showForm && (
              <button
                onClick={() => { setShowForm(true); setEditingId(null); setFormData({ bookId: '', clientId: '', dueDate: '' }); }}
                className="btn-primary flex items-center gap-2 w-fit"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                Add Borrow
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* Form - Only shown to librarians */}
        {showForm && isLibrarian && (
          <div className="card mb-6">
            {/* Card Header */}
            <div className="px-6 pt-6 pb-5 border-b border-gray-100">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${editingId ? 'bg-amber-100' : 'bg-green-100'}`}>
                  <svg className={`w-5 h-5 ${editingId ? 'text-amber-600' : 'text-green-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                  </svg>
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">{editingId ? 'Edit Borrow Record' : 'Add Borrow Record'}</h3>
                  <p className="text-sm text-gray-500">{editingId ? 'Update the record below' : 'Fill in the borrow details below'}</p>
                </div>
              </div>
            </div>
            {/* Card Body */}
            <form onSubmit={handleSubmit} className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                {/* Book */}
                <div className="form-group">
                  <label className="form-label">Book</label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none z-10">
                      <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                      </svg>
                    </div>
                    <select
                      value={formData.bookId}
                      onChange={(e) => setFormData({ ...formData, bookId: e.target.value })}
                      required
                      className="form-select pl-9"
                    >
                      <option value="">Select a book</option>
                      {books.map((book) => (
                        <option key={book._id} value={book._id}>{book.title}</option>
                      ))}
                    </select>
                  </div>
                </div>
                {/* Member */}
                <div className="form-group">
                  <label className="form-label">Member</label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none z-10">
                      <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                      </svg>
                    </div>
                    <select
                      value={formData.clientId}
                      onChange={(e) => setFormData({ ...formData, clientId: e.target.value })}
                      required
                      className="form-select pl-9"
                    >
                      <option value="">Select a member</option>
                      {members.map((member) => (
                        <option key={member._id} value={member._id}>{member.username} ({member.role})</option>
                      ))}
                    </select>
                  </div>
                </div>
                {/* Due Date */}
                <div className="form-group">
                  <label className="form-label">Due Date</label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none z-10">
                      <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                    </div>
                    <input
                      type="date"
                      value={formData.dueDate}
                      onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
                      required
                      className="form-input pl-9"
                    />
                  </div>
                </div>
              </div>
              <div className="flex gap-3 mt-6">
                <button type="submit" disabled={loading} className="btn-primary flex items-center gap-2">
                  {loading ? (
                    <>
                      <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                      </svg>
                      Saving...
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                      {editingId ? 'Update Record' : 'Add Borrow'}
                    </>
                  )}
                </button>
                <button type="button" onClick={handleCancel} className="btn-secondary">
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Table */}
        <div className="card overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Book</th>
                  {isLibrarian && <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Member</th>}
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Borrow Date</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Due Date</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {filteredBorrows.length > 0 ? (
                  filteredBorrows.map((borrow) => {
                    const status = getDueDateStatus(borrow.dueDate)
                    const memberName = getMemberName(borrow)
                    return (
                      <tr key={borrow._id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-5 py-4">
                          <div className="flex items-center gap-3">
                            <div className="w-9 h-9 bg-blue-50 rounded-lg flex items-center justify-center flex-shrink-0">
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                              </svg>
                            </div>
                            <span className="text-sm font-medium text-gray-900">{borrow.bookId?.title || 'N/A'}</span>
                          </div>
                        </td>
                        {isLibrarian && (
                          <td className="px-5 py-4 text-sm text-gray-600">
                            {memberName ? (
                              <span className="font-medium">{memberName}</span>
                            ) : (
                              <span className="text-gray-400 italic">Unknown</span>
                            )}
                          </td>
                        )}
                        <td className="px-5 py-4 text-sm text-gray-600">{borrow.createdAt ? new Date(borrow.createdAt).toLocaleDateString() : 'N/A'}</td>
                        <td className="px-5 py-4 text-sm text-gray-600">{borrow.dueDate ? new Date(borrow.dueDate).toLocaleDateString() : 'N/A'}</td>
                        <td className="px-5 py-4">
                          <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${status.color}`}>
                            {status.label}
                          </span>
                        </td>
                        <td className="px-5 py-4">
                          <div className="flex items-center gap-2">
                            {isLibrarian ? (
                              // Librarian actions
                              <>
                                <button
                                  onClick={() => handleEdit(borrow)}
                                  className="btn-action-edit"
                                  title="Edit"
                                >
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                  </svg>
                                </button>
                                <button
                                  onClick={() => handleDelete(borrow._id)}
                                  className="btn-action-delete"
                                  title="Delete"
                                >
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                  </svg>
                                </button>
                              </>
                            ) : (
                              // Student action - Return Book
                              <button
                                onClick={() => handleReturn(borrow._id)}
                                className="btn-action-return"
                                title="Return Book"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 16v1a2 2 0 01-2 2H3a2 2 0 01-2-2V7a2 2 0 012-2h2m5 0l3 3m0 0l3-3m-3 3V4" />
                                </svg>
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    )
                  })
                ) : (
                  <tr>
                    <td colSpan={isLibrarian ? 6 : 5} className="px-5 py-16 text-center">
                      <div className="w-14 h-14 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                        <svg className="w-7 h-7 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                        </svg>
                      </div>
                      <p className="text-sm font-medium text-gray-700">
                        {isLibrarian ? 'No borrow records found' : 'You have no borrowed books'}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">
                        {isLibrarian ? 'Start by creating a new borrow record' : 'Browse the catalog to borrow books'}
                      </p>
                      {isLibrarian && (
                        <button onClick={() => setShowForm(true)} className="btn-primary mt-4 text-sm">
                          Add First Record
                        </button>
                      )}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Borrows