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';
import { log } from 'console';
import ResendTransaction from '../blocks/ResendTransaction';
import { comment } from 'stylis';

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>>;
  showResendDialog: boolean;
  handleResendDialog: (show: boolean, selected_transaction: string | null) => void;
  selectedTransactionForResend: string | null;
}

const initialProps: ContextProps = {
  getTransactionLists: async () => ({ data: [], totalCount: 0 }),
  showDetailDialog: false,
  setShowDetailDialog: () => { },
  selectedTransactionId: null,
  setSelectedTransactionId: () => { },
  showResendDialog: false,
  handleResendDialog: (show: boolean, selected_transaction: string | null) => { },
  selectedTransactionForResend: null
};

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 [showResendDialog, setShowResendDialog] = useState(false);
  const [selectedTransactionForResend, setSelectedTransactionForResend] = useState<string | null>(null);

  const handleResendDialog = useCallback((show: boolean, selected_transaction: string | null) => {
    setSelectedTransactionForResend(show ? selected_transaction : null);
    setShowResendDialog(show);
  }, []);


  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]',
        },
      },
      {
        accessorKey: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
        cell: ({ row }) => {
          const statusCode = row.original.status;
          let label = '';
          let badgeClass = '';

          switch (statusCode) {
            case 'C':
              label = 'COMPLETE';
              badgeClass = 'bg-green-100 text-green-800';
              break;
            case 'F':
              label = 'FAILED';
              badgeClass = 'bg-red-100 text-red-800';
              break;
            case 'O':
              label = 'ON PROCESS';
              badgeClass = 'bg-blue-100 text-blue-800';
              break;
            default:
              label = 'PENDING';
              badgeClass = 'bg-gray-100 text-gray-800';
              break;
          }

          return (
            <span className={`px-3 py-1 rounded-full text-xs font-semibold ${badgeClass}`}>
              {label}
            </span>
          );
        },
      },
      {
        accessorKey: 'description',
        header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorKey: 'type.name',
        header: ({ column }) => <DataGridColumnHeader title="Transaction Type" 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;
          const isVisible = row.status === 'F' ? true : false || row.status === 'P' ? true : false;
          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>
              {/* add new button for resend transaction failed */}
              {isVisible &&
                <button
                  className="btn btn-sm btn-icon btn-clear btn-light"
                  title="Retry Transaction"
                  onClick={() => {
                    handleResendDialog(true, row.id);
                  }}
                >
                  <KeenIcon icon="abstract-37" />
                </button>
              }
            </div>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleResendDialog]);

  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();

        // Tanggal 1 di bulan sekarang
        const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

        startdate = firstDayOfMonth.toISOString().split('T')[0];
        enddate = today.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,
        showResendDialog,
        handleResendDialog,
        selectedTransactionForResend
      }}
    >
      <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 };
