import React, {useState, useEffect} from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { AuthService, VehicleService } from "../../services";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab, Dropdown } from "react-bootstrap";
import { Columns, Download, Filter, PersonSquare, Plus } from "react-bootstrap-icons";
import { ManageTable, Export } from "../../shared/components";
import { FUEL_TYPE, FUEL_TYPE_TEXT, VEHICLE_TITLE, VEHICLE_TITLE_TEXT, SEATING_CAPACITY_OPTIONS, LIFT_EQUIPPED, LIFT_EQUIPPED_TEXT } from "../../shared";

const VehicleList = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [keyword, setKeyword] = useState('');
  const [vehicles, setVehicles] = useState([]);
  const [tag, setTag] = useState('');
  const [sorting, setSorting] = useState({key: '', order: ''});
  const [selectedItems, setSelectedItems] = useState([]);
	const [filteredVehicles, setFilteredVehicles] = useState(vehicles);
  const [showInactive, setShowInactive] = useState(false);
  const [showFilterDropdown, setShowFilterDropdown] = useState(false);
  const [seatingCapacityFilter, setSeatingCapacityFilter] = useState('');
  const [fuelTypeFilter, setFuelTypeFilter] = useState('');
  const [titleFilter, setTitleFilter] = useState('');
  const [liftEquippedFilter, setLiftEquippedFilter] = useState('');
  const [columns, setColumns] = useState([
    {
      key: 'vehicle_number',
      label: 'Vehicle Number',
      show: true
    },
    {
      key: 'tag',
      label: 'License Plate',
      show: true
    },
    {
      key: 'capacity',
      label: 'Seating Capacity',
      show: true
    },
    {
      key: 'responsible_driver',
      label: 'Responsible Driver',
      show: true
    },
    {
      key: 'mileage',
      label: 'Mileage',
      show: true
    },
    {
      key: 'make',
      label: 'Make',
      show: true
    },
    {
      key: 'model',
      label: 'Model',
      show: true
    },
    {
      key: 'year',
      label: 'Year',
      show: true
    },
    {
      key: 'vin',
      label: 'VIN Number',
      show: true
    },
    {
      key: 'gps_tag',
      label: 'GPS ID',
      show: true
    },
    {
      key: 'ezpass',
      label: 'E-ZPass',
      show: true
    },
    {
      key: 'has_lift_equip',
      label: 'Lift Equipped',
      show: true
    },
    {
      key: 'fuel_type',
      label: 'Fuel Type',
      show: true
    },
    {
      key: 'title',
      label: 'Title',
      show: true
    }
  ]);

  useEffect(() => {
    if (!AuthService.canAddOrEditVechiles()) {
      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`);
    }
    VehicleService.getAll().then((data) =>
      setVehicles(data.data)
    );
  }, []);

  useEffect(() => {
    if (showInactive) {
      setFilteredVehicles(vehicles && vehicles.filter(item => 
        (item?.vehicle_number?.toString()?.startsWith(keyword.toLowerCase()) || 
        item?.tag?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.ezpass?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.gps_tag?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.responsible_driver?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.make?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.vehicle_model?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.year?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.vin?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.fuel_type?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.title?.toLowerCase()?.startsWith(keyword.toLowerCase())) &&
        item?.status?.toLowerCase() !== 'active'
      ).filter((item) => {
        if (seatingCapacityFilter && `${item?.capacity || ''}` !== `${seatingCapacityFilter}`) return false;
        if (fuelTypeFilter && `${item?.fuel_type || ''}` !== fuelTypeFilter) return false;
        if (titleFilter && `${item?.title || ''}` !== titleFilter) return false;
        if (liftEquippedFilter && `${item?.has_lift_equip}` !== liftEquippedFilter) return false;
        return true;
      }))
    } else {
      setFilteredVehicles(vehicles && vehicles.filter(item => 
        (item?.vehicle_number?.toString()?.startsWith(keyword.toLowerCase()) || 
        item?.tag?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.ezpass?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.gps_tag?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.responsible_driver?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.make?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.vehicle_model?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.year?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.vin?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.fuel_type?.toLowerCase()?.startsWith(keyword.toLowerCase()) ||
        item?.title?.toLowerCase()?.startsWith(keyword.toLowerCase())) &&
        item?.status?.toLowerCase() === 'active'
      ).filter((item) => {
        if (seatingCapacityFilter && `${item?.capacity || ''}` !== `${seatingCapacityFilter}`) return false;
        if (fuelTypeFilter && `${item?.fuel_type || ''}` !== fuelTypeFilter) return false;
        if (titleFilter && `${item?.title || ''}` !== titleFilter) return false;
        if (liftEquippedFilter && `${item?.has_lift_equip}` !== liftEquippedFilter) return false;
        return true;
      }))
    }
  }, [keyword, vehicles, showInactive, seatingCapacityFilter, fuelTypeFilter, titleFilter, liftEquippedFilter]);

  useEffect(() => {
    const newVehicles = [...vehicles];
    const sortedVehicles = sorting.key === '' ? newVehicles : newVehicles.sort((a, b) => {
      return a[sorting.key]?.localeCompare(b[sorting.key]);
    });
    setVehicles(
      sorting.order === 'asc' ? sortedVehicles : sortedVehicles.reverse()
    )
  }, [sorting]);
  
  const goToEdit = (id) => {
    navigate(`/vehicles/edit/${id}?redirect=list`)
  }


  const goToView = (id) => {
    navigate(`/vehicles/${id}`)
  }

  const goToCreateNew = () => {
    navigate(`/vehicles`)
  }

  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 toggleSelectedAllItems = () => {
    if (selectedItems.length !== filteredVehicles.length || selectedItems.length === 0) {
      const newSelectedItems = [...filteredVehicles].map((vehicle) => vehicle.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 showArchive = (value) => {
		setShowInactive(value === 'archivedVehicles');
		// Recover all filters
		setKeyword('');
    setTag('');
    setSeatingCapacityFilter('');
    setFuelTypeFilter('');
    setTitleFilter('');
    setLiftEquippedFilter('');
		setSorting({key: '', order: ''});
		setSelectedItems([]);
	}

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

  const clearAndCloseFilter = () => {
    setSeatingCapacityFilter('');
    setFuelTypeFilter('');
    setTitleFilter('');
    setLiftEquippedFilter('');
    setShowFilterDropdown(false);
  };

  const applyAndCloseFilter = () => {
    setShowFilterDropdown(false);
  };

  const customFilterMenu = React.forwardRef(
    ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => (
      <div
        ref={ref}
        style={style}
        className={className}
        aria-labelledby={labeledBy}
      >
        <h6>Filter By</h6>
        <div className="app-main-content-fields-section margin-sm dropdown-container">
          <div className="me-4">
            <div className="field-label">Seating Capacity</div>
            <select value={seatingCapacityFilter} onChange={(e) => setSeatingCapacityFilter(e.currentTarget.value)}>
              <option value="">All</option>
              {SEATING_CAPACITY_OPTIONS.map((item) => (
                <option key={item.value} value={item.value}>{item.label}</option>
              ))}
            </select>
          </div>
          <div className="me-4">
            <div className="field-label">Fuel Type</div>
            <select value={fuelTypeFilter} onChange={(e) => setFuelTypeFilter(e.currentTarget.value)}>
              <option value="">All</option>
              {Object.values(FUEL_TYPE).map((value) => (
                <option key={value} value={value}>{FUEL_TYPE_TEXT[value] || value}</option>
              ))}
            </select>
          </div>
        </div>
        <div className="app-main-content-fields-section margin-sm dropdown-container">
          <div className="me-4">
            <div className="field-label">Title</div>
            <select value={titleFilter} onChange={(e) => setTitleFilter(e.currentTarget.value)}>
              <option value="">All</option>
              {Object.values(VEHICLE_TITLE).map((value) => (
                <option key={value} value={value}>{VEHICLE_TITLE_TEXT[value] || value}</option>
              ))}
            </select>
          </div>
          <div className="me-4">
            <div className="field-label">Lift Equipped</div>
            <select value={liftEquippedFilter} onChange={(e) => setLiftEquippedFilter(e.currentTarget.value)}>
              <option value="">All</option>
              {Object.values(LIFT_EQUIPPED).map((value) => (
                <option key={value} value={value}>{LIFT_EQUIPPED_TEXT[value] || value}</option>
              ))}
            </select>
          </div>
        </div>
        <div className="list row">
          <div className="col-md-12">
            <button className="btn btn-default btn-sm float-right" onClick={clearAndCloseFilter}> Cancel </button>
            <button className="btn btn-primary btn-sm float-right" onClick={applyAndCloseFilter}> Filter </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`}></img></span>
							</th>)
						}
					</tr>
					
				</thead>
				<tbody>
					{
						filteredVehicles.map((vehicle, index) => <tr key={vehicle.id}>
							<td className="td-checkbox"><input type="checkbox" checked={selectedItems.includes(vehicle.id)} onClick={()=>toggleItem(vehicle?.id)}/></td>
              <td className="td-index">{index + 1}</td>
              {columns.find(col => col.key === 'vehicle_number')?.show && <td>{AuthService.canViewVechiles() ? <button className="btn btn-link btn-sm" onClick={() => goToView(vehicle?.id)}>{vehicle?.vehicle_number}</button> :  vehicle?.vehicle_number }</td>}
							{columns.find(col => col.key === 'tag')?.show && <td>{vehicle?.tag}</td>}
							{columns.find(col => col.key === 'capacity')?.show && <td>{vehicle?.capacity}</td>}
              {columns.find(col => col.key === 'responsible_driver')?.show && <td>{vehicle?.responsible_driver}</td>}
							{columns.find(col => col.key === 'mileage')?.show && <td>{vehicle?.mileage}</td>}
              {columns.find(col => col.key === 'make')?.show && <td>{vehicle?.make}</td>}
							{columns.find(col => col.key === 'model')?.show && <td>{vehicle?.vehicle_model}</td>}
							{columns.find(col => col.key === 'year')?.show && <td>{vehicle?.year}</td>}
              {columns.find(col => col.key === 'vin')?.show && <td>{vehicle?.vin}</td>}
              {columns.find(col => col.key === 'gps_tag')?.show && <td>{vehicle?.gps_tag}</td>}
              {columns.find(col => col.key === 'ezpass')?.show && <td>{vehicle?.ezpass}</td>}
              {columns.find(col => col.key === 'has_lift_equip')?.show && <td>{vehicle?.has_lift_equip ? 'Yes' : 'No'}</td>}
              {columns.find(col => col.key === 'fuel_type')?.show && <td>{FUEL_TYPE_TEXT[vehicle?.fuel_type] || vehicle?.fuel_type}</td>}
              {columns.find(col => col.key === 'title')?.show && <td>{VEHICLE_TITLE_TEXT[vehicle?.title] || vehicle?.title}</td>}
						</tr>)
					}
				</tbody>
			</table>
		</div>
	</div>;


  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Vehicle Information
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             All Vehicles 
           </h4> 
        </div>
      </div>
      <div className="app-main-content-list-container list-page">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="activeVehicles" id="vehicles-tab" onSelect={(k) => showArchive(k)}>
						<Tab eventKey="activeVehicles" title="Active Vehicles">
							{table}
						</Tab>
						<Tab eventKey="archivedVehicles" title="Archived Vehicles">
							{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)} />
						<ManageTable columns={columns} onColumnsChange={setColumns} />
            <Dropdown
              key={'filter-vehicles'}
              id="filter-vehicles"
              className="me-2"
              show={showFilterDropdown}
              onToggle={(isOpen) => setShowFilterDropdown(isOpen)}
              autoClose={false}
            > 
              <Dropdown.Toggle variant="primary">
                <Filter size={16} className="me-2"></Filter>Filter
              </Dropdown.Toggle>
              <Dropdown.Menu as={customFilterMenu}/> 
            </Dropdown>
						<button className="btn btn-primary me-2" onClick={() => goToCreateNew()}><Plus size={16}></Plus>Add New Vehicle</button>
						<Export 
							columns={columns} 
							data={filteredVehicles} 
							filename="vehicles" 
						/>
					</div>
				</div>
      </div>
      {/* <div className="list row mb-4">
        <div className="col-md-12">
          <div className="mb-4">Filter By Tag: <input type="text" value={tag} onChange={(e) => setTag(e.currentTarget.value)}/></div>
          <table className="personnel-info-table"> 
            <thead>
              <tr>
                <th>Vehicle Number</th>
                <th>Tag Number</th>
                <th>Mileage</th>
                <th>Status</th>
                <th>Seating Capacity</th>
                <th></th>
              </tr>
              
            </thead>
            <tbody>
              {
                vehicles && vehicles.filter((item)=> item?.tag.toLowerCase().includes(tag.toLowerCase()))?.sort((a, b) => parseInt(a.vehicle_number)-parseInt(b.vehicle_number)).map(vehicle => <tr key={vehicle.id}>
                  <td>{vehicle?.vehicle_number}</td>
                  <td>{vehicle?.tag}</td>
                  <td>{vehicle?.mileage}</td>
                  <td>{vehicle?.status}</td>
                  <td>{vehicle?.capacity}</td>
                  <td>
                    {AuthService.canAddOrEditVechiles() && <button className="btn btn-primary btn-sm me-2" onClick={() => goToEdit(vehicle?.id)}>Edit</button> }
                    {AuthService.canViewVechiles() && <button className="btn btn-default btn-sm me-2" onClick={() => goToView(vehicle?.id)}>View</button>}
                  </td>
                </tr>)
              }
            </tbody>
          </table>
           
        </div>
      </div> */}
    </>
  )
};

export default VehicleList;