'use client';

import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchCustomers } from './slice';
import { Button, Table, Space, Popconfirm, notification, Tag } 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 { deleteCustomer } from './service';
import { LIST_META } from '@/utills/constant';
import type { CustomerState, Filters } from './interface';
import InputSearch from '@/components/form/InputSearch';
import PageHeader from '@/components/pageHeader';
import { TablePaginationConfig } from 'antd/lib';

const CustomerList: React.FC = () => {
  const { customers, status } = useSelector((state: RootState) => state.customer);
  const dispatch: AppDispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [EditValue, setEditValue] = useState<CustomerState | null>(null);

  const [filters, setFilters] = useState</* Filters */ any>({
    page: 1,
    pageSize: 10, /* LIST_META.per_page, */

  });

  useEffect(() => {
    handleGetCustomer(filters);
  }, []);

  const handleGetCustomer = (filter: Filters): void => {
    dispatch(fetchCustomers(filter));
  };

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

  const columns: ColumnsType<any> = [
    {
      title: 'Customer Name',
      dataIndex: 'name',
      key: 'name',
      width: 280,
    },
    {
      title: 'Email Address',
      dataIndex: 'email', // Replace 'email' with the actual field name for email address
      key: 'email',
      width: 200,
    },
    {
      title: 'Phone Number',
      dataIndex: 'phone', // Replace 'phoneNumber' with the actual field name for phone number
      key: 'phone',
      width: 180,
    },
    {
      title: 'Address',
      dataIndex: 'address', // Replace 'alternatePhoneNumber' with the actual field name
      key: 'address',
      width: 250,
    },

    {
      title: 'Status',
      dataIndex: 'status', // Replace 'whatsappPhoneNumber' with the actual field name
      key: 'status',
      width: 100,
      className: 'nowrap',
      align: 'center',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'} className="capitalize">
          {status}
        </Tag>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      width: 110,
      className: 'nowrap',
      align: 'center',
      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 customer?"
            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: CustomerState): void => {
    setEditValue(record);
    setIsModalOpen(true);
  };

  const handleDelete = (record: number): void => {
    deleteCustomer(record)
      .then((response) => {
        notification.success({
          message: 'Success',
          description: response?.data?.message,
        });
        handleGetCustomer(filters);
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error?.response?.data?.message,
        });
      });
  };

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

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

  const onChange = (pagination: TablePaginationConfig, filters: any, sorter: any): void => {
    const newFilters = {
      ...filters,
      page: pagination.current,
      pageSize: LIST_META.per_page,
      sorter: {
        column: sorter.field ?? '',
        order: sorter.order === 'ascend' ? 'ASC' : 'DESC',
      },
    };

    setFilters(newFilters);
    handleGetCustomer(newFilters);
  };

  return (
    <div>
      <PageHeader
        title="Customers"
        isBack={false}
        extra={
          <Space size="middle">
            <InputSearch
              onSearch={(search) => {
                handleGetCustomer({ ...filters, page: 1, search });
              }}
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                handleAddCustomer();
              }}>
                            Add New Customer
            </Button>
          </Space>
        }
      />
      <div>
        <Table
          loading={status === 'loading'}
          columns={columns}
          rowKey="id"
          bordered
          dataSource={customers}
          onChange={onChange}
          tableLayout="fixed"
          scroll={{ x: true }}
          className="table-layout-fixed"
        />
      </div>

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

export default CustomerList;
