import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
import React, { createContext, useCallback, useMemo, useState } from 'react';
import { ListToolBar } from '../blocks/ListToolbar';
import { useCallApi } from '@/hooks';
import moment from 'moment';

interface SelectedNotification {
  all_customers: string;
  customer_name: string;
  id: string;
  content: string;
  subject: string;
  type: string;
  via: string;
  created_at: string;
}

interface ContextProps {
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_notification: string | null) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_notification: string | null) => void;
  selectedNotification: string | null;
}

const initialProps: ContextProps = {
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: () => {},
  showDeleteDialog: false,
  handleDeleteDialog: () => {},
  selectedNotification: null
};

const ManageNotifContext = createContext<ContextProps>(initialProps);
const API_URL_NOTIFICATION = apiConfig.service_notification;

const ManageNotifContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedNotification, setSelectedNotification] = useState<string | null>(null);
  const { GetData } = useCallApi();

  const handleAddDialog = useCallback((show: boolean) => {
    setShowAddDialog(show);
  }, []);

  const handleEditDialog = useCallback((show: boolean, selected_notification: string | null) => {
    setSelectedNotification(show ? selected_notification : null);
    setShowEditDialog(show);
  }, []);

  const handleDeleteDialog = useCallback((show: boolean, selected_notification: string | null) => {
    setSelectedNotification(show ? selected_notification : null);
    setShowDeleteDialog(show);
  }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => {
          if (row.all_customers === 'Y') {
            return 'All Customers';
          }
          return row.customer_name || '';
        },
        id: 'send',
        header: ({ column }) => <DataGridColumnHeader title="Send" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.content,
        id: 'content',
        header: ({ column }) => <DataGridColumnHeader title="Content" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[300px]'
        }
      },
      {
        accessorFn: (row) => row.subject,
        id: 'subject',
        header: ({ column }) => <DataGridColumnHeader title="Subject" column={column} />,
        enableSorting: true,
        enableHiding: false
      },
      {
        accessorFn: (row) => row.type,
        id: 'type',
        header: ({ column }) => <DataGridColumnHeader title="Type" column={column} />,
        enableSorting: true,
        enableHiding: false
      },
      {
        accessorFn: (row) => row.via,
        id: 'via',
        header: ({ column }) => <DataGridColumnHeader title="Via" column={column} />,
        enableSorting: true,
        enableHiding: false
      },
      {
        accessorFn: (row) => row.created_at,
        id: 'created_at',
        header: ({ column }) => <DataGridColumnHeader title="Date Create" column={column} />,
        enableSorting: true,
        enableHiding: false,
        cell: ({ row }) => moment(row.original.created_at).format('YYYY-MM-DD HH:mm:ss')
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getNotificationList = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting = sorting.length === 0 ? [{ id: 'created_at', desc: true }] : sorting;
      filter =
        filter.length == 0 ? {} : { content: { like: `%${filter[0].value?.toLowerCase()}%` } };
      const response = await GetData(`${API_URL_NOTIFICATION}/list`, {
        limit: limit,
        page: page + 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
        filter: JSON.stringify(filter)
      });
      // console.log('API Response notif: ', response);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching notification', error);
    }
  };

  return (
    <div>
      <ManageNotifContext.Provider
        value={{
          handleAddDialog,
          showAddDialog,
          handleEditDialog,
          showEditDialog,
          handleDeleteDialog,
          showDeleteDialog,
          selectedNotification
        }}
      >
        <Toaster expand visibleToasts={9} duration={3000} />

        <DataGridProvider
          columns={columns}
          pagination={{ size: 10 }}
          toolbar={<ListToolBar />}
          layout={{ card: true }}
          sorting={[{ id: 'created_at', desc: true }]}
          serverSide={true}
          onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
            getNotificationList(pageIndex, pageSize, sorting, columnFilters)
          }
        >
          {children}
        </DataGridProvider>
      </ManageNotifContext.Provider>
    </div>
  );
};

export { ManageNotifContext, ManageNotifContextProvider };
export type { SelectedNotification };
