import React, {useEffect, useRef, useState} from "react";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { transRoutesSlice ,selectHistoryInboundRoutes, selectHistoryOutboundRoutes, selectHistoryRoutes, selectAllActiveDrivers, selectAllActiveVehicles } from "./../../store";
import RoutesSection from "./RoutesSection";
import PersonnelSection from "./PersonnelSection";
import DatePicker from "react-datepicker";
import { Modal, ProgressBar } from "react-bootstrap";
import { AuthService, ReportService } from "../../services";

const RoutesHistory = () => {
  const getErrorMessageFromBlob = async (blobData, fallback = 'Failed to export route report.') => {
    try {
      if (!blobData) return fallback;
      const text = await blobData.text();
      if (!text) return fallback;
      const parsed = JSON.parse(text);
      return parsed?.message || fallback;
    } catch (_err) {
      return fallback;
    }
  };
  const getZipFilenameFromHeaders = (headers, fallback = `route_report_${Date.now()}.zip`) => {
    const rawHeader = headers?.['content-disposition'] || headers?.['Content-Disposition'] || '';
    const match = rawHeader.match(/filename\*?=(?:UTF-8'')?\"?([^\";]+)\"?/i);
    if (match?.[1]) {
      try {
        return decodeURIComponent(match[1]);
      } catch (_err) {
        return match[1];
      }
    }
    return fallback;
  };
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const inboundRoutes = useSelector(selectHistoryInboundRoutes);
  const outboundRoutes = useSelector(selectHistoryOutboundRoutes);
  const allRoutes = useSelector(selectHistoryRoutes);
  const [selectedDate, setSelectedDate] = useState(undefined);
  const [isExportingRouteReport, setIsExportingRouteReport] = useState(false);
  const [exportRouteReportProgress, setExportRouteReportProgress] = useState(0);
  const exportProgressTimerRef = useRef(null);
  const drivers = useSelector(selectAllActiveDrivers);
  const vehicles = useSelector(selectAllActiveVehicles);

  const stopExportProgressTimer = () => {
    if (exportProgressTimerRef.current) {
      clearInterval(exportProgressTimerRef.current);
      exportProgressTimerRef.current = null;
    }
  };

  const startExportRouteReportProgress = () => {
    stopExportProgressTimer();
    setIsExportingRouteReport(true);
    setExportRouteReportProgress(12);
    exportProgressTimerRef.current = setInterval(() => {
      setExportRouteReportProgress((prev) => (prev >= 90 ? 90 : prev + 5));
    }, 250);
  };

  const finishExportRouteReportProgress = () => {
    stopExportProgressTimer();
    setExportRouteReportProgress(100);
    setTimeout(() => {
      setIsExportingRouteReport(false);
      setExportRouteReportProgress(0);
    }, 250);
  };

  useEffect(() => {
    return () => {
      stopExportProgressTimer();
    };
  }, []);
  const backToDashboard = () => {
    navigate('/trans-routes/dashboard');
  }
  const { fetchAllHistoryRoutes } = transRoutesSlice.actions;
  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 searchForHistory = () => {
    if (selectedDate) {
      dispatch(fetchAllHistoryRoutes({dateText: getDateString(selectedDate)}));
    }
  };
  const generateRouteReport = async () => {
    if (!selectedDate) {
      window.alert('Please select a date first.');
      return;
    }
    if (isExportingRouteReport) return;
    startExportRouteReportProgress();
    try {
      const selectedDateText = getDateString(selectedDate);
      const response = await ReportService.exportRouteReportZip(selectedDateText);
      const blob = new Blob([response.data], { type: 'application/zip' });
      const downloadName = getZipFilenameFromHeaders(response?.headers);
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', downloadName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(downloadUrl);
    } catch (error) {
      console.error('Failed to export route report:', error);
      const message = await getErrorMessageFromBlob(error?.response?.data);
      window.alert(message);
    } finally {
      finishExportRouteReportProgress();
    }
  }

  return (
    <>
      <div className="list row">
        <div className="col-md-4 text-primary mb-2">
          <h5>Route History <button className="btn btn-link btn-sm ms-2 me-2" onClick={() => backToDashboard()} disabled={isExportingRouteReport}>Back To Dashboard</button> <button type="button" className="btn btn-primary btn-sm me-2" onClick={()=> generateRouteReport()} disabled={isExportingRouteReport}>Generate Route Report</button></h5>
        </div>
      </div>
      <div className="list row mb-4">
        <div className="mb-2 ms-2">
          <span>Select A Date: </span>
        </div>
        <div className="col-md-4 mb-2">
          <DatePicker selected={selectedDate} onChange={(v) => setSelectedDate(v)} />
        </div>
        <div className="col-md-4 text-primary mb-2">
          <button className="btn btn-primary btn-sm" onClick={() => searchForHistory()}>Search</button>
        </div>
        {selectedDate && <div className="col-md-4 text-primary mb-2">
          Selected Date: {getDateString(new Date(selectedDate))}
        </div>}
      </div>
      <div className="list row">
        <div className="col-md-12 mb-4">
          <RoutesSection transRoutes={inboundRoutes} drivers={drivers} vehicles={vehicles} sectionName="Inbound Routes"/>
        </div>
        <hr />
        <div className="col-md-12 mb-4">
          <RoutesSection transRoutes={outboundRoutes} drivers={drivers} vehicles={vehicles} sectionName="Outbound Routes"/>
        </div>
        <hr />
      </div>
      <div className="list row">
        <div className="col-md-12 mb-4">
          <PersonnelSection transRoutes={allRoutes} showCompletedInfo={false} showGroupInfo={false} allowForceEdit={AuthService.canAddOrEditRoutes()} showFilter={true} sectionName="Personnel Status (click on each user to edit)"/>
        </div>
      </div>

      <Modal show={isExportingRouteReport} backdrop="static" keyboard={false} centered>
        <Modal.Header>
          <Modal.Title>Generating Route Report</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="mb-2">Please wait. User interactions are temporarily disabled.</div>
          <ProgressBar now={exportRouteReportProgress} animated label={`${Math.round(exportRouteReportProgress)}%`} />
        </Modal.Body>
      </Modal>
    </>
    
  );
};

export default RoutesHistory;