import React, {useEffect, useState} 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, Tabs, Tab, Spinner, Button } from "react-bootstrap";
import RouteCustomerEditor from "./RouteCustomerEditor";
import { Trash } from "react-bootstrap-icons";

const UpdateDailyTemplateRoute = () => {
  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 [routeName, setRouteName] = useState('');
  const [newDriver, setNewDriver] = useState('');
  const [newVehicle, setNewVehicle] = useState('');
  const [newRouteType, setNewRouteType] = useState('');
  const [newCustomerList, setNewCustomerList] = useState([]);
  const [errorMessage, setErrorMessage] = useState(undefined);
  const [successMessage, setSuccessMessage] = useState(undefined);
  const [saving, setSaving] = useState(false);

  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);
      setRouteName(route.name);
      setNewDriver(route.driver);
      setNewVehicle(route.vehicle);
      setNewRouteType(route.type);
      setNewCustomerList(route.route_customer_list || []);
    });
  };

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

  const updateCurrentRoute = () => {
    try {
      if (!routeName || routeName === '') { 
        setErrorMessage('Route Name is Required'); 
        setTimeout(() => setErrorMessage(undefined), 5000);
        return;
      }
      if (!newRouteType || newRouteType === '') {
        setErrorMessage('Route Type is Required'); 
        setTimeout(() => setErrorMessage(undefined), 5000);
        return;
      }

      setSaving(true);
      
      // Update the route in the template
      const updatedRoutes = template.routes.map(route => {
        if (route._id === params.routeId) {
          return {
            ...route,
            name: routeName,
            driver: newDriver,
            vehicle: newVehicle,
            type: newRouteType,
            route_customer_list: newCustomerList
          };
        }
        return route;
      });

      DailyRoutesTemplateService.updateDailyRoutesTemplate(params.id, {
        ...template,
        routes: updatedRoutes
      }).then(() => {
        setSaving(false);
        setSuccessMessage('Route updated successfully!');
        setTimeout(() => {
          goBack();
        }, 1500);
      }).catch(err => {
        setSaving(false);
        setErrorMessage('Failed to update route');
        setTimeout(() => setErrorMessage(undefined), 5000);
      });
    } catch(ex) {
      setSaving(false);
      setErrorMessage('An error occurred');
      setTimeout(() => setErrorMessage(undefined), 5000);
    }
  };

  const deleteRoute = () => {
    if (window.confirm(`Are you sure you want to delete the route "${currentRoute.name}" from this template?`)) {
      const updatedRoutes = template.routes.filter(r => r._id !== params.routeId);
      
      DailyRoutesTemplateService.updateDailyRoutesTemplate(params.id, {
        ...template,
        routes: updatedRoutes
      }).then(() => {
        navigate(`/trans-routes/daily-templates/view/${params.id}`);
      }).catch(err => {
        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>
            Update Route: {currentRoute.name}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>
            Update Route in Template
            <button className="btn btn-link btn-sm" onClick={goBack}>Cancel</button>
          </h4>
        </div>
      </div>

      {errorMessage && (
        <div className="alert alert-danger alert-dismissible fade show" role="alert">
          {errorMessage}
          <button onClick={() => setErrorMessage(undefined)} type="button" className="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      )}

      {successMessage && (
        <div className="alert alert-success alert-dismissible fade show" role="alert">
          {successMessage}
          <button onClick={() => setSuccessMessage(undefined)} type="button" className="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
      )}

      <div className="app-main-content-list-container">
        <Tabs defaultActiveKey="basicInfo" id="route-edit-tab">
          <Tab eventKey="basicInfo" title="Basic Information">
            <div className="app-main-content-fields-section">
              <div className="mb-3 me-2">
                <label className="form-label">Route Name *</label>
                <input 
                  type="text" 
                  className="form-control" 
                  value={routeName}
                  onChange={(e) => setRouteName(e.target.value)}
                  disabled={saving}
                />
              </div>

              <div className="mb-3">
                <label className="form-label">Route Type *</label>
                <select 
                  className="form-select" 
                  value={newRouteType}
                  onChange={(e) => setNewRouteType(e.target.value)}
                  disabled={saving}
                >
                  <option value="">Select Type</option>
                  <option value="inbound">Inbound</option>
                  <option value="outbound">Outbound</option>
                </select>
              </div>
              </div>
            <div className="app-main-content-fields-section">
              <div className="mb-3 me-2">
                <label className="form-label">Driver</label>
                <select 
                  className="form-select" 
                  value={newDriver}
                  onChange={(e) => setNewDriver(e.target.value)}
                  disabled={saving}
                >
                  <option value="">Select Driver</option>
                  {drivers.map((driver) => (
                    <option key={driver.id} value={driver.id}>{driver.name}</option>
                  ))}
                </select>
              </div>

              <div className="mb-3">
                <label className="form-label">Vehicle</label>
                <select 
                  className="form-select" 
                  value={newVehicle}
                  onChange={(e) => setNewVehicle(e.target.value)}
                  disabled={saving}
                >
                  <option value="">Select Vehicle</option>
                  {vehicles.map((vehicle) => (
                    <option key={vehicle.id} value={vehicle.id}>{vehicle.vehicle_number}</option>
                  ))}
                </select>
              </div>
            </div>
            <div className="app-main-content-fields-section">
              <div className="mt-4">
                <button 
                  className="btn btn-primary me-2" 
                  onClick={updateCurrentRoute}
                  disabled={saving}
                >
                  {saving ? <><Spinner size="sm" className="me-2" />Saving...</> : 'Save Changes'}
                </button>
                <button 
                  className="btn btn-secondary me-2" 
                  onClick={goBack}
                  disabled={saving}
                >
                  Cancel
                </button>
                <button 
                  className="btn btn-danger" 
                  onClick={deleteRoute}
                  disabled={saving}
                >
                  <Trash size={16} className="me-2" />
                  Delete Route
                </button>
              </div>
            </div>
          </Tab>

          <Tab eventKey="customers" title="Customers">
            <div className="app-main-content-fields-section">
              <RouteCustomerEditor 
                currentRoute={currentRoute}
                setNewCustomerList={setNewCustomerList}
              />
            </div>
            <div className="app-main-content-fields-section">
              <div className="mt-4">
                <button 
                  className="btn btn-primary me-2" 
                  onClick={updateCurrentRoute}
                  disabled={saving}
                >
                  {saving ? <><Spinner size="sm" className="me-2" />Saving...</> : 'Save Changes'}
                </button>
                <button 
                  className="btn btn-secondary me-2" 
                  onClick={goBack}
                  disabled={saving}
                >
                  Cancel
                </button>
              </div>
            </div>
          </Tab>
        </Tabs>
      </div>
    </>
  );
};

export default UpdateDailyTemplateRoute;

