import { useState, useMemo, useEffect, CSSProperties } from 'react';
import { Card, Typography, Tag, Space, Divider, Row, Col, Spin, Empty, Pagination, Breadcrumb, Button, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { request } from '../api/client';

interface AuthorResponse {
  id: string;
  name: string;
  biography?: string | null;
  birth_date?: string | null;
  death_date?: string | null;
  nationality?: string | null;
}

interface BookAuthorResponse {
  book_id: string;
  author_id: string;
  author_order?: number | null;
}

interface BookResponse {
  id: string;
  title: string;
  book_authors: BookAuthorResponse[];
  isbn?: string | null;
  publisher?: string | null;
  publication_date?: string | null;
  cover_image_url?: string | null;
  description?: string | null;
}

export default function AuthorBooksPage() {
  const { authorId } = useParams<{ authorId: string }>();
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const [author, setAuthor] = useState<AuthorResponse | null>(null);
  const [books, setBooks] = useState<BookResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [totalBooks, setTotalBooks] = useState<number>(0);
  const [pageSize] = useState<number>(12);

  const authorDisplayName = useMemo(() => {
    return author?.name || 'Unknown Author';
  }, [author]);

  const hasBooks = useMemo(() => {
    return books.length > 0;
  }, [books]);

  useEffect(() => {
    const fetchAuthor = async () => {
      if (!authorId) return;
      setLoading(true);
      try {
        const result = await request<AuthorResponse>({
          method: 'GET',
          path: '/catalog/authors/{author_id}',
          pathParams: { author_id: authorId }
        });
        setAuthor(result.data);
      } catch (error) {
        messageApi.error('Failed to load author information');
      } finally {
        setLoading(false);
      }
    };
    fetchAuthor();
  }, [authorId, messageApi]);

  useEffect(() => {
    const fetchBooks = async () => {
      if (!author?.name) return;
      setLoading(true);
      try {
        const offset = (currentPage - 1) * pageSize;
        const result = await request<BookResponse[]>({
          method: 'GET',
          path: '/catalog/books/search',
          query: {
            author: author.name,
            limit: pageSize.toString(),
            offset: offset.toString()
          }
        });
        setBooks(result.data);
        setTotalBooks(result.data.length);
      } catch (error) {
        messageApi.error('Failed to load books');
      } finally {
        setLoading(false);
      }
    };
    fetchBooks();
  }, [author, currentPage, pageSize, messageApi]);

  const navigateToCatalog = () => {
    navigate('/');
  };

  const navigateToBookDetail = (bookId: string) => {
    navigate(`/books/${bookId}`);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const rootStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: '24px',
    maxWidth: '1200px',
    margin: '0 auto'
  };

  const breadcrumbItems = [
    { title: 'Catalog', href: '/' },
    { title: 'Author' }
  ];

  return (
    <div style={rootStyle}>
      {contextHolder}
      <Breadcrumb items={breadcrumbItems} style={{ marginBottom: '24px' }} />
      <Button
        type="link"
        icon={<ArrowLeftOutlined />}
        onClick={navigateToCatalog}
        style={{ marginBottom: '16px', paddingLeft: '0' }}
      >
        Back to Catalog
      </Button>
      <Card bordered style={{ marginBottom: '32px' }}>
        <div>
          <Typography.Title level={2} style={{ marginBottom: '8px' }}>
            {authorDisplayName}
          </Typography.Title>
          <Space size="large" wrap style={{ marginBottom: '16px' }}>
            {author?.nationality && (
              <Tag color="blue">{author.nationality}</Tag>
            )}
            {author?.birth_date && (
              <Typography.Text type="secondary">
                Born: {author.birth_date}
              </Typography.Text>
            )}
            {author?.death_date && (
              <Typography.Text type="secondary">
                Died: {author.death_date}
              </Typography.Text>
            )}
          </Space>
          {author?.biography && (
            <>
              <Divider orientation="left" plain>
                Biography
              </Divider>
              <Typography.Paragraph ellipsis={{ rows: 4, expandable: true }}>
                {author.biography}
              </Typography.Paragraph>
            </>
          )}
        </div>
      </Card>
      <div style={{ marginBottom: '16px' }}>
        <Typography.Title level={3}>Books by this Author</Typography.Title>
        <Typography.Text type="secondary">{totalBooks} books</Typography.Text>
      </div>
      {loading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: '48px' }}>
          <Spin size="large" tip="Loading books..." />
        </div>
      ) : !hasBooks ? (
        <Empty description="No books found for this author" style={{ padding: '48px' }} />
      ) : (
        <Row gutter={[16, 16]}>
          {books.map((item) => (
            <Col xs={24} sm={12} md={8} lg={6} key={item.id}>
              <Card
                hoverable
                cover={item.cover_image_url ? <img alt={item.title} src={item.cover_image_url} /> : undefined}
                onClick={() => navigateToBookDetail(item.id)}
                style={{ cursor: 'pointer', height: '100%' }}
              >
                <Typography.Text strong ellipsis>
                  {item.title}
                </Typography.Text>
                {item.publisher && (
                  <Typography.Text type="secondary" ellipsis style={{ fontSize: '12px', display: 'block' }}>
                    {item.publisher}
                  </Typography.Text>
                )}
                {item.publication_date && (
                  <Typography.Text type="secondary" style={{ fontSize: '12px', display: 'block' }}>
                    {item.publication_date}
                  </Typography.Text>
                )}
              </Card>
            </Col>
          ))}
        </Row>
      )}
      {hasBooks && (
        <div style={{ marginTop: '32px', display: 'flex', justifyContent: 'center' }}>
          <Pagination
            current={currentPage}
            total={totalBooks}
            pageSize={pageSize}
            showSizeChanger={false}
            showTotal={(total) => `Total ${total} items`}
            onChange={handlePageChange}
          />
        </div>
      )}
    </div>
  );
}