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 ProviderProps {
  id: string;
  name: string;
  description: string;
  type: string;
  status: string;
  transactionTypeId: string;
  agentId: string;
}

interface ContextProps {
  provider: ProviderProps[];
  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;
  selectedProvider: string | null;
  getProviderLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: ProviderProps[]; totalCount: number } | undefined>;
}

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

const ManageProviderContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_master_data;

const ManageProviderContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [provider, setProvider] = useState([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
  const { GetData } = useCallApi();

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.provider_name,
        id: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.provider_description,
        id: 'description',
        header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => {
          const typeMapping: Record<string, string> = {
            h2h: 'Host To Host',
            agent: 'Agent'
          };
          return typeMapping[row.provider_type] || row.provider_type;
        },
        id: 'type',
        header: ({ column }) => <DataGridColumnHeader title="Type" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.provider_status,
        id: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: true,
        enableHiding: false,
        cell: ({ row }) => {
          const isActive = row.original.provider_status === 'Y';

          return (
            <span
              className={`px-2 py-1 text-xs font-semibold rounded-full ${
                isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
              }`}
            >
              {isActive ? 'Active' : 'Inactive'}
            </span>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      },
      {
        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.provider_id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.provider_id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

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

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

export { ManageProviderContext, ManageProviderContextProvider };
export type { ProviderProps };
