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';

interface CurrencyProps {
  ID: string;
  name: string;
}

interface Conversion {
  id: string;
  id_currency_origin: string;
  id_currency_destination: string;
  buy: number;
  sell: number;
  status: string;
}

interface ContextProps {
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_conversion: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_conversion: string | null) => void;
  selectedConversion: string | null;
  conversion: string | null;
}

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

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

const ManageConversionContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const { GetData } = useCallApi();
  const [selectedConversion, setSelectedConversion] = useState<string | null>(null);
  const [conversion, setConversion] = useState<string | null>(null);

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.currency_origin.name,
        id: 'id_currency_origin',
        header: ({ column }) => <DataGridColumnHeader title="Currency Origin" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.currency_destination.name,
        id: 'id_currency_destination',
        header: ({ column }) => <DataGridColumnHeader title="Currency Destination" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.buy,
        id: 'buy',
        header: ({ column }) => <DataGridColumnHeader title="Buy" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => row.sell,
        id: 'sell',
        header: ({ column }) => <DataGridColumnHeader title="Sell" 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 doGetConversion = 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/conversion/`, {
      limit: 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">
      <ManageConversionContext.Provider
        value={{
          showEditDialog,
          handleEditDialog,
          showAddDialog,
          handleAddDialog,
          showDeleteDialog,
          handleDeleteDialog,
          selectedConversion,
          conversion
        }}
      >
        <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, columnFilters }) =>
              doGetConversion(pageIndex, pageSize, sorting, columnFilters)
            }
          >
            {children}
          </DataGridProvider>
        </div>
      </ManageConversionContext.Provider>
    </div>
  );
};

export { ManageConversionContext, ManageConversionContextProvider };
export type { Conversion };
