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';
import ShowDetailDialog from '../blocks/ShowDetailDialog';

interface ContextProps {
  showDetailDialog: boolean;
  setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
  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: any | null;
}

const initialProps: ContextProps = {
  showDetailDialog: false,
  setShowDetailDialog: () => {},
  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 [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedNotification, setSelectedNotification] = useState<any | 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: true,
        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-[350px]',
          searchable: true
        },
        cell: ({ row }) => {
          const content = row.original.content;
          const paragraphs = content.split(/\n+/);

          const preview = paragraphs.slice(0, 2).join('\n');
          const isTruncated = paragraphs.length > 2;

          return (
            <div className="whitespace-pre-wrap">
              {preview}
              {isTruncated && '...'}
            </div>
          );
        }
      },
      {
        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
      },
      {
        accessorKey: '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')
      },
      {
        accessorKey: 'detail',
        id: 'detail',
        header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: (data) => {
          const row = data.row.original;
          return (
            <div key={`actions-${row.id}`} className="flex gap-2 justify-center">
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => {
                  setSelectedNotification(row);
                  setShowDetailDialog(true);
                }}
              >
                <KeenIcon icon="eye" />
              </button>
            </div>
          );
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getNotificationList = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      const sortField = sorting.length > 0 ? sorting[0].id : 'created_at';
      const sortDirection = sorting.length > 0 ? (sorting[0].desc ? 'DESC' : 'ASC') : 'DESC';

      // Initialize filter object
      let filterParams: any = {};

      // Process filter array
      if (Array.isArray(filter)) {
        filter.forEach((f: any) => {
          if (f.id === 'content' && f.value) {
            filterParams.content = { like: `%${f.value.toLowerCase()}%` };
          }

          // Handle date range filter
          if (f.id === 'created_at' && f.value?.from && f.value?.to) {
            filterParams.created_at = {
              from: `${f.value.from} 00:00:00`,
              to: `${f.value.to} 23:59:59`
            };
          }
        });
      }

      const response = await GetData(`${API_URL_NOTIFICATION}/list`, {
        limit: limit,
        page: page + 1,
        with_deleted: false,
        order_field: sortField,
        order_direction: sortDirection,
        filter: JSON.stringify(filterParams)
      });
      // 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={{
          showDetailDialog,
          setShowDetailDialog,
          handleAddDialog,
          showAddDialog,
          handleEditDialog,
          showEditDialog,
          handleDeleteDialog,
          showDeleteDialog,
          selectedNotification
        }}
      >
        <Toaster expand visibleToasts={9} duration={3000} />

        <ShowDetailDialog />

        <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 };
