import React, {useState, useEffect, useRef} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, DailyRoutesTemplateService, TransRoutesService } from "../../services";
import { Breadcrumb, Modal, Button, Tabs, Tab, Dropdown, ProgressBar } from "react-bootstrap";
import { PencilSquare } from "react-bootstrap-icons";
import ReactPaginate from 'react-paginate';
import DatePicker from "react-datepicker";
import moment from "moment";

const DailyTemplatesList = () => {
  const navigate = useNavigate();
  const [templates, setTemplates] = useState([]);
  const [keyword, setKeyword] = useState('');
  const [currentItems, setCurrentItems] = useState(null);
  const [sorting, setSorting] = useState({key: '', order: ''});
  const [selectedItems, setSelectedItems] = useState([]);
  const [itemOffset, setItemOffset] = useState(0);
  const [pageCount, setPageCount] = useState(0);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [templateToDelete, setTemplateToDelete] = useState(null);
  const [showCreateFromDateDropdown, setShowCreateFromDateDropdown] = useState(false);
  const [createFromDate, setCreateFromDate] = useState(new Date());
  const [isCreatingTemplate, setIsCreatingTemplate] = useState(false);
  const [createTemplateProgress, setCreateTemplateProgress] = useState(0);
  const createTemplateProgressTimerRef = useRef(null);

  const columns = [
    {
      key: 'name',
      label: 'Template Name',
      show: true
    },
    {
      key: 'template_date',
      label: 'Template Date',
      show: true
    },
    {
      key: 'routes_count',
      label: 'Routes Count',
      show: true
    },
    {
      key: 'create_by',
      label: 'Created By',
      show: true
    },
    {
      key: 'create_date',
      label: 'Created Date',
      show: true
    }
  ];

  useEffect(() => {
    if (!AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    fetchTemplates();
  }, []);

  const fetchTemplates = () => {
    DailyRoutesTemplateService.getAll().then(data => {
      setTemplates(data.data);
    });
  };

  useEffect(() => {
    const endOffset = itemOffset + parseInt(itemsPerPage);
    const newTemplates = templates?.filter(template => 
      template?.name?.toLowerCase().includes(keyword.toLowerCase()) || 
      template?.template_date?.toLowerCase().includes(keyword.toLowerCase())
    );
    
    const sortedTemplates = sorting.key === '' ? newTemplates : newTemplates.sort((a, b) => {
      if (sorting.key === 'routes_count') {
        return (a.routes?.length || 0) - (b.routes?.length || 0);
      }
      return a[sorting.key]?.toString().localeCompare(b[sorting.key]?.toString());
    });
    
    const results = sorting.order === 'asc' ? sortedTemplates : sortedTemplates.reverse();
    setCurrentItems(results.slice(itemOffset, endOffset)?.map(item => ({
      ...item,
      routes_count: item.routes?.length || 0,
      create_date: item.create_date ? new Date(item.create_date).toLocaleDateString() : ''
    })));
    setPageCount(Math.ceil(newTemplates.length / itemsPerPage));
  }, [templates, itemOffset, keyword, itemsPerPage, sorting]);

  const handlePageClick = (event) => {
    const newOffset = (event.selected * itemsPerPage) % templates?.filter(template => 
      template?.name?.toLowerCase().includes(keyword.toLowerCase()) || 
      template?.template_date?.toLowerCase().includes(keyword.toLowerCase())
    ).length;
    setItemOffset(newOffset);
    setCurrentPage(event.selected + 1);
  };

  const handlePageSelect = (pageNo) => {
    const newOffset = ((pageNo-1) * itemsPerPage) % templates?.filter(template => 
      template?.name?.toLowerCase().includes(keyword.toLowerCase()) || 
      template?.template_date?.toLowerCase().includes(keyword.toLowerCase())
    ).length;
    setItemOffset(newOffset);
  };

  const getSortingImg = (key) => {
    return sorting.key === key ? (sorting.order === 'asc' ? 'up_arrow' : 'down_arrow') : 'default';
  }

  const sortTableWithField = (key) => {
    let newSorting = {
      key,
      order: 'asc',
    }
    
    if (sorting.key === key && sorting.order === 'asc') {
      newSorting = {...newSorting, order: 'desc'};
    }
    setSorting(newSorting);
  }

  const goToView = (id) => {
    navigate(`/trans-routes/daily-templates/view/${id}`);
  }

  const confirmDelete = (template) => {
    setTemplateToDelete(template);
    setShowDeleteModal(true);
  }

  const deleteTemplate = () => {
    if (templateToDelete) {
      DailyRoutesTemplateService.deleteDailyRoutesTemplate(templateToDelete.id).then(() => {
        fetchTemplates();
        setShowDeleteModal(false);
        setTemplateToDelete(null);
      });
    }
  }

  const toggleSelectedAllItems = () => {
    if (selectedItems.length !== currentItems?.length || selectedItems?.length === 0) {
      const newSelectedItems = [...currentItems].map((template) => template.id);
      setSelectedItems(newSelectedItems);
    } else {
      setSelectedItems([]);
    }
  }

  const toggleItem  = (id) => {
    if (selectedItems.includes(id)) {
      const newSelectedItems = [...selectedItems].filter((item) => item !== id);
      setSelectedItems(newSelectedItems);
    } else {
      const newSelectedItems = [...selectedItems, id];
      setSelectedItems(newSelectedItems);
    }
  }

  const checkSelectAll = () => {
    return selectedItems?.length === currentItems?.length && selectedItems?.length > 0;
  }

  const getDateString = (date) => {
    return ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear()
  }

  const startCreateTemplateProgress = () => {
    if (createTemplateProgressTimerRef.current) {
      clearInterval(createTemplateProgressTimerRef.current);
    }
    setCreateTemplateProgress(10);
    setIsCreatingTemplate(true);
    createTemplateProgressTimerRef.current = setInterval(() => {
      setCreateTemplateProgress((prev) => (prev >= 90 ? 90 : prev + 5));
    }, 250);
  };

  const finishCreateTemplateProgress = () => {
    if (createTemplateProgressTimerRef.current) {
      clearInterval(createTemplateProgressTimerRef.current);
      createTemplateProgressTimerRef.current = null;
    }
    setCreateTemplateProgress(100);
    setTimeout(() => {
      setIsCreatingTemplate(false);
      setCreateTemplateProgress(0);
    }, 350);
  };

  const createTemplateFromSelectedDate = async () => {
    if (!createFromDate) {
      window.alert('Please select a date.');
      return;
    }

    startCreateTemplateProgress();
    try {
      const targetDate = getDateString(createFromDate);
      const { data: routes } = await TransRoutesService.getAll(targetDate);
      if (!routes || routes.length === 0) {
        window.alert(`No schedule routes found on ${targetDate}.`);
        finishCreateTemplateProgress();
        return;
      }

      const cleanedRoutes = routes.map(route => {
        const cleanedCustomerList = route.route_customer_list?.map(customer => ({
          ...customer,
          customer_enter_center_time: null,
          customer_leave_center_time: null,
          customer_pickup_time: null,
          customer_dropoff_time: null,
          customer_route_status: null,
        })) || [];

        return {
          name: route.name,
          schedule_date: route.schedule_date,
          vehicle: route.vehicle,
          status: [],
          driver: route.driver,
          type: route.type,
          start_mileage: route.start_mileage,
          end_mileage: route.end_mileage,
          start_time: null,
          end_time: null,
          estimated_start_time: null,
          route_customer_list: cleanedCustomerList,
          checklist_result: route.checklist_result || []
        };
      });

      const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user'))?.name : '';
      const payload = {
        name: `Template ${moment(createFromDate).format('MM/DD/YYYY')}`,
        template_date: targetDate,
        routes: cleanedRoutes,
        create_by: currentUser
      };

      await DailyRoutesTemplateService.createNewDailyRoutesTemplate(payload);
      await fetchTemplates();
      setShowCreateFromDateDropdown(false);
      window.alert(`Template created from ${targetDate}.`);
    } catch (error) {
      console.error('Failed to create template from date:', error);
      window.alert(error?.message || 'Failed to create template from selected date.');
    } finally {
      finishCreateTemplateProgress();
    }
  };

  useEffect(() => {
    return () => {
      if (createTemplateProgressTimerRef.current) {
        clearInterval(createTemplateProgressTimerRef.current);
      }
    };
  }, []);

  const customMenuCreateFromDate = 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</div>
              <DatePicker selected={createFromDate} onChange={(v) => setCreateFromDate(v)} />
            </div>
          </div>
          <div className="list row">
            <div className="col-md-12">
              <button className="btn btn-default btn-sm float-right" onClick={() => setShowCreateFromDateDropdown(false)}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={createTemplateFromSelectedDate}> Create </button>
            </div>
          </div>
        </div>
      );
    },
  );

  const table = (
    <div className="list row mb-4">
      <div className="col-md-12">
        <table className="personnel-info-table"> 
                <thead>
                  <tr>
                    <th className="th-checkbox"><input type="checkbox" checked={checkSelectAll()} onClick={() => toggleSelectedAllItems()}></input></th>
                    <th className="th-index">No.</th>
                    {
                      columns.filter(col => col.show).map((column, index) => <th className="sortable-header" key={index}>
                        {column.label}  <span className="float-right" onClick={() => sortTableWithField(column.key)}><img src={`/images/${getSortingImg(column.key)}.png`} alt="sort"></img></span>
                      </th>)
                    }
                  </tr>
                </thead>
                <tbody>
                  {
                    currentItems?.map((template, index) => <tr key={template?.id}>
                      <td className="td-checkbox"><input type="checkbox" checked={selectedItems.includes(template.id)} onClick={()=>toggleItem(template?.id)}/></td>
                      <td className="td-index">{index + 1 + itemOffset}</td>
                      {columns.find(col => col.key === 'name')?.show && <td>
                        <button className="btn btn-link btn-sm" onClick={() => goToView(template?.id)}>{template?.name}</button>
                      </td>}
                      {columns.find(col => col.key === 'template_date')?.show && <td>{template?.template_date}</td>}
                      {columns.find(col => col.key === 'routes_count')?.show && <td>{template?.routes_count}</td>}
                      {columns.find(col => col.key === 'create_by')?.show && <td>{template?.create_by}</td>}
                      {columns.find(col => col.key === 'create_date')?.show && <td>{template?.create_date}</td>}
                    </tr>)
                  }
                </tbody>
              </table>
              <div className="pagination-container">
                <ReactPaginate
                  key={itemsPerPage}
                  className="customers-pagination"
                  breakLabel="..."
                  nextLabel="Next"
                  onPageChange={handlePageClick}
                  pageRangeDisplayed={5}
                  pageCount={pageCount}
                  previousLabel="Prev"
                  renderOnZeroPageCount={null}
                  containerClassName="pagination justify-content-center"
                  pageClassName="page-item"
                  pageLinkClassName="page-link"
                  previousClassName="page-prev-item"
                  previousLinkClassName="page-link"
                  nextClassName="page-next-item"
                  nextLinkClassName="page-link"
                  activeClassName="active"
                  breakClassName="page-item"
                  breakLinkClassName="page-link"
                />
                <div className="select-page-container">
                  <input type="number" className="page-picker" max={pageCount} min={1} value={currentPage} onChange={(e) => {handlePageSelect(e.target.value); setCurrentPage(e.target.value)}}/>
                  <div className="per-page-label"> {` of ${pageCount}`}</div>
                </div>

                <div className="select-page-container">
                  <select className="per-page" value={itemsPerPage} onChange={e => setItemsPerPage(e.target.value)}>
                    <option value="10">10</option>
                    <option value="25">25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                  </select> <span className="per-page-label"> /page</span>
                </div>
              </div>
            </div>
    </div>
  );

  return (
    <>
      {isCreatingTemplate && <div className="spinner-overlay" style={{ flexDirection: 'column', gap: '12px', zIndex: 1060 }}>
        <div style={{ width: '360px', maxWidth: '80vw', textAlign: 'center' }}>
          <div style={{ marginBottom: '8px', color: '#333' }}>Creating template from date...</div>
          <ProgressBar now={createTemplateProgress} animated label={`${Math.round(createTemplateProgress)}%`} />
        </div>
      </div>}
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Daily Route Templates
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>
            All Daily Route Templates
          </h4> 
        </div>
      </div>
      <div className="app-main-content-list-container">
        <div className="app-main-content-list-func-container">
          <Tabs defaultActiveKey="dailyTemplates" id="daily-templates-tab">
            <Tab eventKey="dailyTemplates" title="Daily Route Templates">
              {table}
            </Tab>
          </Tabs>
          <div className="list-func-panel">
            <input className="me-2 with-search-icon" type="text" placeholder="Search" value={keyword}  onChange={(e) => setKeyword(e.currentTarget.value)} />
            <Dropdown
              key={'create-template-from-date'}
              id="create-template-from-date"
              className="me-2"
              show={showCreateFromDateDropdown}
              onToggle={() => setShowCreateFromDateDropdown(!showCreateFromDateDropdown)}
              autoClose={false}
            >
              <Dropdown.Toggle variant="outline-secondary" disabled={isCreatingTemplate}>
                Create template from date
              </Dropdown.Toggle>
              <Dropdown.Menu as={customMenuCreateFromDate}/>
            </Dropdown>
          </div>
        </div>
      </div>

      <Modal show={showDeleteModal} onHide={() => setShowDeleteModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Delete Template</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Are you sure you want to delete the template "{templateToDelete?.name}"?
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowDeleteModal(false)}>
            Cancel
          </Button>
          <Button variant="danger" onClick={deleteTemplate}>
            Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  )
};

export default DailyTemplatesList;

