import React, { useEffect, useState } from 'react'
import { Table, Modal, Typography } from 'antd';
import moment from 'moment';
import { firestore } from '../../../services/firebase';
import { SimpleTableLayout } from '../../../components/layouts';
import { collection, limit, query, orderBy, getDocs } from 'firebase/firestore';
import { CheckCircleOutlined, MinusCircleOutlined, WhatsAppOutlined } from '@ant-design/icons';

const { Text } = Typography;

const Notificaciones = () => {

  const [searchInput, setSearchInput] = useState('');
  const [data, setData] = useState([]);
  const [filteredResults, setFilteredResults] = useState([]);
  const [visible, setVisible] = useState(false);
  const [dataModal, setDataModal] = useState(null);

  const columns = [
    {
      title: 'titulo',
      dataIndex: 'titulo',
    },
    {
      title: 'Plantilla',
      dataIndex: 'plantilla',
      render: (_, item) => renderPlantilla(item)
    },
    {
      title: 'Creado',
      dataIndex: 'fecha',
      render: (_, item) =>  moment(item?.fecha?.toDate()).format("DD-MM-YYYY HH:mm:ss")
    },
    {
      title: 'Enviado',
      dataIndex: 'enviado',
      render: (_, item) =>  moment(item?.enviado?.toDate()).format("DD-MM-YYYY HH:mm:ss")
    },

  ];

  const renderPlantilla = (item) => {
    const plantilla = item?.plantilla;
    let txtPlantilla = "";  
    if(plantilla === "recordatorio") {
      txtPlantilla = "Recordatorio"
    } else if (plantilla === "nuevo_evento") {
      txtPlantilla = "Nuevo Evento"
    } else if (plantilla === "evento_gracias") {
      txtPlantilla = "Evento Gracias"
    }

    return txtPlantilla;
  };

  const renderRedSocial = (red) => {
    if(red) {
      return <CheckCircleOutlined style={{ color: '#2196f3', fontSize: '1.3em'  }} />
    } else {
      return <MinusCircleOutlined style={{ color: '#c2c2c2', fontSize: '1.3em'  }} />
    }
  };

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

  const obtenerDatos = async () => {
    try {
      const ref = collection(firestore, "notificaciones");
      const q = query(ref, orderBy("fecha", "desc"), limit(20));
      const querySnapshot = await getDocs(q);
      const docs = [];
      querySnapshot.forEach((doc) => {
        docs.push({ ...doc.data(), id:doc.id });
      });
      setData(docs)
    } catch (error) {
      console.log('error al obtener datos: ', error);
    }
  };

  const ModalComponent = () => {
    if( !dataModal ) return <></>;

    const columnsModal = [
      {
        title: 'Nombre',
        dataIndex: 'nombre',
      },
      {
        title: 'Teléfono',
        dataIndex: 'telefono',
      },
      {
        title: 'Enviado',
        dataIndex: 'enviado',
        align: 'center',
        render: (_, item) => item?.detalle ? <WhatsAppOutlined style={{ color: '#38cf3d', fontSize: '1.3em' }} /> : <MinusCircleOutlined  style={{ color: '#c2c2c2', fontSize: '1.3em'  }} />,
      },
      {
        title: 'Facebook',
        dataIndex: 'fb',
        align: 'center',
        render: (_, item) => renderRedSocial(item?.fb)
      },
      {
        title: 'Twitter',
        dataIndex: 'tw',
        align: 'center',
        render: (_, item) => renderRedSocial(item?.tw)
      },
      {
        title: 'Instagram',
        dataIndex: 'ig',
        align: 'center',
        render: (_, item) => renderRedSocial(item?.ig)
      },
    ];

    return (
      <Modal 
        title={ `Usuarios notificados: ${dataModal?.titulo}` }
        centered
        open={visible}
        okButtonProps={{ style: { display: 'none' } }}
        cancelText="Cerrar"
        onCancel={() => {
          setVisible(false)
          setDataModal(null)
        }}
        width={1000}
      >
        <Text type="secondary">
          Nota: los iconos en gris pueden significar que no se ha validado la red social.
        </Text>
        <br />
        <Table 
          columns={columnsModal}
          dataSource={dataModal?.usuarios}
          rowKey={'telefono'}
          size="small"
        />

      </Modal>
    )

  };

  useEffect(() => {
    obtenerDatos();
  }, []);

  return (
    <SimpleTableLayout 
      onSearchClicked={onSearch}
      children={
        <>
        <ModalComponent />
        <Table 
          dataSource={ searchInput.length > 1 ? filteredResults : data }
          rowKey={'id'}
          onRow={(record) => ({
            onClick: async () => {
              setVisible(true);
              setDataModal(record);
            }
          })}
          size="small"
          columns={columns}
          pagination={false}
        />
        </>
      }
    />
  )
}

export default Notificaciones