import { DataGridColumnHeader, DataGridProvider } 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 axios from 'axios';
import { createContext, useCallback, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import ListToolbar from '../blocks/ListToolbar';

interface PostoAdmsProps {
  id: number;
  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 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.id,
        id: 'id',
        header: ({ column }) => <DataGridColumnHeader title="ID" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px]'
        }
      },
      {
        accessorFn: (row) => row.name,
        id: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Municipios Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[1000px]'
        }
      },
      {
        id: 'actions',
        header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[100px], text-center',
          cellClassName: 'text-center'
        },
        cell: (info) => (
          <Button
            variant={'outline'}
            onClick={() => navigate(`/master-data/municipios/postoadms/${info.row.original.id}`)}
          >
            Details
          </Button>
        )
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const getPostoAdmsLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting: sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
      const response = await axios.get(`${API_URL}/postoadms/list`, {
        params: {
          limit,
          page: page + 1,
          with_deleted: false,
          order_field: sorting[0].id,
          order_direction: sorting[0].desc ? 'DESC' : 'ASC'
        }
      });
      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.data.list);
      return { data: response.data.data.list, totalCount: response.data.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: 25 }}
        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 };
