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, useEffect } from 'react';
import { Toaster } from 'sonner';
import FeedbackDetail from '../blocks/FeedbackDetail';
import FeedbackEditDialog from '../blocks/EditDialog';
import { useNavigate } from 'react-router';

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

interface FetchParams {
  pageIndex: number;
  pageSize: number;
  sorting: any[];
  columnFilters: any[];
}

interface ContextProps {
  feedback: feedbackProps[];
  showDetailDialog: boolean;
  handleDetailDialog: (show: boolean, selected_feedback: string | null) => void;
  selectedFeedback: string | null;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_feedback: string | null) => void;
  getfeedbackLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: feedbackProps[]; totalCount: number } | undefined>;
  refreshData: () => void;
}

const initialProps: ContextProps = {
  feedback: [],
  showDetailDialog: false,
  handleDetailDialog: () => {},
  selectedFeedback: null,
  showEditDialog: false,
  handleEditDialog: () => {},
  getfeedbackLists: async () => undefined,
  refreshData: () => {}
};

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 [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedFeedback, setSelectedFeedback] = useState<string | null>(null);
  const { GetData } = useCallApi();

  const [refreshTrigger, setRefreshTrigger] = useState(0);

  const [lastFetchParams, setLastFetchParams] = useState<FetchParams | null>(null);

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

  const handleDetailDialog = useCallback((show: boolean, selected_feedback: string | null) => {
    setShowDetailDialog(show);
    setSelectedFeedback(show ? selected_feedback : null);
  }, []);

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

  const refreshData = useCallback(() => {
    setRefreshTrigger((prev) => prev + 1);
  }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.fullname,
        id: 'customer_id',
        header: ({ column }) => <DataGridColumnHeader title="Customer Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.feedbacks_emotion,
        id: 'feedback_emotion',
        header: ({ column }) => <DataGridColumnHeader title="Emotion" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.feedbacks_feedback_notes,
        id: 'feedback_notes',
        header: ({ column }) => <DataGridColumnHeader title="Feedback Notes" 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={() => {
                  setSelectedFeedback(row.feedbacks_id);
                  handleDetailDialog(true, row.feedbacks_id);
                }}
                title="View Details"
              >
                <KeenIcon icon="eye" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[150px] text-center',
          cellClassName: 'text-center'
        }
      }
    ],
    []
  );

  const getfeedbackLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      setLastFetchParams({
        pageIndex: page,
        pageSize: limit,
        sorting: sorting,
        columnFilters: filter
      });

      sorting = sorting.length == 0 ? [{ id: 'feedbacks_created_at', desc: true }] : 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'
      });
      // 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);
    }
  };

  useEffect(() => {
    if (refreshTrigger > 0 && lastFetchParams) {
      getfeedbackLists(
        lastFetchParams.pageIndex,
        lastFetchParams.pageSize,
        lastFetchParams.sorting,
        lastFetchParams.columnFilters
      );
    }
  }, [refreshTrigger]);

  return (
    <ManageFeedbackMemberContext.Provider
      value={{
        feedback,
        showDetailDialog,
        handleDetailDialog,
        selectedFeedback,
        showEditDialog,
        handleEditDialog,
        getfeedbackLists,
        refreshData
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

      <DataGridProvider
        columns={columns}
        pagination={{ size: 10 }}
        layout={{ card: true }}
        sorting={[{ id: 'feedbacks_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 };
