import React, {useState, useEffect} from "react";
import { useSelector } from "react-redux";
import { useParams, useNavigate } from "react-router-dom";
import { DailyRoutesTemplateService } from "../../services";
import { selectAllActiveDrivers, selectAllActiveVehicles } from "./../../store";
import { Breadcrumb, Spinner, Modal, Button } from "react-bootstrap";
import { Pencil, Trash } from "react-bootstrap-icons";
import RouteCustomerEditor from "./RouteCustomerEditor";

const ViewDailyTemplateRoute = () => {
  const params = useParams();
  const navigate = useNavigate();
  const drivers = useSelector(selectAllActiveDrivers);
  const vehicles = useSelector(selectAllActiveVehicles);
  const [template, setTemplate] = useState(null);
  const [currentRoute, setCurrentRoute] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleting, setDeleting] = useState(false);
  
  const currentVehicle = vehicles.find(item => item.id === currentRoute?.vehicle);
  const currentDriver = drivers.find(item => item.id === currentRoute?.driver);

  useEffect(() => {
    fetchTemplateAndRoute();
  }, [params.id, params.routeId]);

  const fetchTemplateAndRoute = () => {
    DailyRoutesTemplateService.getDailyRoutesTemplate(params.id).then(data => {
      setTemplate(data.data);
      const route = data.data.routes?.find(r => r._id === params.routeId);
      setCurrentRoute(route);
    });
  };

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

  const goToEdit = () => {
    navigate(`/trans-routes/daily-templates/${params.id}/update-route/${params.routeId}`);
  };

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

  const deleteRoute = () => {
    setDeleting(true);
    const updatedRoutes = template.routes.filter(r => r._id !== params.routeId);
    
    DailyRoutesTemplateService.updateDailyRoutesTemplate(params.id, {
      ...template,
      routes: updatedRoutes
    }).then(() => {
      setDeleting(false);
      setShowDeleteModal(false);
      navigate(`/trans-routes/daily-templates/view/${params.id}`);
    }).catch(err => {
      setDeleting(false);
      alert('Failed to delete route');
    });
  };

  if (!template || !currentRoute) {
    return (
      <div className="list row mb-4">
        <Spinner animation="border" role="status">
          <span className="visually-hidden">Loading...</span>
        </Spinner>
      </div>
    );
  }

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item href="/trans-routes/daily-templates/list">
            Daily Route Templates
          </Breadcrumb.Item>
          <Breadcrumb.Item href={`/trans-routes/daily-templates/view/${params.id}`}>
            {template.name}
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            {currentRoute.name}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>
            View Route in Template: {currentRoute.name}
            <button className="btn btn-link btn-sm" onClick={goBack}>Back</button>
          </h4>
        </div>
      </div>

      <div className="app-main-content-list-container">
        <div className="app-main-content-fields-section">
          <div className="row">
            <div className="col-md-6">
              <div className="mb-3">
                <strong>Route Name:</strong> {currentRoute.name}
              </div>
              <div className="mb-3">
                <strong>Type:</strong> {currentRoute.type}
              </div>
              <div className="mb-3">
                <strong>Vehicle:</strong> {currentVehicle?.vehicle_number || 'Not assigned'}
              </div>
              <div className="mb-3">
                <strong>Driver:</strong> {currentDriver?.name || 'Not assigned'}
              </div>
            </div>
            <div className="col-md-6">
              <div className="mb-3">
                <strong>Start Mileage:</strong> {currentRoute.start_mileage || 'N/A'}
              </div>
              <div className="mb-3">
                <strong>End Mileage:</strong> {currentRoute.end_mileage || 'N/A'}
              </div>
              <div className="mb-3">
                <strong>Customers:</strong> {currentRoute.route_customer_list?.length || 0}
              </div>
            </div>
          </div>

          <div className="mt-4">
            <button className="btn btn-primary me-2" onClick={goToEdit}>
              <Pencil size={16} className="me-2" />
              Update Route
            </button>
            <button className="btn btn-danger" onClick={confirmDelete}>
              <Trash size={16} className="me-2" />
              Delete Route
            </button>
          </div>
        </div>

        <RouteCustomerEditor 
          currentRoute={currentRoute} 
          viewMode={true} 
          editFun={() => goToEdit()}
        />
      </div>

      <Modal show={showDeleteModal} onHide={() => setShowDeleteModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Delete Route</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Are you sure you want to delete the route "{currentRoute.name}" from this template?
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowDeleteModal(false)} disabled={deleting}>
            Cancel
          </Button>
          <Button variant="danger" onClick={deleteRoute} disabled={deleting}>
            {deleting ? <><Spinner size="sm" className="me-2" />Deleting...</> : 'Delete'}
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};

export default ViewDailyTemplateRoute;

