'use client';
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchCluster, fetchCity } from './slice';
import { Button, Table, Tag, Space, Popconfirm, notification, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import ModalBox from './component/modal';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { AppDispatch, RootState } from '@/store/store';
import { deleteCluster } from './service';
import type { ClusterData, Filters } from './interface';
import { LIST_META } from '@/utills/constant';
import InputSearch from '@/components/form/InputSearch';
import { TablePaginationConfig } from 'antd/lib';
const { Title } = Typography;

const ClusterList: React.FC = () => {
  const { cluster, status, meta } = useSelector((state: RootState) => state.cluster);

  const dispatch: AppDispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [EditValue, setEditValue] = useState<ClusterData | null>(null);
  const [filters, setFilters] = useState<Filters>({
    page: 1, // Number, not a string
    pageSize: LIST_META.per_page, // Number, not a string
    pagination: true,
    search: '',
    sorter: {
      column: '',
      order: '',
    },
  });

  useEffect(() => {
    dispatch(fetchCity());
  }, []);

  useEffect(() => {
    handleGetCluster(filters);
  }, [filters]); // Include dependencies in useEffect

  const handleGetCluster = (filter: Filters): void => {
    dispatch(fetchCluster(filter));
  };

  const handleCloseModal = (): void => {
    setIsModalOpen(false);
  };

  const columns: ColumnsType<any> = [
    {
      title: 'Name',
      dataIndex: 'name',
      sorter: true,
      key: 'name',
    },
    {
      title: 'City',
      dataIndex: 'city_name',
      key: 'city_name',
      sorter: (a, b) => a.city_name.localeCompare(b.city_name),
      sortDirections: ['ascend', 'descend'],
    },
    {
      title: 'Status',
      dataIndex: 'status',
      sorter: (a, b) => a.status.localeCompare(b.status),
      key: 'status',
      className: 'w-1 nowrap',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>{status}</Tag>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      className: 'w-1 nowrap',
      render: (text, record) => (
        <Space size="small">
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            size="middle"
            title="Edit"
            onClick={() => {
              handleEdit(record);
            }}
          />
          <Popconfirm
            title="Are you sure you want to delete this item?"
            onConfirm={() => {
              handleDelete(record.id);
            }}
            okText="Yes"
            cancelText="No"
            placement="topRight"
          >
            <Button
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
              size="middle"
              title="Delete"
              danger
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleEdit = (record: ClusterData): void => {
    setEditValue(record);
    setIsModalOpen(true);
  };

  const handleDelete = (record: number): void => {
    deleteCluster(record)
      .then(() => {
        notification.success({
          message: 'Success',
          description: 'Cluster deleted successfully.',
        });
        handleGetCluster(filters);
      })
      .catch((error) => {
        notification.error({
          message: error,
          description: 'There was an error deleting the Cluster.',
        });
      });
  };

  const handleAddCluster = (): void => {
    setIsModalOpen(true);
    setEditValue(null);
  };

  const handleOk = (): void => {
    handleGetCluster(filters);
    setIsModalOpen(false);
  };

  const onChange = (pagination: TablePaginationConfig, filters: any, sorter: any): void => {
    const newFilters = {
      ...filters,
      page: pagination.current, // Use the current page from Ant Design Table
      pageSize: pagination.pageSize, // Use the page size from Ant Design Table
      sorter: {
        column: sorter.field ?? '',
        order: sorter.order === 'ascend' ? 'ASC' : 'DESC',
      },
    };

    setFilters(newFilters);
    handleGetCluster(newFilters);
  };

  return (
    <div>
      <div className="page-header">
        <Title level={2}>Cluster</Title>
        <Space size="middle">
          <InputSearch
            onSearch={(search) => {
              handleGetCluster({ ...filters, page: 1, search });
            }}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              handleAddCluster();
            }}>
                        Add New Cluster
          </Button>
        </Space>
      </div>
      <div>
        <Table
          loading={status === 'loading'}
          columns={columns}
          rowKey="id"
          bordered
          dataSource={cluster}
          onChange={onChange}
          pagination={{
            pageSize: filters.pageSize,
            current: filters.page,
            total: meta?.total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            defaultPageSize: 10,
          }}
        />
      </div>

      <ModalBox
        isModalOpen={isModalOpen}
        data={EditValue}
        handleOk={handleOk}
        handleClose={handleCloseModal}
      />
    </div>
  );
};

export default ClusterList;
