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

interface TransactionProps {
  id: number;
  name: string;
}

interface ContextProps {
  getTransactionLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any,
    filter: any
  ) => Promise<{ data: TransactionProps[]; totalCount: number } | undefined>;
  showDetailDialog: boolean;
  setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
  selectedTransactionId: number | null;
  setSelectedTransactionId: React.Dispatch<React.SetStateAction<number | null>>;
}

const initialProps: ContextProps = {
  getTransactionLists: async () => ({ data: [], totalCount: 0 }),
  showDetailDialog: false,
  setShowDetailDialog: () => { },
  selectedTransactionId: null,
  setSelectedTransactionId: () => { }
};

const ManageTransactionContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.transaction;

const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null);
  const [transaction, setTransaction] = useState<TransactionProps[]>([]);
  const { GetData } = useCallApi();
  const navigate = useNavigate();
  const handleNavigate = (path: string) => {
    const url = navigate(`${API_URL}/transaction/history/${path}`);
  };

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      // {
      //   accessorKey: 'transaction_date',
      //   header: ({ column }) => <DataGridColumnHeader title="Transaction Date" column={column} />,
      //   enableSorting: false,
      //   enableHiding: false,
      //   meta: {
      //     headerClassName: 'w-[250px]'
      //   }
      // },
      {
        accessorKey: 'transaction_date',
        header: ({ column }) => <DataGridColumnHeader title="Transaction Date" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
        cell: ({ row }) => {
          // Memformat tanggal dan waktu dari ISO ke format biasa (DD-MM-YYYY HH:MM:SS)
          const transactionDate = new Date(row.original.transaction_date);
          const formattedDateTime = transactionDate.toLocaleString('en-GB', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false // Gunakan format 24 jam
          });
          return formattedDateTime; // Format DD-MM-YYYY HH:MM:SS (menggunakan waktu yang sudah ada)
        }
      },      
      {
        accessorKey: 'origin_customer.fullname',
        header: ({ column }) => <DataGridColumnHeader title="Full Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => {
          const purchaseAmount = row?.purchase?.amount;
          const transferAmount = row?.transfer?.amount;

          return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(purchaseAmount ?? transferAmount ?? 0);
        },
        id: 'amount',
        header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
      },
      {
        accessorFn: (row) => {
          const purchaseAmount = row?.purchase?.fee_amount;
          const transferAmount = row?.transfer?.fee_amount;

          return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(purchaseAmount ?? transferAmount ?? 0);
        },
        id: 'feeamount',
        header: ({ column }) => <DataGridColumnHeader title="Fee Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
      },
      {
        accessorFn: (row) => {
          let status;
          if (row.status === 'C') {
            status = 'COMPLETE';
          } else if (row.status === 'F') {
            status = 'FAILED';
          } else if (row.status === 'O') {
            status = 'ON PROCESS';
          } else {
            status = 'PENDING';
          }
          return status;
        },
        accessorKey: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
      },
      {
        accessorKey: 'description',
        header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorKey: 'type.name',
        header: ({ column }) => <DataGridColumnHeader title="Name" 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 (
            <div key={`actions-${row.id}`}>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => {
                  setSelectedTransactionId(row.id);
                  setShowDetailDialog(true);
                }}
              >
                <KeenIcon icon="eye" />
              </button>
            </div>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    []);

  const getTransactionLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      let startdate;
      let enddate;
      let formattedFilter;

      if (filter == undefined || filter.length == 0) {
        const today = new Date();
        const nextWeek = new Date();
        nextWeek.setDate(today.getDate() + 7);

        startdate = today.toISOString().split('T')[0];
        enddate = nextWeek.toISOString().split('T')[0];
      } else if (filter != undefined || filter.length != 0) {
        startdate = filter[0].value.from;
        enddate = filter[0].value.to;
      }

      formattedFilter = {
        "Transactions.transaction_date": {
          from: startdate + " 00:00:00",
          to: enddate + " 23:59:59"
        }
      };

      const response = await GetData(`${API_URL}/transaction/history`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: "Transactions.created_at",
        order_direction: 'DESC',
        filter: JSON.stringify(formattedFilter)
      });

      setTransaction(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching transaction', error);
    }
  };

  return (
    <ManageTransactionContext.Provider
      value={{
        getTransactionLists,
        showDetailDialog,
        setShowDetailDialog,
        selectedTransactionId,
        setSelectedTransactionId
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DetailTransaction />

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

export { TransactionProvider, ManageTransactionContext };
export type { TransactionProps };
