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

interface AuthorResponse {
  id: string;
  first_name: string;
  last_name: string;
  biography?: string | null;
  birth_date?: string | null;
  nationality?: string | null;
  created_at: string;
  updated_at: string;
}

interface BookResponse {
  id: string;
  isbn?: string | null;
  title: string;
  subtitle?: string | null;
  publisher_id?: string | null;
  publication_date?: string | null;
  edition?: string | null;
  language: string;
  pages?: number | null;
  description?: string | null;
  book_format: 'PHYSICAL' | 'DIGITAL';
  total_copies: number;
  available_copies: number;
  location?: string | null;
  status: 'AVAILABLE' | 'CHECKED_OUT' | 'RESERVED' | 'MAINTENANCE' | 'LOST' | 'DAMAGED';
  created_at: string;
  updated_at: string;
}

interface BookAuthorResponse {
  id: string;
  book_id: string;
  author_id: string;
  author_order?: number;
  created_at: string;
  updated_at: string;
}

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

  const [author, setAuthor] = useState<AuthorResponse | null>(null);
  const [authorBooks, setAuthorBooks] = useState<BookResponse[]>([]);
  const [bookAuthorRelations, setBookAuthorRelations] = useState<BookAuthorResponse[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [booksLoading, setBooksLoading] = useState<boolean>(true);

  const authorFullName = useMemo(() => {
    return `${author?.first_name || ''} ${author?.last_name || ''}`.trim();
  }, [author]);

  const authorInitials = useMemo(() => {
    return `${author?.first_name?.[0] || ''}${author?.last_name?.[0] || ''}`;
  }, [author]);

  const filteredAuthorBooks = useMemo(() => {
    if (!author || bookAuthorRelations.length === 0) return [];
    const bookIds = bookAuthorRelations
      .filter(rel => rel.author_id === author.id)
      .map(rel => rel.book_id);
    return authorBooks.filter(book => bookIds.includes(book.id));
  }, [author, authorBooks, bookAuthorRelations]);

  useEffect(() => {
    const fetchAuthorData = async () => {
      if (!authorId) {
        messageApi.error('Author ID is missing');
        setLoading(false);
        return;
      }

      try {
        const result = await request<AuthorResponse>({
          method: 'GET',
          path: '/authors/{author_id}',
          pathParams: { author_id: authorId }
        });
        setAuthor(result.data);
      } catch (error) {
        messageApi.error('Failed to load author details');
      } finally {
        setLoading(false);
      }
    };

    fetchAuthorData();
  }, [authorId, messageApi]);

  useEffect(() => {
    const fetchBookAuthorRelations = async () => {
      try {
        const result = await request<BookAuthorResponse[]>({
          method: 'GET',
          path: '/book-authors',
          query: { limit: 100, offset: 0 }
        });
        setBookAuthorRelations(result.data);
      } catch (error) {
        messageApi.error('Failed to load book-author relationships');
      }
    };

    fetchBookAuthorRelations();
  }, [messageApi]);

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        const result = await request<BookResponse[]>({
          method: 'GET',
          path: '/books',
          query: { limit: 50, offset: 0 }
        });
        setAuthorBooks(result.data);
      } catch (error) {
        messageApi.error('Failed to load books');
      } finally {
        setBooksLoading(false);
      }
    };

    fetchBooks();
  }, [messageApi]);

  const navigateToCatalog = () => {
    navigate(ROUTES.CATALOG);
  };

  const navigateToBookDetail = (bookId: string) => {
    navigate(ROUTES.BOOK_DETAIL(bookId));
  };

  const getStatusColor = (status: string): string => {
    const colorMap: Record<string, string> = {
      AVAILABLE: 'green',
      CHECKED_OUT: 'orange',
      RESERVED: 'blue',
      MAINTENANCE: 'gray',
      LOST: 'red',
      DAMAGED: 'red'
    };
    return colorMap[status] || 'default';
  };

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' }}>
        {contextHolder}
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
          <Spin size="large" tip="Loading author details..." />
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', height: '100%', width: '100%', display: 'flex', flexDirection: 'column', padding: '24px', background: '#f5f5f5' }}>
      {contextHolder}
      
      <Breadcrumb
        style={{ marginBottom: '24px' }}
        items={[
          { title: 'Catalog', href: ROUTES.CATALOG },
          { title: 'Authors' },
          { title: 'Author Details' }
        ]}
      />

      <Button
        type="link"
        icon={<ArrowLeftOutlined />}
        onClick={navigateToCatalog}
        style={{ marginBottom: '16px', paddingLeft: '0' }}
      >
        Back to Catalog
      </Button>

      <Card bordered={false} style={{ marginBottom: '32px', borderRadius: '8px' }}>
        <div style={{ display: 'flex', gap: '32px', alignItems: 'flex-start' }}>
          <Avatar
            size={120}
            shape="circle"
            style={{ flexShrink: 0, fontSize: '36px', backgroundColor: '#1677ff' }}
          >
            {authorInitials}
          </Avatar>

          <div style={{ flex: 1 }}>
            <Typography.Title level={2} style={{ marginBottom: '8px', marginTop: '0' }}>
              {authorFullName}
            </Typography.Title>

            {author?.nationality && (
              <Tag color="blue" style={{ marginBottom: '12px' }}>
                {author.nationality}
              </Tag>
            )}

            {author?.birth_date && (
              <Typography.Text type="secondary" style={{ display: 'block', marginBottom: '16px' }}>
                Born: {author.birth_date}
              </Typography.Text>
            )}

            <Typography.Title level={5} style={{ marginBottom: '8px' }}>
              Biography
            </Typography.Title>

            <Typography.Paragraph
              ellipsis={{ rows: 6, expandable: true }}
              style={{ color: '#595959', lineHeight: '1.8' }}
            >
              {author?.biography || 'No biography available.'}
            </Typography.Paragraph>
          </div>
        </div>
      </Card>

      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <Typography.Title level={3} style={{ margin: '0' }}>
            Books by this Author
          </Typography.Title>
          <Badge count={filteredAuthorBooks.length} showZero color="#1677ff" />
        </div>

        {booksLoading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '48px 0' }}>
            <Spin size="large" />
          </div>
        ) : filteredAuthorBooks.length === 0 ? (
          <Empty
            description="No books found for this author in the catalog"
            style={{ padding: '48px 0' }}
          />
        ) : (
          <Row gutter={[16, 16]}>
            {filteredAuthorBooks.map((book) => (
              <Col key={book.id} xs={24} sm={12} md={8} lg={6}>
                <Card
                  hoverable
                  bordered
                  onClick={() => navigateToBookDetail(book.id)}
                  style={{ borderRadius: '8px', height: '100%', cursor: 'pointer' }}
                >
                  <div
                    style={{
                      height: '180px',
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginBottom: '12px'
                    }}
                  >
                    <BookOutlined style={{ fontSize: '48px', color: '#ffffff' }} />
                  </div>

                  <Typography.Title
                    level={5}
                    ellipsis={{ rows: 2 }}
                    style={{ marginBottom: '8px', marginTop: '0' }}
                  >
                    {book.title}
                  </Typography.Title>

                  {book.publication_date && (
                    <Typography.Text
                      type="secondary"
                      style={{ display: 'block', marginBottom: '8px', fontSize: '13px' }}
                    >
                      {new Date(book.publication_date).getFullYear()}
                    </Typography.Text>
                  )}

                  <Tag color={getStatusColor(book.status)}>{book.status}</Tag>

                  <Typography.Text
                    type="secondary"
                    style={{ fontSize: '12px', display: 'block', marginTop: '4px' }}
                  >
                    {book.available_copies} of {book.total_copies} available
                  </Typography.Text>
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </div>
    </div>
  );
}