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

interface Publisher {
  id: string;
  name: string;
  address: string | null;
  phone: string | null;
  email: string | null;
  website: string | null;
  created_at: string;
  updated_at: string;
}

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

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

  const [publishers, setPublishers] = useState<Publisher[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [editingPublisher, setEditingPublisher] = useState<Publisher | null>(null);
  const [searchText, setSearchText] = useState<string>('');
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [deleteConfirmVisible, setDeleteConfirmVisible] = useState<boolean>(false);
  const [selectedPublisherId, setSelectedPublisherId] = useState<string | null>(null);

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

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

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

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

  const openCreateModal = useCallback(() => {
    setModalVisible(true);
    setEditingPublisher(null);
    form.resetFields();
  }, [form]);

  const openEditModal = useCallback((record: Publisher) => {
    setModalVisible(true);
    setEditingPublisher(record);
    form.setFieldsValue(record);
  }, [form]);

  const closeModal = useCallback(() => {
    setModalVisible(false);
    setEditingPublisher(null);
    form.resetFields();
  }, [form]);

  const openDeleteConfirm = useCallback((record: Publisher) => {
    setDeleteConfirmVisible(true);
    setSelectedPublisherId(record.id);
  }, []);

  const closeDeleteConfirm = useCallback(() => {
    setDeleteConfirmVisible(false);
    setSelectedPublisherId(null);
  }, []);

  const handleSubmit = useCallback(async () => {
    try {
      const formValues = await form.validateFields();
      
      if (editingPublisher) {
        await request<Publisher>({
          method: 'PUT',
          path: '/publishers/{publisher_id}',
          pathParams: { publisher_id: editingPublisher.id },
          body: {
            name: formValues.name,
            address: formValues.address,
            phone: formValues.phone,
            email: formValues.email,
          },
        });
        messageApi.success('Publisher updated successfully');
      } else {
        await request<Publisher>({
          method: 'POST',
          path: '/publishers',
          body: {
            name: formValues.name,
            address: formValues.address,
            phone: formValues.phone,
            email: formValues.email,
          },
        });
        messageApi.success('Publisher created successfully');
      }
      
      closeModal();
      fetchPublishers();
    } catch (error) {
      messageApi.error(editingPublisher ? 'Failed to update publisher' : 'Failed to create publisher');
    }
  }, [editingPublisher, form, messageApi, closeModal, fetchPublishers]);

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

    try {
      await request({
        method: 'DELETE',
        path: '/publishers/{publisher_id}',
        pathParams: { publisher_id: selectedPublisherId },
      });
      messageApi.success('Publisher deleted successfully');
      closeDeleteConfirm();
      fetchPublishers();
    } catch (error) {
      messageApi.error('Failed to delete publisher');
    }
  }, [selectedPublisherId, messageApi, closeDeleteConfirm, fetchPublishers]);

  const columns = useMemo(() => [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      ellipsis: true,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
      ellipsis: true,
    },
    {
      title: 'Phone',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Website',
      dataIndex: 'website',
      key: 'website',
      ellipsis: true,
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right' as const,
      width: 150,
      render: (_: unknown, record: Publisher) => (
        <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)}
          >
            Delete
          </Button>
        </Space>
      ),
    },
  ], [openEditModal, openDeleteConfirm]);

  const rootStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    padding: '24px',
    background: '#f5f5f5',
  };

  const headerStyle: CSSProperties = {
    marginBottom: '24px',
  };

  const toolbarStyle: CSSProperties = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '16px',
    flexWrap: 'wrap',
    gap: '12px',
  };

  const searchStyle: CSSProperties = {
    maxWidth: '400px',
    width: '100%',
  };

  return (
    <div style={rootStyle}>
      {contextHolder}
      
      <div style={headerStyle}>
        <Breadcrumb
          style={{ marginBottom: '8px' }}
          items={[
            { title: 'Dashboard', href: '/admin/dashboard' },
            { title: 'Publishers' },
          ]}
        />
        <Typography.Title level={2} style={{ margin: 0 }}>
          Publishers Management
        </Typography.Title>
      </div>

      <div style={toolbarStyle}>
        <Input.Search
          placeholder="Search by publisher name..."
          allowClear
          enterButton
          value={searchText}
          onChange={handleSearchChange}
          style={searchStyle}
          aria-label="Search publishers"
        />
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={openCreateModal}
        >
          Add Publisher
        </Button>
      </div>

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

      <Modal
        title={editingPublisher ? 'Edit Publisher' : 'Add Publisher'}
        open={modalVisible}
        onCancel={closeModal}
        destroyOnClose
        width={600}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={editingPublisher || undefined}
        >
          <Form.Item
            name="name"
            label="Publisher Name"
            rules={[{ required: true, message: 'Please enter publisher name' }]}
          >
            <Input placeholder="Enter publisher name" />
          </Form.Item>

          <Form.Item name="address" label="Address">
            <Input.TextArea placeholder="Enter address" rows={3} />
          </Form.Item>

          <Form.Item name="phone" label="Phone">
            <Input placeholder="Enter phone number" />
          </Form.Item>

          <Form.Item
            name="email"
            label="Email"
            rules={[{ type: 'email', message: 'Please enter a valid email' }]}
          >
            <Input placeholder="Enter email address" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              Save
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Confirm Delete"
        open={deleteConfirmVisible}
        onCancel={closeDeleteConfirm}
        onOk={handleDelete}
        okText="Delete"
        okButtonProps={{ danger: true }}
      >
        <p>Are you sure you want to delete this publisher?</p>
      </Modal>
    </div>
  );
}