import React, {useState, useEffect} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, MessageService } from "../../services";
import DatePicker from "react-datepicker";
import { CalendarWeek, ClockHistory, Copy, Download, Eraser, Plus, Clock, Send, Filter, CalendarCheck, Check } from "react-bootstrap-icons";
import { Breadcrumb, Tabs, Tab, Dropdown, Spinner, Modal, Button } from "react-bootstrap";

const SentMessageList = () => {
  const navigate = useNavigate();
  const [messages, setMessages] = useState([]);
  const [datePicked, setDatePicked] = useState(new Date());
  const [showDateDropdown, setShowDateDropdown] = useState(false);
  const params = new URLSearchParams(window.location.search);
  useEffect(() => {
    if (!AuthService.canAddOrEditRoutes() && !AuthService.canViewRoutes()&&!AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change a dispatcher or admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    MessageService.getSentMessages().then(data => {
      console.log(data);
      setMessages(data.data);
    })
  }, []);

  const cleanDate = () => {
    setDatePicked(new Date());
    setShowDateDropdown(false);
  }

  const FilterAndClose = () => {
    setShowDateDropdown(false);
  }
  

  const redirectToAdmin = () => {
    if (params.get('from') === 'medical') {
      navigate(`/medical/`)
    } else {
      navigate(`/admin/customer-report`)
    }
    
  }

  const redirectToSend = () => {
    navigate(`/messages/send-message`);
  }

  const customMenuDate = React.forwardRef(
    ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => {
      return (
        <div
          ref={ref}
          style={style}
          className={className}
          aria-labelledby={labeledBy}
        >
          <div className="app-main-content-fields-section margin-sm dropdown-container">
            <div className="me-4">
              <div className="field-label">Select Date to Filter</div>
              <DatePicker selected={datePicked} onChange={(v) => setDatePicked(v)} />
            </div>
          </div>
          <div className="list row">
            <div className="col-md-12">
              <button className="btn btn-default btn-sm float-right" onClick={() => cleanDate()}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={() => FilterAndClose()}>Filter</button>
            </div>
          </div>
        </div>
      );
    },
  );

  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">General</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Messaging
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>All Sent Messages <button className="btn btn-link btn-sm" onClick={() => {redirectToSend()}}>Back</button>
           </h4> 
        </div>
      </div>
      <div className="app-main-content-list-container">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="allSentMessages" id="sent-messages-tab">
						<Tab eventKey="allSentMessages" title="All Sent Messages">
              <table className="personnel-info-table"> 
                <thead>
                  <tr>
                    <th className="th-index">No.</th>
                    <th>From</th>
                    <th>To</th>
                    <th>Message</th>
                    <th>Sent Time</th>
                  </tr>
                  
                </thead>
                <tbody>
                  {
                    messages && messages.filter((message) => (new Date(message?.create_date))?.toLocaleDateString() === (new Date(datePicked)).toLocaleDateString()).map((message, index) => <tr key={message.id}>
                      <td className="td-index">{index + 1}</td>
                      <td>{message?.from}</td>
                      <td>{message?.to}</td>
                      <td>{message?.content}</td>
                      <td>{`${new Date(message?.create_date)?.toLocaleDateString()} ${new Date(message?.create_date)?.toLocaleTimeString()}`}</td>
                    </tr>)
                  }
                </tbody>
              </table>
            </Tab>
          </Tabs>
          <div className="list-func-panel">
            <Dropdown
              key={'sent-date'}
              id="sent-date"
              className="me-2"
              show={showDateDropdown}
              onToggle={() => setShowDateDropdown(!showDateDropdown)}
              autoClose={false}
            > 
              <Dropdown.Toggle variant="primary">
                <CalendarWeek size={16} className="me-2"></CalendarWeek>Select Date to Filter
              </Dropdown.Toggle>
              <Dropdown.Menu as={customMenuDate}/> 
            </Dropdown>
          </div>
        </div>
      </div>
    </>
  )
};

export default SentMessageList;