import React, { createContext, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom'; // FIXED HERE
import { ColumnDef } from '@tanstack/react-table';
import axios from 'axios';

import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';

import ListToolbar from '../blocks/ListToolbar';
import DetailApprovalTransaction from '../blocks/DetailApprovalTransaction';
import ApprovalDialog from '../blocks/ApprovalDialog';

import { Button } from '@/components/ui/button';

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

interface ContextProps {
  getTransactionLists: (
    page: number,
    limit: number,
    sorting: any,
    filter: any
  ) => Promise<{ data: ApprovalTransactionProps[]; totalCount: number } | undefined>;
  showDetailDialog: boolean;
  setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
  showApprovalDialog: boolean;
  setShowApprovalDialog: React.Dispatch<React.SetStateAction<boolean>>;
  selectedTransactionId: number | null;
  setSelectedTransactionId: React.Dispatch<React.SetStateAction<number | null>>;
  selectedTransactionIdForApproval: number | null;
  setSelectedTransactionIdForApproval: React.Dispatch<React.SetStateAction<number | null>>;
}

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

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

const ApprovalTransactionProvider = ({ children }: { children: React.ReactNode }) => {
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [showApprovalDialog, setShowApprovalDialog] = useState(false);
  const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null);
  const [selectedTransactionIdForApproval, setSelectedTransactionIdForApproval] = useState<number | null>(null);
  const [transaction, setTransaction] = useState<ApprovalTransactionProps[]>([]);

  const { GetData } = useCallApi();
  const navigate = useNavigate();

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorKey: 'transaction_date',
        header: ({ column }) => <DataGridColumnHeader title="Transaction Date" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
        cell: ({ row }) => {
          const transactionDate = new Date(row.original.transaction_date);
          return transactionDate.toLocaleString('en-GB', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false,
          });
        },
      },
      {
        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 purchaseFee = row?.purchase?.fee_amount;
          const transferFee = row?.transfer?.fee_amount;
          return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
          }).format(purchaseFee ?? transferFee ?? 0);
        },
        id: 'feeamount',
        header: ({ column }) => <DataGridColumnHeader title="Fee Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
      },
      {
        accessorFn: (row) => {
          switch (row.status) {
            case 'C': return 'COMPLETE';
            case 'F': return 'FAILED';
            case 'O': return 'ON PROCESS';
            default: return 'PENDING';
          }
        },
        id: '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]',
        },
      },
      {
        accessorFn: (row) => {
          switch (row.status_approve) {
            case 'W': return 'WAITING APPROVAL';
            case 'Y': return 'APPROVED';
            case 'N': return 'REJECTED';
            default: return 'PENDING';
          }
        },
        id: 'status_approve',
        header: ({ column }) => <DataGridColumnHeader title="Status" 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}`} className="flex gap-2 justify-center">
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => {
                  setSelectedTransactionId(row.id);
                  setShowDetailDialog(true);
                }}
              >
                <KeenIcon icon="eye" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => {
                  setSelectedTransactionIdForApproval(row.id);
                  setShowApprovalDialog(true);
                }}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
            </div>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center',
        },
      },
    ],
    []
  );

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

      if (!filter || 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 {
        startdate = filter[0]?.value?.from;
        enddate = filter[0]?.value?.to;
      }

      const formattedFilter = {
        "Transactions.transaction_date": {
          from: `${startdate} 00:00:00`,
          to: `${enddate} 23:59:59`,
        },
        "Transactions.status_approve": { in: ["W", "Y", "N"] },
      };

      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 || 0,
      };
    } catch (error) {
      console.error('Error fetching transaction', error);
    }
  };

  return (
    <ManageApprovalTransactionContext.Provider
      value={{
        getTransactionLists,
        showDetailDialog,
        setShowDetailDialog,
        showApprovalDialog,
        setShowApprovalDialog,
        selectedTransactionId,
        setSelectedTransactionId,
        selectedTransactionIdForApproval,
        setSelectedTransactionIdForApproval,
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DetailApprovalTransaction />
      <ApprovalDialog />

      <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>
    </ManageApprovalTransactionContext.Provider>
  );
};

export { ApprovalTransactionProvider, ManageApprovalTransactionContext };
export type { ApprovalTransactionProps };
