import { useState, useMemo, useEffect, useCallback } from 'react';
import { Table, Button, Input, Modal, Form, DatePicker, Typography, Breadcrumb, message, Space, Avatar, Upload } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UserOutlined } from '@ant-design/icons';
import { request } from '../api/client';
import dayjs from 'dayjs';

interface Author {
  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 PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

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

  const [authors, setAuthors] = useState<Author[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [editingAuthor, setEditingAuthor] = useState<Author | null>(null);
  const [searchText, setSearchText] = useState<string>('');
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [deleteConfirmVisible, setDeleteConfirmVisible] = useState<boolean>(false);
  const [deletingAuthorId, setDeletingAuthorId] = useState<string | null>(null);

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

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

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

  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: pageSize }));
  };

  const openCreateModal = () => {
    setModalVisible(true);
    setEditingAuthor(null);
    form.resetFields();
  };

  const openEditModal = (record: Author) => {
    setModalVisible(true);
    setEditingAuthor(record);
    form.setFieldsValue({
      first_name: record.first_name,
      last_name: record.last_name,
      biography: record.biography,
      birth_date: record.birth_date ? dayjs(record.birth_date) : null,
      nationality: record.nationality,
    });
  };

  const closeModal = () => {
    setModalVisible(false);
    setEditingAuthor(null);
    form.resetFields();
  };

  const openDeleteConfirm = (authorId: string) => {
    setDeleteConfirmVisible(true);
    setDeletingAuthorId(authorId);
  };

  const closeDeleteConfirm = () => {
    setDeleteConfirmVisible(false);
    setDeletingAuthorId(null);
  };

  const handleFormSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (!values.first_name) {
        messageApi.error('First name is required');
        return;
      }
      if (!values.last_name) {
        messageApi.error('Last name is required');
        return;
      }

      setSubmitting(true);

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

      if (isEditing && editingAuthor) {
        await request<Author>({
          method: 'PUT',
          path: '/authors/{author_id}',
          pathParams: { author_id: editingAuthor.id },
          body: body,
        });
        messageApi.success('Author updated successfully');
      } else {
        await request<Author>({
          method: 'POST',
          path: '/authors',
          body: body,
        });
        messageApi.success('Author created successfully');
      }

      closeModal();
      fetchAuthors();
    } catch (error) {
      if (isEditing) {
        messageApi.error('Failed to update author');
      } else {
        messageApi.error('Failed to create author');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!deletingAuthorId) return;

    try {
      setSubmitting(true);
      await request({
        method: 'DELETE',
        path: '/authors/{author_id}',
        pathParams: { author_id: deletingAuthorId },
      });
      messageApi.success('Author deleted successfully');
      closeDeleteConfirm();
      fetchAuthors();
    } catch (error) {
      messageApi.error('Failed to delete author. Author may have associated books.');
    } finally {
      setSubmitting(false);
    }
  };

  const columns = useMemo(
    () => [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80,
        ellipsis: true,
      },
      {
        title: 'Photo',
        dataIndex: 'photo',
        key: 'photo',
        width: 70,
        render: () => <Avatar icon={<UserOutlined />} />,
      },
      {
        title: 'Name',
        dataIndex: 'full_name',
        key: 'full_name',
        render: (_: unknown, record: Author) => `${record.first_name} ${record.last_name}`,
      },
      {
        title: 'Biography',
        dataIndex: 'biography',
        key: 'biography',
        ellipsis: true,
        width: 250,
      },
      {
        title: 'Nationality',
        dataIndex: 'nationality',
        key: 'nationality',
        width: 120,
      },
      {
        title: 'Birth Date',
        dataIndex: 'birth_date',
        key: 'birth_date',
        width: 120,
        render: (date: string | null) => (date ? dayjs(date).format('YYYY-MM-DD') : '-'),
      },
      {
        title: 'Actions',
        key: 'actions',
        width: 150,
        render: (_: unknown, record: Author) => (
          <Space size="small">
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => openEditModal(record)}
            >
              Edit
            </Button>
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => openDeleteConfirm(record.id)}
            >
              Delete
            </Button>
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <div
      style={{
        minHeight: '100vh',
        width: '100%',
        padding: '24px',
        backgroundColor: '#f5f5f5',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {contextHolder}
      
      <Breadcrumb
        style={{ marginBottom: '16px' }}
        items={[
          { title: 'Dashboard', href: '/admin/dashboard' },
          { title: 'Authors Management' },
        ]}
      />

      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '24px',
        }}
      >
        <Typography.Title level={2} style={{ margin: 0 }}>
          Authors Management
        </Typography.Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="large"
          onClick={openCreateModal}
        >
          Add Author
        </Button>
      </div>

      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '16px',
        }}
      >
        <Input.Search
          placeholder="Search authors by name..."
          allowClear
          size="large"
          value={searchText}
          onChange={handleSearchChange}
          style={{ maxWidth: '400px' }}
          aria-label="Search authors by name"
        />
      </div>

      <Table
        rowKey="id"
        dataSource={authors}
        columns={columns}
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: handlePaginationChange,
        }}
        style={{
          backgroundColor: '#ffffff',
          borderRadius: '6px',
        }}
      />

      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleFormSubmit}
        onCancel={closeModal}
        width={600}
        destroyOnClose
        okText="Save"
        cancelText="Cancel"
        confirmLoading={submitting}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="first_name"
            label="First Name"
            rules={[{ required: true, message: 'First name is required' }]}
          >
            <Input placeholder="Enter first name" />
          </Form.Item>

          <Form.Item
            name="last_name"
            label="Last Name"
            rules={[{ required: true, message: 'Last name is required' }]}
          >
            <Input placeholder="Enter last name" />
          </Form.Item>

          <Form.Item name="biography" label="Biography">
            <Input.TextArea
              placeholder="Enter biography"
              rows={4}
              maxLength={2000}
              showCount
            />
          </Form.Item>

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

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

          <Form.Item name="photo" label="Photo">
            <Upload listType="picture-card" maxCount={1} accept="image/*">
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Confirm Delete"
        open={deleteConfirmVisible}
        onOk={handleDelete}
        onCancel={closeDeleteConfirm}
        okText="Delete"
        cancelText="Cancel"
        okButtonProps={{ danger: true }}
        width={420}
        confirmLoading={submitting}
      >
        <Typography.Text>
          Are you sure you want to delete this author? This action cannot be undone. Authors with associated books cannot be deleted.
        </Typography.Text>
      </Modal>
    </div>
  );
}