import { useState, useMemo, useEffect, useCallback } from 'react';
import { Card, Table, Button, Input, Modal, Form, DatePicker, Typography, Breadcrumb, Space, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '../router/routes.constant';
import dayjs from 'dayjs';

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

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

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

export default function AuthorManagementPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const [authors, setAuthors] = useState<AuthorResponse[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingAuthorId, setEditingAuthorId] = useState<string | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  const isEditing = useMemo(() => editingAuthorId !== null, [editingAuthorId]);
  const modalTitle = useMemo(() => (editingAuthorId ? 'Edit Author' : 'Add Author'), [editingAuthorId]);

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

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

  const fetchAuthorDetails = useCallback(async (authorId: string) => {
    try {
      const { data } = await request<AuthorDetailResponse>({
        method: 'GET',
        path: '/catalog/authors/{author_id}',
        pathParams: { author_id: authorId },
      });
      form.setFieldsValue({
        name: data.name,
        biography: data.biography,
        birth_date: data.birth_date ? dayjs(data.birth_date) : null,
        nationality: data.nationality,
      });
    } catch (error) {
      messageApi.error('Failed to load author details');
    }
  }, [form, messageApi]);

  useEffect(() => {
    if (isModalVisible && editingAuthorId) {
      fetchAuthorDetails(editingAuthorId);
    }
  }, [isModalVisible, editingAuthorId, fetchAuthorDetails]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

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

  const openAddModal = () => {
    setIsModalVisible(true);
    setEditingAuthorId(null);
    form.resetFields();
  };

  const openEditModal = (record: AuthorResponse) => {
    setIsModalVisible(true);
    setEditingAuthorId(record.id);
  };

  const closeModal = () => {
    setIsModalVisible(false);
    setEditingAuthorId(null);
    form.resetFields();
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);

      const payload = {
        name: values.name,
        biography: values.biography || null,
        birth_date: values.birth_date ? values.birth_date.format('YYYY-MM-DD') : null,
        nationality: values.nationality || null,
      };

      if (editingAuthorId) {
        await request<AuthorResponse>({
          method: 'PUT',
          path: '/catalog/authors/{author_id}',
          pathParams: { author_id: editingAuthorId },
          body: payload,
        });
        messageApi.success('Author updated successfully');
      } else {
        await request<AuthorResponse>({
          method: 'POST',
          path: '/catalog/authors',
          body: payload,
        });
        messageApi.success('Author created successfully');
      }

      setIsModalVisible(false);
      setEditingAuthorId(null);
      form.resetFields();
      fetchAuthors();
    } catch (error) {
      if (editingAuthorId) {
        messageApi.error('Failed to update author');
      } else {
        messageApi.error('Failed to create author');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = (authorId: string) => {
    Modal.confirm({
      title: 'Delete Author',
      content: 'Are you sure you want to delete this author? This action cannot be undone. Note: Authors with associated books cannot be deleted.',
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          await request({
            method: 'DELETE',
            path: '/catalog/authors/{author_id}',
            pathParams: { author_id: authorId },
          });
          messageApi.success('Author deleted successfully');
          fetchAuthors();
        } catch (error) {
          messageApi.error('Cannot delete author with associated books');
        }
      },
    });
  };

  const navigateToDashboard = () => {
    navigate(ROUTES.STAFF_DASHBOARD || '/staff/dashboard');
  };

  const navigateToBooks = () => {
    navigate(ROUTES.STAFF_BOOKS || '/staff/books');
  };

  const columns = useMemo(
    () => [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        sorter: (a: AuthorResponse, b: AuthorResponse) => a.name.localeCompare(b.name),
      },
      {
        title: 'Nationality',
        dataIndex: 'nationality',
        key: 'nationality',
      },
      {
        title: 'Birth Date',
        dataIndex: 'birth_date',
        key: 'birth_date',
      },
      {
        title: 'Books Count',
        dataIndex: 'books_count',
        key: 'books_count',
        align: 'center' as const,
      },
      {
        title: 'Actions',
        key: 'actions',
        render: (_: unknown, record: AuthorResponse) => (
          <Space size="small">
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => openEditModal(record)}
            >
              Edit
            </Button>
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => handleDelete(record.id)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <div
      style={{
        minHeight: '100vh',
        height: '100%',
        width: '100%',
        display: 'flex',
        flexDirection: 'column',
        padding: '24px',
        backgroundColor: '#f5f5f5',
      }}
    >
      {contextHolder}
      <div style={{ marginBottom: '24px' }}>
        <Breadcrumb
          style={{ marginBottom: '16px' }}
          items={[
            {
              title: 'Dashboard',
              onClick: navigateToDashboard,
              style: { cursor: 'pointer' },
            },
            {
              title: 'Authors',
            },
          ]}
        />
        <Typography.Title level={2} style={{ marginBottom: '0' }}>
          Author Management
        </Typography.Title>
        <Typography.Text type="secondary">
          Manage authors in the library catalog. Add, edit, or remove authors and view their associated books.
        </Typography.Text>
      </div>

      <div
        style={{
          marginBottom: '16px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '12px',
        }}
      >
        <Input.Search
          placeholder="Search authors by name..."
          allowClear
          style={{ width: 320 }}
          value={searchText}
          onChange={handleSearchChange}
          aria-label="Search authors"
        />
        <Button type="primary" icon={<PlusOutlined />} onClick={openAddModal}>
          Add Author
        </Button>
      </div>

      <Card bordered={false}>
        <Table
          columns={columns}
          dataSource={authors}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} items`,
            onChange: handlePaginationChange,
          }}
        />
      </Card>

      <Modal
        title={modalTitle}
        open={isModalVisible}
        onCancel={closeModal}
        destroyOnClose
        width={600}
        footer={null}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            label="Name"
            name="name"
            rules={[{ required: true, message: 'Please enter the author name' }]}
          >
            <Input placeholder="Enter author name" aria-label="Author Name" />
          </Form.Item>

          <Form.Item label="Biography" name="biography">
            <Input.TextArea placeholder="Enter author biography" rows={4} aria-label="Biography" />
          </Form.Item>

          <Form.Item label="Birth Date" name="birth_date">
            <DatePicker placeholder="Select birth date" style={{ width: '100%' }} aria-label="Birth Date" />
          </Form.Item>

          <Form.Item label="Nationality" name="nationality">
            <Input placeholder="Enter nationality" aria-label="Nationality" />
          </Form.Item>

          <div
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: '8px',
              marginTop: '16px',
            }}
          >
            <Button onClick={closeModal}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={submitting}>
              Save
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
}