import { useState, useMemo, useEffect, useCallback } from 'react';
import { Layout, Card, Button, Input, Select, Table, Space, Typography, Breadcrumb, Modal, Form, DatePicker, InputNumber, Drawer, Tag, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';

interface BookAuthorResponse {
  id: string;
  name: string;
}

interface BookResponse {
  id: string;
  title: string;
  isbn?: string;
  book_authors: BookAuthorResponse[];
}

interface AuthorResponse {
  id: string;
  name: string;
}

interface CategoryResponse {
  id: string;
  name: string;
  description?: string | null;
  parent_category_id?: string | null;
  created_at: string;
  updated_at: string;
}

interface LibraryBranchResponse {
  id: string;
  name?: string;
  address?: string;
  phone?: string | null;
  email?: string | null;
  operating_hours?: string | null;
  created_at: string;
  updated_at: string;
}

type ConditionStatus = 'EXCELLENT' | 'GOOD' | 'FAIR' | 'POOR' | 'DAMAGED' | 'LOST';
type AvailabilityStatus = 'AVAILABLE' | 'CHECKED_OUT' | 'RESERVED' | 'IN_TRANSIT' | 'MAINTENANCE' | 'LOST';

interface BookCopyResponse {
  id: string;
  book_id: string;
  barcode?: string;
  library_branch_id: string;
  condition_status: ConditionStatus;
  availability_status: AvailabilityStatus;
  acquisition_date?: string | null;
  physical_location?: string | null;
  created_at: string;
  updated_at: string;
}

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

export default function BookManagementPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();

  const [books, setBooks] = useState<BookResponse[]>([]);
  const [authors, setAuthors] = useState<AuthorResponse[]>([]);
  const [categories, setCategories] = useState<CategoryResponse[]>([]);
  const [branches, setBranches] = useState<LibraryBranchResponse[]>([]);
  const [bookCopies, setBookCopies] = useState<BookCopyResponse[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const [filterCategory, setFilterCategory] = useState<string | null>(null);
  const [filterAuthor, setFilterAuthor] = useState<string | null>(null);
  const [filterStatus, setFilterStatus] = useState<string | null>(null);
  const [filterBranch, setFilterBranch] = useState<string | null>(null);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [addBookModalVisible, setAddBookModalVisible] = useState<boolean>(false);
  const [editBookModalVisible, setEditBookModalVisible] = useState<boolean>(false);
  const [manageCopiesDrawerVisible, setManageCopiesDrawerVisible] = useState<boolean>(false);
  const [addCopyModalVisible, setAddCopyModalVisible] = useState<boolean>(false);
  const [editCopyModalVisible, setEditCopyModalVisible] = useState<boolean>(false);
  const [selectedBookId, setSelectedBookId] = useState<string | null>(null);
  const [selectedCopyId, setSelectedCopyId] = useState<string | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [copiesLoading, setCopiesLoading] = useState<boolean>(false);

  const [addBookForm] = Form.useForm();
  const [editBookForm] = Form.useForm();
  const [addCopyForm] = Form.useForm();
  const [editCopyForm] = Form.useForm();

  const totalBooks = useMemo(() => pagination.total, [pagination.total]);

  const fetchBooks = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await request<BookResponse[]>({
        method: 'GET',
        path: '/catalog/books',
        query: {
          limit: pagination.pageSize,
          offset: (pagination.current - 1) * pagination.pageSize,
          search: searchText || undefined,
        },
      });
      setBooks(data);
      setPagination((prev) => ({ ...prev, total: data.length }));
    } catch (error) {
      messageApi.error('Failed to load books');
    } finally {
      setLoading(false);
    }
  }, [pagination.pageSize, pagination.current, searchText, messageApi]);

  const fetchAuthors = useCallback(async () => {
    try {
      const { data } = await request<AuthorResponse[]>({
        method: 'GET',
        path: '/catalog/authors',
        query: { limit: 100 },
      });
      setAuthors(data);
    } catch (error) {
      messageApi.error('Failed to load authors');
    }
  }, [messageApi]);

  const fetchCategories = useCallback(async () => {
    try {
      const { data } = await request<CategoryResponse[]>({
        method: 'GET',
        path: '/catalog/categories',
        query: { limit: 100 },
      });
      setCategories(data);
    } catch (error) {
      messageApi.error('Failed to load categories');
    }
  }, [messageApi]);

  const fetchBranches = useCallback(async () => {
    try {
      const { data } = await request<LibraryBranchResponse[]>({
        method: 'GET',
        path: '/library-branches/',
        query: { limit: 50 },
      });
      setBranches(data);
    } catch (error) {
      messageApi.error('Failed to load branches');
    }
  }, [messageApi]);

  useEffect(() => {
    fetchBooks();
    fetchAuthors();
    fetchCategories();
    fetchBranches();
  }, [fetchBooks, fetchAuthors, fetchCategories, fetchBranches]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchBooks();
    }, 300);
    return () => clearTimeout(timer);
  }, [searchText, fetchBooks]);

  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination((prev) => ({ ...prev, current: page, pageSize }));
  };

  const openAddBookModal = () => {
    setAddBookModalVisible(true);
  };

  const closeAddBookModal = () => {
    setAddBookModalVisible(false);
    addBookForm.resetFields();
  };

  const openEditBookModal = (record: BookResponse) => {
    setEditBookModalVisible(true);
    setSelectedBookId(record.id);
    editBookForm.setFieldsValue(record);
  };

  const closeEditBookModal = () => {
    setEditBookModalVisible(false);
    setSelectedBookId(null);
    editBookForm.resetFields();
  };

  const openManageCopiesDrawer = async (record: BookResponse) => {
    setManageCopiesDrawerVisible(true);
    setSelectedBookId(record.id);
    setCopiesLoading(true);
    try {
      const { data } = await request<BookCopyResponse[]>({
        method: 'GET',
        path: '/catalog/book-copies',
        query: {
          book_id: record.id,
          limit: 50,
        },
      });
      setBookCopies(data);
    } catch (error) {
      messageApi.error('Failed to load copies.');
    } finally {
      setCopiesLoading(false);
    }
  };

  const closeManageCopiesDrawer = () => {
    setManageCopiesDrawerVisible(false);
    setSelectedBookId(null);
    setBookCopies([]);
  };

  const openAddCopyModal = () => {
    setAddCopyModalVisible(true);
  };

  const closeAddCopyModal = () => {
    setAddCopyModalVisible(false);
    addCopyForm.resetFields();
  };

  const openEditCopyModal = (record: BookCopyResponse) => {
    setEditCopyModalVisible(true);
    setSelectedCopyId(record.id);
    editCopyForm.setFieldsValue(record);
  };

  const closeEditCopyModal = () => {
    setEditCopyModalVisible(false);
    setSelectedCopyId(null);
    editCopyForm.resetFields();
  };

  const handleAddBook = async () => {
    try {
      const formValues = await addBookForm.validateFields();
      setLoading(true);
      await request<BookResponse>({
        method: 'POST',
        path: '/catalog/books',
        body: {
          isbn: formValues.isbn,
          title: formValues.title,
          publisher: formValues.publisher,
          publication_date: formValues.publication_date,
          edition: formValues.edition,
          number_of_pages: formValues.number_of_pages,
          language: formValues.language,
          description: formValues.description,
          cover_image_url: formValues.cover_image_url,
        },
      });
      messageApi.success('Book added successfully!');
      closeAddBookModal();
      fetchBooks();
    } catch (error) {
      messageApi.error('Failed to add book. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleEditBook = async () => {
    try {
      const formValues = await editBookForm.validateFields();
      setLoading(true);
      await request<BookResponse>({
        method: 'PUT',
        path: '/catalog/books/{book_id}',
        pathParams: { book_id: selectedBookId! },
        body: {
          isbn: formValues.isbn,
          title: formValues.title,
          publisher: formValues.publisher,
          publication_date: formValues.publication_date,
          edition: formValues.edition,
          number_of_pages: formValues.number_of_pages,
          language: formValues.language,
          description: formValues.description,
          cover_image_url: formValues.cover_image_url,
        },
      });
      messageApi.success('Book updated successfully!');
      closeEditBookModal();
      fetchBooks();
    } catch (error) {
      messageApi.error('Failed to update book. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleDeactivateBook = (record: BookResponse) => {
    Modal.confirm({
      title: 'Are you sure you want to deactivate this book?',
      onOk: async () => {
        setLoading(true);
        try {
          await request({
            method: 'DELETE',
            path: '/catalog/books/{book_id}',
            pathParams: { book_id: record.id },
          });
          messageApi.success('Book deactivated successfully!');
          fetchBooks();
        } catch (error) {
          messageApi.error('Failed to deactivate book.');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  const handleAddCopy = async () => {
    try {
      const formValues = await addCopyForm.validateFields();
      setCopiesLoading(true);
      await request<BookCopyResponse>({
        method: 'POST',
        path: '/catalog/book-copies',
        body: {
          book_id: selectedBookId!,
          barcode: formValues.barcode,
          library_branch_id: formValues.library_branch_id,
          condition_status: formValues.condition_status,
          availability_status: formValues.availability_status || 'AVAILABLE',
          acquisition_date: formValues.acquisition_date,
          physical_location: formValues.physical_location,
        },
      });
      messageApi.success('Copy added successfully!');
      closeAddCopyModal();
      const { data } = await request<BookCopyResponse[]>({
        method: 'GET',
        path: '/catalog/book-copies',
        query: {
          book_id: selectedBookId!,
          limit: 50,
        },
      });
      setBookCopies(data);
    } catch (error) {
      messageApi.error('Failed to add copy.');
    } finally {
      setCopiesLoading(false);
    }
  };

  const handleEditCopy = async () => {
    try {
      const formValues = await editCopyForm.validateFields();
      setCopiesLoading(true);
      await request<BookCopyResponse>({
        method: 'PUT',
        path: '/catalog/book-copies/{bookcopy_id}',
        pathParams: { bookcopy_id: selectedCopyId! },
        body: {
          barcode: formValues.barcode,
          library_branch_id: formValues.library_branch_id,
          condition_status: formValues.condition_status,
          availability_status: formValues.availability_status,
          physical_location: formValues.physical_location,
        },
      });
      messageApi.success('Copy updated successfully!');
      closeEditCopyModal();
      const { data } = await request<BookCopyResponse[]>({
        method: 'GET',
        path: '/catalog/book-copies',
        query: {
          book_id: selectedBookId!,
          limit: 50,
        },
      });
      setBookCopies(data);
    } catch (error) {
      messageApi.error('Failed to update copy.');
    } finally {
      setCopiesLoading(false);
    }
  };

  const handleDeleteCopy = (record: BookCopyResponse) => {
    Modal.confirm({
      title: 'Are you sure you want to delete this copy?',
      onOk: async () => {
        setCopiesLoading(true);
        try {
          await request({
            method: 'DELETE',
            path: '/catalog/book-copies/{bookcopy_id}',
            pathParams: { bookcopy_id: record.id },
          });
          messageApi.success('Copy deleted successfully!');
          const { data } = await request<BookCopyResponse[]>({
            method: 'GET',
            path: '/catalog/book-copies',
            query: {
              book_id: selectedBookId!,
              limit: 50,
            },
          });
          setBookCopies(data);
        } catch (error) {
          messageApi.error('Failed to delete copy.');
        } finally {
          setCopiesLoading(false);
        }
      },
    });
  };

  const navigateToDashboard = () => {
    navigate('/staff/dashboard');
  };

  const navigateToAuthors = () => {
    navigate('/staff/authors');
  };

  const navigateToCategories = () => {
    navigate('/staff/categories');
  };

  const bookColumns = useMemo(
    () => [
      {
        title: 'Title',
        dataIndex: 'title',
        key: 'title',
        sorter: true,
      },
      {
        title: 'ISBN',
        dataIndex: 'isbn',
        key: 'isbn',
      },
      {
        title: 'Author(s)',
        dataIndex: 'book_authors',
        key: 'book_authors',
        render: (authors: BookAuthorResponse[]) =>
          authors?.map((a) => a.name).join(', ') || '-',
      },
      {
        title: 'Category',
        dataIndex: 'book_categories',
        key: 'book_categories',
        render: () => '-',
      },
      {
        title: 'Total Copies',
        dataIndex: 'total_copies',
        key: 'total_copies',
        render: () => '-',
      },
      {
        title: 'Available Copies',
        dataIndex: 'available_copies',
        key: 'available_copies',
        render: () => '-',
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        render: () => <Tag color="green">Active</Tag>,
      },
      {
        title: 'Actions',
        key: 'actions',
        render: (_: unknown, record: BookResponse) => (
          <Space size="small">
            <Button type="link" size="small" onClick={() => openEditBookModal(record)}>
              Edit
            </Button>
            <Button
              type="link"
              danger
              size="small"
              onClick={() => handleDeactivateBook(record)}
            >
              Deactivate
            </Button>
            <Button type="link" size="small" onClick={() => openManageCopiesDrawer(record)}>
              Manage Copies
            </Button>
          </Space>
        ),
      },
    ],
    []
  );

  const copyColumns = useMemo(
    () => [
      {
        title: 'Barcode',
        dataIndex: 'barcode',
        key: 'barcode',
      },
      {
        title: 'Branch',
        dataIndex: 'library_branch_id',
        key: 'library_branch_id',
        render: (branchId: string) => {
          const branch = branches.find((b) => b.id === branchId);
          return branch?.name || branchId;
        },
      },
      {
        title: 'Condition',
        dataIndex: 'condition_status',
        key: 'condition_status',
        render: (status: ConditionStatus) => <Tag>{status}</Tag>,
      },
      {
        title: 'Status',
        dataIndex: 'availability_status',
        key: 'availability_status',
        render: (status: AvailabilityStatus) => <Tag color="blue">{status}</Tag>,
      },
      {
        title: 'Actions',
        key: 'actions',
        render: (_: unknown, record: BookCopyResponse) => (
          <Space size="small">
            <Button type="link" size="small" onClick={() => openEditCopyModal(record)}>
              Edit
            </Button>
            <Button
              type="link"
              danger
              size="small"
              onClick={() => handleDeleteCopy(record)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    [branches]
  );

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' }}>
      {contextHolder}
      <Layout style={{ minHeight: '100vh', width: '100%', background: '#f5f5f5' }}>
        <div style={{ padding: '24px 24px 0 24px' }}>
          <Breadcrumb
            style={{ marginBottom: '16px' }}
            items={[{ title: 'Staff' }, { title: 'Books' }]}
          />
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '24px',
            }}
          >
            <Typography.Title level={2} style={{ margin: 0 }}>
              Book Management
            </Typography.Title>
            <Space>
              <Button type="default" onClick={navigateToDashboard}>
                Dashboard
              </Button>
              <Button type="default" onClick={navigateToAuthors}>
                Authors
              </Button>
              <Button type="default" onClick={navigateToCategories}>
                Categories
              </Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={openAddBookModal}>
                Add Book
              </Button>
            </Space>
          </div>
        </div>
        <Card style={{ margin: '0 24px 24px 24px' }}>
          <div style={{ display: 'flex', gap: '12px', marginBottom: '16px', flexWrap: 'wrap' }}>
            <Input.Search
              placeholder="Search by title or ISBN..."
              allowClear
              enterButton
              value={searchText}
              onChange={handleSearchChange}
              style={{ width: '280px' }}
            />
            <Select
              placeholder="All Categories"
              allowClear
              value={filterCategory}
              onChange={setFilterCategory}
              options={categories.map((c) => ({ label: c.name, value: c.id }))}
              style={{ width: '180px' }}
            />
            <Select
              placeholder="All Authors"
              allowClear
              showSearch
              value={filterAuthor}
              onChange={setFilterAuthor}
              options={authors.map((a) => ({ label: a.name, value: a.id }))}
              style={{ width: '180px' }}
            />
            <Select
              placeholder="All Statuses"
              allowClear
              value={filterStatus}
              onChange={setFilterStatus}
              options={[
                { label: 'Active', value: 'active' },
                { label: 'Inactive', value: 'inactive' },
              ]}
              style={{ width: '140px' }}
            />
            <Select
              placeholder="All Branches"
              allowClear
              value={filterBranch}
              onChange={setFilterBranch}
              options={branches.map((b) => ({ label: b.name, value: b.id }))}
              style={{ width: '180px' }}
            />
          </div>
          <Table
            columns={bookColumns}
            dataSource={books}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showTotal: (total) => `Total ${total} items`,
              onChange: handlePaginationChange,
            }}
          />
        </Card>
      </Layout>

      <Modal
        title="Add New Book"
        open={addBookModalVisible}
        onCancel={closeAddBookModal}
        onOk={handleAddBook}
        width={720}
        destroyOnClose
      >
        <Form form={addBookForm} layout="vertical">
          <Form.Item
            name="isbn"
            label="ISBN"
            rules={[
              {
                pattern: /^(\d{10}|\d{13}|\d{3}-\d{10})$/,
                message: 'Please enter a valid ISBN',
              },
            ]}
          >
            <Input placeholder="Enter ISBN-10 or ISBN-13" />
          </Form.Item>
          <Form.Item
            name="title"
            label="Title"
            rules={[{ required: true, message: 'Title is required' }]}
          >
            <Input placeholder="Enter book title" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea placeholder="Enter book description" rows={4} />
          </Form.Item>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            <Form.Item name="publisher" label="Publisher">
              <Input placeholder="Enter publisher" />
            </Form.Item>
            <Form.Item name="publication_date" label="Publication Date">
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>
            <Form.Item name="edition" label="Edition">
              <Input placeholder="e.g. 2nd" />
            </Form.Item>
            <Form.Item name="number_of_pages" label="Pages">
              <InputNumber placeholder="Number of pages" min={1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="language" label="Language">
              <Input placeholder="e.g. English" />
            </Form.Item>
          </div>
          <Form.Item name="cover_image_url" label="Cover Image URL">
            <Input placeholder="Enter cover image URL" />
          </Form.Item>
          <Form.Item name="author_ids" label="Authors">
            <Select
              mode="multiple"
              placeholder="Select authors"
              showSearch
              options={authors.map((a) => ({ label: a.name, value: a.id }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="category_ids" label="Categories">
            <Select
              mode="multiple"
              placeholder="Select categories"
              showSearch
              options={categories.map((c) => ({ label: c.name, value: c.id }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Book"
        open={editBookModalVisible}
        onCancel={closeEditBookModal}
        onOk={handleEditBook}
        width={720}
        destroyOnClose
      >
        <Form form={editBookForm} layout="vertical">
          <Form.Item name="isbn" label="ISBN">
            <Input placeholder="Enter ISBN-10 or ISBN-13" />
          </Form.Item>
          <Form.Item
            name="title"
            label="Title"
            rules={[{ required: true, message: 'Title is required' }]}
          >
            <Input placeholder="Enter book title" />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea placeholder="Enter book description" rows={4} />
          </Form.Item>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            <Form.Item name="publisher" label="Publisher">
              <Input placeholder="Enter publisher" />
            </Form.Item>
            <Form.Item name="publication_date" label="Publication Date">
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px' }}>
            <Form.Item name="edition" label="Edition">
              <Input placeholder="e.g. 2nd" />
            </Form.Item>
            <Form.Item name="number_of_pages" label="Pages">
              <InputNumber placeholder="Number of pages" min={1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="language" label="Language">
              <Input placeholder="e.g. English" />
            </Form.Item>
          </div>
          <Form.Item name="cover_image_url" label="Cover Image URL">
            <Input placeholder="Enter cover image URL" />
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title="Manage Book Copies"
        open={manageCopiesDrawerVisible}
        onClose={closeManageCopiesDrawer}
        width={720}
        destroyOnClose
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '16px',
          }}
        >
          <Typography.Title level={5} style={{ margin: 0 }}>
            Book Copies
          </Typography.Title>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="small"
            onClick={openAddCopyModal}
          >
            Add Copy
          </Button>
        </div>
        <Table
          columns={copyColumns}
          dataSource={bookCopies}
          rowKey="id"
          loading={copiesLoading}
          size="small"
          pagination={false}
        />
      </Drawer>

      <Modal
        title="Add Book Copy"
        open={addCopyModalVisible}
        onCancel={closeAddCopyModal}
        onOk={handleAddCopy}
        width={520}
        destroyOnClose
      >
        <Form form={addCopyForm} layout="vertical">
          <Form.Item name="barcode" label="Barcode" tooltip="Auto-generated if left empty">
            <Input placeholder="Auto-generated if empty" />
          </Form.Item>
          <Form.Item
            name="library_branch_id"
            label="Branch"
            rules={[{ required: true, message: 'Branch is required' }]}
          >
            <Select
              placeholder="Select branch"
              options={branches.map((b) => ({ label: b.name, value: b.id }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            name="condition_status"
            label="Condition"
            rules={[{ required: true, message: 'Condition is required' }]}
          >
            <Select
              placeholder="Select condition"
              options={[
                { label: 'Excellent', value: 'EXCELLENT' },
                { label: 'Good', value: 'GOOD' },
                { label: 'Fair', value: 'FAIR' },
                { label: 'Poor', value: 'POOR' },
                { label: 'Damaged', value: 'DAMAGED' },
              ]}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="availability_status" label="Availability Status" initialValue="AVAILABLE">
            <Select
              placeholder="Select status"
              options={[
                { label: 'Available', value: 'AVAILABLE' },
                { label: 'Checked Out', value: 'CHECKED_OUT' },
                { label: 'Reserved', value: 'RESERVED' },
                { label: 'In Transit', value: 'IN_TRANSIT' },
                { label: 'Maintenance', value: 'MAINTENANCE' },
                { label: 'Lost', value: 'LOST' },
              ]}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="physical_location" label="Physical Location">
            <Input placeholder="e.g. Shelf A3, Row 2" />
          </Form.Item>
          <Form.Item name="acquisition_date" label="Acquisition Date">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Book Copy"
        open={editCopyModalVisible}
        onCancel={closeEditCopyModal}
        onOk={handleEditCopy}
        width={520}
        destroyOnClose
      >
        <Form form={editCopyForm} layout="vertical">
          <Form.Item name="barcode" label="Barcode">
            <Input placeholder="Barcode" />
          </Form.Item>
          <Form.Item name="library_branch_id" label="Branch">
            <Select
              placeholder="Select branch"
              options={branches.map((b) => ({ label: b.name, value: b.id }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="condition_status" label="Condition">
            <Select
              placeholder="Select condition"
              options={[
                { label: 'Excellent', value: 'EXCELLENT' },
                { label: 'Good', value: 'GOOD' },
                { label: 'Fair', value: 'FAIR' },
                { label: 'Poor', value: 'POOR' },
                { label: 'Damaged', value: 'DAMAGED' },
              ]}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="availability_status" label="Availability Status">
            <Select
              placeholder="Select status"
              options={[
                { label: 'Available', value: 'AVAILABLE' },
                { label: 'Checked Out', value: 'CHECKED_OUT' },
                { label: 'Reserved', value: 'RESERVED' },
                { label: 'In Transit', value: 'IN_TRANSIT' },
                { label: 'Maintenance', value: 'MAINTENANCE' },
                { label: 'Lost', value: 'LOST' },
              ]}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="physical_location" label="Physical Location">
            <Input placeholder="e.g. Shelf A3, Row 2" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}