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

interface PostoAdmsProps {
  PostoAdms_id: number;
  PostoAdms_name: string;
  municipios_name: string;
}

interface ContextProps {
  postoAdms: PostoAdmsProps[];
  showSearchDialog: boolean;
  handleSearchDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_postoAdms: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_postoAdms: string | null) => void;
  selectedPostoAdms: string | null;
  getPostoAdmsLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: PostoAdmsProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  postoAdms: [],
  showSearchDialog: false,
  handleSearchDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_postoAdms: string | null) => {},
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_postoAdms: string | null) => {},
  selectedPostoAdms: null,
  getPostoAdmsLists: async () => ({ data: [], totalCount: 0 })
};

const ManagePostoAdmsContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_master_data;

const ManagePostoAdmsContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [postoAdms, setPostoAdms] = useState<PostoAdmsProps[]>([]);
  const [showSearchDialog, setShowSearchDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedPostoAdms, setSelectedPostoAdms] = useState<string | null>(null);
  const { GetData } = useCallApi();

  const navigate = useNavigate();
  const { municipioId } = useParams();

  const handleSearchDialog = useCallback((show: boolean) => {
    setShowSearchDialog(show);
  }, []);

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

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

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

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.PostoAdms_name,
        id: 'name',
        // accessorKey: 'PostoAdms_name',
        header: ({ column }) => (
          <DataGridColumnHeader title="Postu Administrativo Name" column={column} />
        ),
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.Municipios_name,
        id: 'municipios_name',
        header: ({ column }) => <DataGridColumnHeader title="Municipio 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 (
            <>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleEditDialog(true, row.PostoAdms_id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.PostoAdms_id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getPostoAdmsLists = async (
    page: number,
    limit: number,
    sorting: any,
    filters: any[] = []
  ) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      // filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };

      let filter = '';
      if (filters.length > 0 && filters[0].value) {
        filter = filters[0].value.toLowerCase();
      }

      const response = await GetData(`${API_URL}/postoadms/list`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc ? 'DESC' : 'ASC',
        filter
      });
      // console.log(response?.data);
      // const sortedList = response.data.data.list.sort((a: PostoAdmsProps, b: PostoAdmsProps) => {
      //   if (a.name < b.name) return -1;
      //   if (a.name > b.name) return 1;
      //   return 0;
      // });
      setPostoAdms(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Postu Administrativo', error);
    }
  };

  return (
    <ManagePostoAdmsContext.Provider
      value={{
        postoAdms,
        showSearchDialog,
        handleSearchDialog,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedPostoAdms,
        getPostoAdmsLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

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

export { ManagePostoAdmsContextProvider, ManagePostoAdmsContext };
export type { PostoAdmsProps };
