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

interface Currency {
  id: string;
  code: string;
  name: string;
  prefix: string;
  status: string;
}

interface ContextProps {
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_currency: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_currency: string | null) => void;
  selectedCurrency: string | null;
  currency: string | null;
}

const initialProps: ContextProps = {
  showEditDialog: false,
  handleEditDialog: () => {},
  showAddDialog: false,
  handleAddDialog: () => {},
  showDeleteDialog: false,
  handleDeleteDialog: () => {},
  selectedCurrency: null,
  currency: null
};

const ManageCurrencyContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_wallet;

const ManageCurrencyContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const { GetData } = useCallApi();
  const [selectedCurrency, setSelectedCurrency] = useState<string | null>(null);
  const [currency, setCurrency] = useState<string | null>(null);

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.name,
        id: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.code,
        id: 'code',
        header: ({ column }) => <DataGridColumnHeader title="Code" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.prefix,
        id: 'prefix',
        header: ({ column }) => <DataGridColumnHeader title="Prefix" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.status,
        id: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' },
        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>
          );
        }
      },
      {
        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 doGetCurrency = async (
    page: number,
    limit: number,
    sorting: any
    // filter: any
  ) => {
    // sorting = sorting.length == 0 ? [{ id: 'name', desc: true }] : sorting;
    // filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
    // console.log(sorting);
    const response = await GetData(`${API_URL}/dashboard/currency/`, {
      limit,
      page: page + 1,
      with_deleted: false,
      order_field: sorting[0].id,
      order_direction: sorting[0].desc ? 'ASC' : 'DESC'
      // filter: JSON.stringify(filter)
    });
    // console.log(response?.data);
    return { data: response?.data.list, totalCount: response?.data.total_count };
  };

  return (
    <div className="min-h-screen">
      <ManageCurrencyContext.Provider
        value={{
          showEditDialog,
          handleEditDialog,
          showAddDialog,
          handleAddDialog,
          showDeleteDialog,
          handleDeleteDialog,
          selectedCurrency,
          currency
        }}
      >
        <Toaster expand visibleToasts={9} duration={3000} />

        <div className="px-4">
          <DataGridProvider
            columns={columns}
            pagination={{ size: 10 }}
            layout={{ card: true }}
            toolbar={<ListToolbar />}
            sorting={[{ id: 'ID', desc: true }]}
            serverSide={true}
            onFetchData={({ pageIndex, pageSize, sorting }) =>
              doGetCurrency(pageIndex, pageSize, sorting)
            }
          >
            {children}
          </DataGridProvider>
        </div>
      </ManageCurrencyContext.Provider>
    </div>
  );
};

export { ManageCurrencyContext, ManageCurrencyContextProvider };
export type { Currency };
