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

const GruposListado = () => {

  const titulo = "Grupos";
  const url = "/administracion/grupos";
  const history = useHistory();
  const { confirm } = Modal;

  const [ reporteCargando, setReporteCargando ] = useState(false)
  const [ cargandoGrupos, setCargandoGrupos ] = useState(true);
  const [ grupos, setGrupos ] = 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={[
            {
              disabled: reporteCargando, 
              name: "Descargar reporte",
              icon: <FileExcelOutlined />,
              onClick: () => obtenerReporte(item)
            },
            {
              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: "Ciudad",
      dataIndex: "ciudad",
      key: "ciudad",
      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+'/nuevo'),
    icon: <PlusCircleOutlined />,
    props: { disabled: false, type: 'primary', }
  }];

  const obtenerReporte = async (item) => {

    try {
      setReporteCargando(true);
      const idGrupo = item?.id;

      const q = query( collection(firestore, "usuarios"), where('grupos', 'array-contains-any', [idGrupo]));
      const querySnapshot = await getDocs(q);
      const docs = []
      
      querySnapshot.forEach((doc) => {
        const data = doc.data();
        docs.push({
          nombre: data?.nombre,
          email: data?.email,
          telefono: data?.telefono,
          facebook: data?.facebook,
          instagram: data?.instagram,
          twitter: data?.twitter,
          verificado: data?.verificado === '' ? '-----' : 'SÍ'
        });
      });

      const columnas = [
        { title: 'Nombre', key: 'nombre' },
        { title: 'Email', key: 'email' },
        { title: 'Teléfono', key: 'telefono' },
        { title: 'Facebook', key: 'facebook' },
        { title: 'Instagram', key: 'instagram' },
        { title: 'Twitter', key: 'twitter' },
        { title: 'Verificado', key: 'verificado' },
      ];

      await exportarExcelJS(columnas, docs, 'reporte grupos', "Reporte Yager", 'Grupos', '/LAUD-Logotipo.png',"")


    } catch (error) {
      console.log('error al obtener reporte: ', error);
      Modal.warning({
        title: 'Atención',
        content: 'Hubo un problema al generar reporte, intentalo de nuevo.',
      });
    } finally {
      setReporteCargando(false)
    }
    
  };

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

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

  // Grupos
  useEffect (() => {  
    try {
      onSnapshot( collection(firestore, "grupos"), (querySnapshot) => {
         const docs = [];
         querySnapshot.forEach((doc) => {
          if( doc.data().estatus ) {
            docs.push({ ...doc.data(), id:doc.id });
          }
         });
         setGrupos(docs);
       })
     } catch (error) {
       console.log('error al cargar eventos de firebase: ', error);
     } finally {
       setCargandoGrupos(false);
     }
  }, [] );


  return (
    <SimpleTableLayout 
      title={titulo}
      multipleButtonData={multipleButtonData}
      onSearchClicked={onSearch}
    >
      <Table
        dataSource={searchInput.length > 1 ? filteredResults : grupos}
        rowKey="id"
        loading={cargandoGrupos}
        columns={columns}
        size='small'
        scroll={{ x: 700 }}
      />
    </SimpleTableLayout>
  )
}

export default GruposListado