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 ProductsProps {
  products_name: string;
  products_description: string;
  products_price_point: number;
  products_price_cash: number;
  products_status: string;
  products_providerId: string;
}

interface ContextProps {
  products: ProductsProps[];
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_products: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_products: string | null) => void;
  selectedProducts: string | null;
  getProductsLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: ProductsProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  products: [],
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_products: string | null) => {},
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_products: string | null) => {},
  selectedProducts: null,
  getProductsLists: async () => undefined
};

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

const ManageProductsContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [products, setProducts] = useState([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedProducts, setSelectedProducts] = useState<string | null>(null);
  const { GetData } = useCallApi();

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.code,
        id: 'code',
        header: ({ column }) => <DataGridColumnHeader title="Code" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        },
        filterFn: (row, id, value) => {
          return row.original.products_name.toLowerCase().includes(value.toLowerCase());
        }
      },
      {
        accessorFn: (row) => row.name,
        id: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
        filterFn: (row, id, value) => {
          return row.original.products_name.toLowerCase().includes(value.toLowerCase());
        }
      },
      {
        accessorFn: (row) => row.description,
        id: 'description',
        header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.provider?.name,
        id: 'provider_name',
        header: ({ column }) => <DataGridColumnHeader title="Provider Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.type,
        id: 'type',
        header: ({ column }) => <DataGridColumnHeader title="Type" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[150px]'
        }
      },
      {
        accessorFn: (row) => row.price_point,
        id: 'price_point',
        header: ({ column }) => <DataGridColumnHeader title="Price Point" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.price_cash,
        id: 'price_cash',
        header: ({ column }) => <DataGridColumnHeader title="Price Cash" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.cashback_point,
        id: 'cashback_point',
        header: ({ column }) => <DataGridColumnHeader title="Cashback Point" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.cashback_cash,
        id: 'cashback_cash',
        header: ({ column }) => <DataGridColumnHeader title="Cashback Cash" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.process_on_third_party,
        id: 'process_on_third_party',
        header: ({ column }) => <DataGridColumnHeader title="Third Party" column={column} />,
        cell: ({ row }) => {
          const isActive = row.original.process_on_third_party === 'Y';

          return <span>{isActive ? 'Yes' : 'No'}</span>;
        },
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.status,
        id: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        cell: ({ row }) => {
          const isActive = row.original.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>
          );
        },
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        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.id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getProductsLists = 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}/product/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);
      setProducts(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Products', error);
    }
  };

  return (
    <ManageProductsContext.Provider
      value={{
        products,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedProducts,
        getProductsLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

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

export { ManageProductsContext, ManageProductsContextProvider };
export type { ProductsProps };
