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

interface feedbackProps {
  id: string;
  name: string;
  description: string;
  type: string;
  status: string;
  transactionTypeId: string;
  agentId: string;
}

interface ContextProps {
  feedback: feedbackProps[];
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_sucos: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_sucos: string | null) => void;
  selectedfeedback: string | null;
  getfeedbackLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: feedbackProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  feedback: [],
  showEditDialog: false,
  handleEditDialog: () => {},
  showAddDialog: false,
  handleAddDialog: () => {},
  showDeleteDialog: false,
  handleDeleteDialog: () => {},
  selectedfeedback: null,
  getfeedbackLists: async () => undefined
};

const ManageFeedbackMemberContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_feedback;

const ManageFeedbackMemberProvider = ({ children }: { children: React.ReactNode }) => {
  const [feedback, setFeedback] = useState([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedfeedback, setSelectedfeedback] = useState<string | null>(null);
  const { GetData } = useCallApi();

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.feedback_notes,
        id: 'feedback_notes',
        header: ({ column }) => <DataGridColumnHeader title="Feedback Notes" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.feedback_screenshot,
        id: 'feedback_screenshot',
        header: ({ column }) => <DataGridColumnHeader title="Feedback Screenshot" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.review_notes,
        id: 'review_notes',
        header: ({ column }) => <DataGridColumnHeader title="Review Notes" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.review_screenshot,
        id: 'review_screenshot',
        header: ({ column }) => <DataGridColumnHeader title="Review Screenshot" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      }
      // ,
      // {
      //   id: 'actions',
      //   header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
      //   enableSorting: false,
      //   enableHiding: false,
      //   cell: (data) => {
      //     const row = data.row.original;
      //     return (
      //       <>
      //         <button
      //           className="btn btn-sm btn-icon btn-clear btn-light"
      //           onClick={() => handleEditDialog(true, row.feedback_id)}
      //         >
      //           <KeenIcon icon="notepad-edit" />
      //         </button>
      //         <button
      //           className="btn btn-sm btn-icon btn-clear btn-light"
      //           onClick={() => handleDeleteDialog(true, row.feedback_id)}
      //         >
      //           <KeenIcon icon="trash" />
      //         </button>
      //       </>
      //     );
      //   },
      //   meta: {
      //     headerClassName: 'w-[100px] text-center',
      //     cellClassName: 'text-center'
      //   }
      // }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getfeedbackLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
      const response = await GetData(`${API_URL}/feedback/list`, {
        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(response?.data);
      setFeedback(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Feedback Member', error);
    }
  };


  return (
    <ManageFeedbackMemberContext.Provider
      value={{
        feedback,
        showEditDialog,
        handleEditDialog,
        showAddDialog,
        handleAddDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedfeedback,
        getfeedbackLists
      }}
    >
      <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 }) =>
          getfeedbackLists(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageFeedbackMemberContext.Provider>
  );
};

export { ManageFeedbackMemberContext, ManageFeedbackMemberProvider};
export type { feedbackProps };
