import React, { useEffect, useState } from 'react';
import { Table, Modal } from 'antd';
import { useHistory } from 'react-router-dom';
import { EditOutlined, DeleteOutlined, PlusCircleOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import { firestore } from "../../../services/firebase";
import { ActionsButton } from '../../../components';
import { SimpleTableLayout } from '../../../components/layouts'
import { collection, onSnapshot, doc, updateDoc } from "firebase/firestore";
import moment from 'moment';

const DependenciasListado = () => {

  const titulo = "Dependencias";
  const firebaseCollection = "dependencias";
  const url = "/administracion/dependencias";
  const history = useHistory();
  const { confirm } = Modal;

  const [cargandoDependencias, setCargandoDependencias] = useState(true);
  const [dependencias, setDependencias] = useState([]);
  const [filteredResults, setFilteredResults] = useState([]);
  const [searchInput, setSearchInput] = useState('');

  const defaultText = prop => prop || <span style={{ color: '#c7c3c3' }}>---</span>;

  const columns = [
    {
      title: "Acciones",
      dataIndex: "id",
      key: "id",
      align: "center",
      width: 100,
      render: (_, item ) => (
        <ActionsButton
          key={item}
          options={[
            {
              name: "Editar",
              icon: <EditOutlined />,
              onClick: () => history.push(url+'/detalle?id='+item.id)
            },
            {
              name: "Eliminar",
              icon: <DeleteOutlined />,
              onClick: () => {
                eliminarRegistro(item)
              },
              styleProps: { color: '#e91e63' },
            },
          ]}
        />
      )
    },
    {
      title: "Nombre",
      dataIndex: "nombre",
      key: "nombre",
      render: defaultText,
    },
    {
      title: "Creado",
      dataIndex: "timestamp",
      key: "timestamp",
      render: (_, item) => (
        moment(item?.timestamp?.toDate()).format('DD-MM-YYYY')
      ),
    },
  ];
  
  const multipleButtonData = [{
    text: "Agregar",
    to: () => history.push(url+'/nueva'),
    icon: <PlusCircleOutlined />,
    props: { disabled: false, type: 'primary', }
  }];

  const eliminarRegistro = async (item) => {
    confirm({
      title: `Atención`,
      icon: <ExclamationCircleOutlined />,
      content: '¿Seguro que desea eliminar este registro?',
      onOk: async () => {
        try {
          await updateDoc(doc(firestore, firebaseCollection, item.id), {estatus: false}); 
        } catch (error) {
          console.log('error al eliminar: ', error);
        }
      },
      onCancel() {},
    });
  };

  const onSearch = (searchValue) =>  {
    setSearchInput(searchValue);
    if( searchValue !== '' ){
      const filteredData = dependencias.filter((item) => {
        return Object.values(item).join('').toLowerCase().includes(searchValue.toLowerCase());
      })
      setFilteredResults(filteredData);
    }else{
      setFilteredResults(dependencias);
    }
  };

  // Dependencias
  useEffect (() => {  
    try {
      onSnapshot( collection(firestore, firebaseCollection), (querySnapshot) => {
         const docs = [];
         querySnapshot.forEach((doc) => {
          if( doc.data().estatus ) {
            docs.push({ ...doc.data(), id:doc.id });
          }
         });
         setDependencias(docs);
       })
     } catch (error) {
       console.log('error al cargar dependencias de firebase: ', error);
     } finally {
      setCargandoDependencias(false);
     }
  }, []);
  
  return (
    <SimpleTableLayout 
      title={titulo}
      multipleButtonData={multipleButtonData}
      onSearchClicked={onSearch}
    >
      <Table
        dataSource={searchInput.length > 1 ? filteredResults : dependencias}
        rowKey="id"
        loading={cargandoDependencias}
        columns={columns}
        size='small'
        scroll={{ x: 700 }}
      />
    </SimpleTableLayout>
  )
}

export default DependenciasListado