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 moment from 'moment';
import DetailTransaction from '../blocks/DetailTransaction';
import TransactionLogViewer from '../blocks/DetailTransactionLog';

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>>;
  showUploadBatchDialog: boolean;
  handleUploadBatchDialog: (show: boolean) => void;
  showDetailLogDialog: boolean;
  // handleDetailLogDialog: (show: boolean) => void;
  setShowDetailLogDialog: React.Dispatch<React.SetStateAction<boolean>>;
  setDetailLogData: React.Dispatch<React.SetStateAction<any | null>>;
  detailLogData: any | null
}

const initialProps: ContextProps = {
  getTransactionLists: async () => ({ data: [], totalCount: 0 }),
  showDetailDialog: false,
  setShowDetailDialog: () => { },
  selectedTransactionId: null,
  setSelectedTransactionId: () => { },
  showUploadBatchDialog: false,
  handleUploadBatchDialog: (show: boolean) => {},
  showDetailLogDialog: false,
  // handleDetailLogDialog: (show: boolean) => {},
  setShowDetailLogDialog: () => { },
  setDetailLogData: () => {},
  detailLogData: null,
};

type StatusCode = 'W' | 'P' | 'F' | 'D' | 'Y';

interface StatusInfo {
  label: string;
  bg: string;
  text: string;
}

const statusMap: Record<StatusCode, StatusInfo> = {
  W: { label: 'Waiting', bg: 'bg-yellow-100', text: 'text-yellow-600' },
  P: { label: 'Pending', bg: 'bg-blue-100', text: 'text-blue-600' },
  F: { label: 'Fail', bg: 'bg-red-100', text: 'text-red-600' },
  D: { label: 'Done', bg: 'bg-green-100', text: 'text-green-600' },
  Y: { label: 'Active', bg: 'bg-green-100', text: 'text-green-600' },
};


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

const TransactionProvider = ({ children }: { children: React.ReactNode }) => {
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedTransactionId, setSelectedTransactionId] = useState<number | null>(null);
  const [showUploadBatchDialog, setShowUploadBatchDialog] = useState(false);
  const [showDetailLogDialog, setShowDetailLogDialog] = useState(false);
  const [detailLogData, setDetailLogData] = useState<any | null>(null);
  const [transaction, setTransaction] = useState<TransactionProps[]>([]);
  const { GetData } = useCallApi();
  const navigate = useNavigate();
  
  const handleUploadBatchDialog = useCallback((show: boolean) => {
    setShowUploadBatchDialog(show);
  }, []);
  // const handleDetailLogDialog = useCallback((show: boolean) => {
  //   setShowDetailLogDialog(show);
  // }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorKey: 'file_name',
        header: ({ column }) => <DataGridColumnHeader title="File Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
      },
      {
        accessorFn: (row) => {
          return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(row.amount);
        },
        id: 'amount',
        header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]',
        },
      },
      {
        accessorKey: 'total_record',
        header: ({ column }) => <DataGridColumnHeader title="Total Record" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
      },
      {
        accessorKey: 'total_success',
        header: ({ column }) => <DataGridColumnHeader title="Success Record" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
      },
      {
        accessorKey: 'total_fail',
        header: ({ column }) => <DataGridColumnHeader title="Fail Record" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
      },
      {
        accessorKey: 'total_pending',
        header: ({ column }) => <DataGridColumnHeader title="Pending Record" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        },
      },
      {
        accessorFn: (row) => row.status,
        id: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: ({ row }) => {
          const status = row.original.status as StatusCode;
          const { label, bg, text } = statusMap[status] ?? {
            label: 'Unknown',
            bg: 'bg-gray-100',
            text: 'text-gray-600',
          };
      
          return (
            <span
              className={`px-2 py-1 text-xs font-semibold rounded-full ${bg} ${text}`}
            >
              {label}
            </span>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center',
        },
      },
      {
        accessorFn: (row) => row.execution_date,
        id: 'execution_date',
        header: ({ column }) => <DataGridColumnHeader title="Execution Date" column={column} />,
        enableSorting: true,
        enableHiding: false,
        cell: ({ row }) => moment(row.original.execution_date).format('DD/MM/YYYY HH:mm:ss')
      },
      {
        accessorFn: (row) => row.done_date,
        id: 'done_date',
        header: ({ column }) => <DataGridColumnHeader title="Done Date" column={column} />,
        enableSorting: true,
        enableHiding: false,
        cell: ({ row }) => row.original.done_date ? moment(row.original.done_date).format('DD/MM/YYYY HH:mm:ss') : ''
      },
      {
        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 = {
        
      };

      const response = await GetData(`${API_URL}/transaction/history`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: "id",
        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,
        handleUploadBatchDialog,
        showUploadBatchDialog,
        // handleDetailLogDialog,
        showDetailLogDialog,
        setShowDetailLogDialog,
        setDetailLogData,
        detailLogData
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DetailTransaction />
      <TransactionLogViewer />

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