import React, { useEffect, useState } from 'react';
import { Table, Modal} 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";

const Timeline = () => {

  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: "Evento",
      dataIndex: "evento",
      key: "evento",
      render: (_, item) => item?.evento.nombre,
    },
    {
      title: "Red social",
      dataIndex: "redSocial",
      key: "redSocial",
      render: (_, item) => item?.evento.redSocial,
    },
    {
      title: "Fecha",
      dataIndex: "fecha",
      key: "fecha",
      render: (_, item) => moment(item?.evento?.timestamp?.toDate()).format('DD-MM-YYYY hh:mm A'),
    },
  ];

  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 ModalComponent = () => {

    if( !dataModal ) return <></>;

    return (
      <Modal
        title="Información"
        centered
        open={visible}
        okText="ok"
        okButtonProps={{ style: { display: 'none' } }}
        cancelText="Cerrar"
        onCancel={() => {
          setVisible(false)
          setDataModal(null)
        }}
        width={1000}
      >

      </Modal>
    )
  };

  const obtenerDatos = async () => {
    try {
      const ref = collection(firestore, "procesos");
      const q = query(ref, orderBy("timestamp", "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);
    }
  }

  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)
            }
          })}
          columns={columns}
          size="small"
          pagination={false}
        />
        </>
      }
    />
  )
}

export default Timeline