import React, {useEffect, useState} from "react";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { vehicleSlice, selectVehicleError } from "./../../store";
import { AuthService, VehicleService, DriverService } from "../../services";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";
import { Upload } from "react-bootstrap-icons";
import DatePicker from "react-datepicker";
import Select from 'react-select';
import moment from 'moment';
import {
  SEATING_CAPACITY_OPTIONS,
  FUEL_TYPE, FUEL_TYPE_TEXT,
  VEHICLE_TITLE, VEHICLE_TITLE_TEXT,
  LIFT_EQUIPPED, LIFT_EQUIPPED_TEXT,
  REPAIR_PART_NAME, REPAIR_PART_NAME_TEXT,
  QUANTITY_OPTIONS
} from "../../shared";

const CreateVehicle = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { createVehicle } = vehicleSlice.actions;
  const error = useSelector(selectVehicleError);

  // Basic Information
  const [vehicleNumber, setVehicleNumber] = useState('');
  const [responsibleDriver, setResponsibleDriver] = useState(null);
  const [capacity, setCapacity] = useState('');
  const [mileage, setMileage] = useState('');
  const [make, setMake] = useState('');
  const [vehicleModel, setVehicleModel] = useState('');
  const [year, setYear] = useState('');
  const [vin, setVin] = useState('');
  const [tag, setTag] = useState('');
  const [gps, setGps] = useState('');
  const [ezpass, setEzpass] = useState('');
  const [hasLiftEquip, setHasLiftEquip] = useState('');
  const [fuelType, setFuelType] = useState('');
  const [title, setTitle] = useState('');
  const [titleOther, setTitleOther] = useState('');

  // Compliance & Deadlines
  const [insuranceStartDate, setInsuranceStartDate] = useState(null);
  const [vehicleRegistrationDate, setVehicleRegistrationDate] = useState(null);

  // Check List
  const [checklist, setChecklist] = useState(['']);

  // Additional Information
  const [note, setNote] = useState('');

  // Drivers list
  const [drivers, setDrivers] = useState([]);

  // Documents
  const [selectedMonthlyFile, setSelectedMonthlyFile] = useState();
  const [selectedYearlyFile, setSelectedYearlyFile] = useState();
  const [monthlyInspectionDate, setMonthlyInspectionDate] = useState(null);
  const [yearlyInspectionDate, setYearlyInspectionDate] = useState(null);

  // Repair & Maintenance Record
  const [repairPartName, setRepairPartName] = useState('');
  const [repairReplacementDate, setRepairReplacementDate] = useState(null);
  const [repairMileage, setRepairMileage] = useState('');
  const [repairQuantity, setRepairQuantity] = useState('');
  const [repairCost, setRepairCost] = useState('');
  const [repairLocation, setRepairLocation] = useState('');
  const [repairReceiptFile, setRepairReceiptFile] = useState(null);
  const [repairNextReminder, setRepairNextReminder] = useState('');

  useEffect(() => {
    if (!AuthService.canAddOrEditVechiles()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an Dispatcher or admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    // Fetch drivers list
    DriverService.getAllActiveDrivers('driver', 'active').then(data => {
      setDrivers(data.data || []);
    }).catch(() => {
      setDrivers([]);
    });
  }, []);

  const redirectTo = () => {
    const params = new URLSearchParams(window.location.search);
    const redirect = params.get('redirect');
    if (redirect === 'schedule') {
      navigate(`/trans-routes/schedule`);
    } else {
      redirectToList();
    }
  }

  const redirectToList = () => {
    navigate('/vehicles/list')
  }

  const addItemToArray = () => {
    const arr = [...checklist, ''];
    setChecklist(arr);
  }

  const formatDateForBackend = (date) => {
    if (!date) return '';
    return moment(date).format('MM/DD/YYYY');
  }

  const validateVehicle = () => {
    const errors = [];
    
    // Required fields validation
    if (!vehicleNumber || vehicleNumber.trim() === '') {
      errors.push('Vehicle Number');
    }
    if (!tag || tag.trim() === '') {
      errors.push('License Plate');
    }
    
    if (errors.length > 0) {
      window.alert(`Please fill in the following required fields:\n${errors.join('\n')}`);
      return false;
    }
    return true;
  };

  const saveVehicle = () => {
    if (!validateVehicle()) {
      return;
    }
    
    const data = {
      // Basic Information
      vehicle_number: vehicleNumber,
      responsible_driver: responsibleDriver?.label || '',
      responsible_driver_id: responsibleDriver?.value || '',
      capacity: parseInt(capacity) || 0,
      mileage: parseInt(mileage) || 0,
      make,
      vehicle_model: vehicleModel,
      year,
      vin,
      tag,
      gps_tag: gps,
      ezpass,
      has_lift_equip: hasLiftEquip === 'true',
      fuel_type: fuelType,
      title,
      title_other: titleOther,
      
      // Compliance & Deadlines
      insurance_start_date: formatDateForBackend(insuranceStartDate),
      vehicle_registration_date: formatDateForBackend(vehicleRegistrationDate),
      
      // Check List
      checklist,
      
      // Additional Information
      note,
      
      // System fields
      status: 'active'
    };
    dispatch(createVehicle({data, redirectFun: redirectTo}));
  }

  // Custom styles for react-select
  const selectStyles = {
    control: (baseStyles) => ({
      ...baseStyles,
      minWidth: '200px',
      borderRadius: '8px'
    }),
    indicatorSeparator: () => ({
      display: 'none'
    }),
    dropdownIndicator: (baseStyles) => ({
      ...baseStyles,
      paddingRight: '8px',
      color: '#333',
      '&:hover': {
        color: '#000',
      },
    }),
    valueContainer: (baseStyles) => ({
      ...baseStyles,
      height: '43px',
      padding: '0 8px',
    }),
    input: (baseStyles) => ({
      ...baseStyles,
      margin: '0px',
      padding: '0px',
      height: '30px',
      width: '290px'
    }),
    singleValue: (baseStyles) => ({
      ...baseStyles,
      margin: '0px',
    }),
  };

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item href="/vehicles/list">
            Vehicles Information
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            Create New Vehicle
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Create New Vehicle <button className="btn btn-link btn-sm" onClick={() => {redirectTo()}}>Back</button></h4> 
        </div>
      </div>
      <div className="app-main-content-list-container form-page">
        <div className="app-main-content-list-func-container">
          <Tabs defaultActiveKey="basicInfo" id="vehicles-tab">
            <Tab eventKey="basicInfo" title="Basic Information">
              <h6 className="text-primary">Basic Information</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Vehicle Number <span className="required">*</span></div>
                  <input type="text" placeholder="e.g., 101" value={vehicleNumber} onChange={e => setVehicleNumber(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Responsible Driver</div>
                  <Select
                    value={responsibleDriver}
                    onChange={setResponsibleDriver}
                    options={[{value: '', label: ''}, ...drivers.map(driver => ({
                      value: driver?.id || '',
                      label: driver?.name || '',
                    }))]}
                    styles={selectStyles}
                    placeholder="e.g., John Smith"
                    isClearable
                  />
                </div>
                <div className="me-4">
                  <div className="field-label">Seating Capacity</div>
                  <select value={capacity} onChange={e => setCapacity(e.target.value)}>
                    <option value="">Select...</option>
                    {SEATING_CAPACITY_OPTIONS.map(opt => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
                <div className="me-4">
                  <div className="field-label">Mileage</div>
                  <input type="number" placeholder="e.g., 48000" value={mileage} onChange={e => setMileage(e.target.value)}/>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Make</div>
                  <input type="text" placeholder="e.g., Ford" value={make} onChange={e => setMake(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Model</div>
                  <input type="text" placeholder="e.g., T350" value={vehicleModel} onChange={e => setVehicleModel(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Year</div>
                  <input type="text" placeholder="e.g., 2018" value={year} onChange={e => setYear(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">VIN Number</div>
                  <input type="text" placeholder="e.g., 1FBAX2CM9KKA34959" value={vin} onChange={e => setVin(e.target.value)}/>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">License Plate <span className="required">*</span></div>
                  <input type="text" placeholder="e.g., 91579HT" value={tag} onChange={e => setTag(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">GPS ID</div>
                  <input type="text" placeholder="e.g., 609671" value={gps} onChange={e => setGps(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">E-ZPass</div>
                  <input type="text" placeholder="e.g., NY12345" value={ezpass} onChange={e => setEzpass(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Lift Equipped</div>
                  <select value={hasLiftEquip} onChange={e => setHasLiftEquip(e.target.value)}>
                    <option value="">Select...</option>
                    {Object.keys(LIFT_EQUIPPED).map(key => (
                      <option key={key} value={LIFT_EQUIPPED[key]}>{LIFT_EQUIPPED_TEXT[LIFT_EQUIPPED[key]]}</option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Fuel Type</div>
                  <select value={fuelType} onChange={e => setFuelType(e.target.value)}>
                    <option value="">Select...</option>
                    {Object.keys(FUEL_TYPE).map(key => (
                      <option key={key} value={FUEL_TYPE[key]}>{FUEL_TYPE_TEXT[FUEL_TYPE[key]]}</option>
                    ))}
                  </select>
                </div>
                <div className="me-4">
                  <div className="field-label">Title</div>
                  <select value={title} onChange={e => setTitle(e.target.value)}>
                    <option value="">Select...</option>
                    {Object.keys(VEHICLE_TITLE).map(key => (
                      <option key={key} value={VEHICLE_TITLE[key]}>{VEHICLE_TITLE_TEXT[VEHICLE_TITLE[key]]}</option>
                    ))}
                  </select>
                </div>
                {title === 'other' && (
                  <div className="me-4">
                    <div className="field-label">Title (Other)</div>
                    <input type="text" placeholder="Please specify..." value={titleOther} onChange={e => setTitleOther(e.target.value)}/>
                  </div>
                )}
              </div>

              <h6 className="text-primary">Check List</h6>
              <div className="app-main-content-fields-section column">
                {checklist.map((item, index) => (
                  <div className="mb-4" key={index}>
                    <input type="text" placeholder="e.g., Tire pressure" value={item} onChange={(e) => setChecklist([...checklist].map((a, index1) => {if (index1 === index) {return e.target.value;} return a;}))}/>
                    <button className="btn btn-link btn-sm" onClick={(e) => setChecklist([...checklist].filter((value, index1) => index1 != index))}>Remove</button>
                  </div>
                ))}
                <button className="btn btn-link" onClick={() => addItemToArray()}>+Add New Item</button>
              </div>

              <h6 className="text-primary">Additional Information</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Notes and Attachments</div>
                  <textarea placeholder="e.g., Vehicle assigned to Route A" value={note} onChange={e => setNote(e.target.value)} rows={4} style={{width: '400px'}}/>
                </div>
              </div>

              {error && <div className="col-md-12 mb-4 alert alert-danger" role="alert">
                {error}
              </div>}
              <div className="list row mb-5">
                <div className="col-md-12 col-sm-12 col-xs-12">
                  <button className="btn btn-default btn-sm float-right" onClick={() => redirectTo()}> Cancel </button>
                  <button className="btn btn-primary btn-sm float-right" onClick={() => saveVehicle()}> Save </button>
                </div>
              </div>
            </Tab>

            <Tab eventKey="complianceDeadlines" title="Compliance & Deadlines">
              <h6 className="text-primary">Compliance & Deadlines</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Insurance Expiration Date</div>
                  <DatePicker 
                    selected={insuranceStartDate} 
                    onChange={(date) => setInsuranceStartDate(date)}
                    dateFormat="MM/dd/yyyy"
                    placeholderText="e.g., 03/01/2024"
                    className="form-control"
                  />
                </div>
                <div className="me-4">
                  <div className="field-label">Vehicle Registration Date</div>
                  <DatePicker 
                    selected={vehicleRegistrationDate} 
                    onChange={(date) => setVehicleRegistrationDate(date)}
                    dateFormat="MM/dd/yyyy"
                    placeholderText="e.g., 03/01/2024"
                    className="form-control"
                  />
                </div>
              </div>

              {error && <div className="col-md-12 mb-4 alert alert-danger" role="alert">
                {error}
              </div>}
              <div className="list row mb-5">
                <div className="col-md-12 col-sm-12 col-xs-12">
                  <button className="btn btn-default btn-sm float-right" onClick={() => redirectTo()}> Cancel </button>
                  <button className="btn btn-primary btn-sm float-right" onClick={() => saveVehicle()}> Save </button>
                </div>
              </div>
            </Tab>

            <Tab eventKey="documents" title="Documents & Records">
              <h6 className="text-primary">Yearly Inspection</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Yearly Inspection Date</div>
                  <DatePicker 
                    selected={yearlyInspectionDate} 
                    onChange={(date) => setYearlyInspectionDate(date)}
                    dateFormat="MM/dd/yyyy"
                    placeholderText="e.g., 03/01/2024"
                    className="form-control"
                  />
                </div>
                <div className="me-4">
                  <div className="field-label">Yearly Inspection File</div>
                  <label className="custom-file-upload">
                    <Upload width={20} color={"#fff"} className="me-2"></Upload> Upload
                    <input type="file" onChange={(e) => setSelectedYearlyFile(e.target.files[0])}/>
                  </label>
                  <div className="file-name">{selectedYearlyFile?.name}</div>
                </div>
              </div>

              <h6 className="text-primary">Monthly Inspection</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Monthly Inspection Date</div>
                  <DatePicker 
                    selected={monthlyInspectionDate} 
                    onChange={(date) => setMonthlyInspectionDate(date)}
                    dateFormat="MM/dd/yyyy"
                    placeholderText="e.g., 03/01/2024"
                    className="form-control"
                  />
                </div>
                <div className="me-4">
                  <div className="field-label">Monthly Inspection File</div>
                  <label className="custom-file-upload">
                    <Upload width={20} color={"#fff"} className="me-2"></Upload> Upload
                    <input type="file" onChange={(e) => setSelectedMonthlyFile(e.target.files[0])}/>
                  </label>
                  <div className="file-name">{selectedMonthlyFile?.name}</div>
                </div>
              </div>

              <h6 className="text-primary">Repair & Maintenance Record</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Part Name</div>
                  <select value={repairPartName} onChange={e => setRepairPartName(e.target.value)}>
                    <option value="">Select...</option>
                    {Object.keys(REPAIR_PART_NAME).map(key => (
                      <option key={key} value={REPAIR_PART_NAME[key]}>{REPAIR_PART_NAME_TEXT[REPAIR_PART_NAME[key]]}</option>
                    ))}
                  </select>
                </div>
                <div className="me-4">
                  <div className="field-label">Replacement Date</div>
                  <DatePicker 
                    selected={repairReplacementDate} 
                    onChange={(date) => setRepairReplacementDate(date)}
                    dateFormat="MM/dd/yyyy"
                    placeholderText="e.g., 03/01/2024"
                    className="form-control"
                  />
                </div>
                <div className="me-4">
                  <div className="field-label">Mileage at Replacement</div>
                  <input type="text" placeholder="e.g., 48,000" value={repairMileage} onChange={e => setRepairMileage(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Quantity</div>
                  <select value={repairQuantity} onChange={e => setRepairQuantity(e.target.value)}>
                    <option value="">Select...</option>
                    {QUANTITY_OPTIONS.map(opt => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
                  <div className="field-label">Cost</div>
                  <input type="text" placeholder="e.g., $250.00" value={repairCost} onChange={e => setRepairCost(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Location</div>
                  <input type="text" placeholder="e.g., Rockville Auto Center" value={repairLocation} onChange={e => setRepairLocation(e.target.value)}/>
                </div>
                <div className="me-4">
                  <div className="field-label">Receipt Upload</div>
                  <label className="custom-file-upload">
                    <Upload width={20} color={"#fff"} className="me-2"></Upload> Upload
                    <input type="file" onChange={(e) => setRepairReceiptFile(e.target.files[0])}/>
                  </label>
                  <div className="file-name">{repairReceiptFile?.name}</div>
                </div>
                <div className="me-4">
                  <div className="field-label">Next Replacement Reminder</div>
                  <input type="text" placeholder="e.g., 78,000" value={repairNextReminder} onChange={e => setRepairNextReminder(e.target.value)}/>
                </div>
              </div>

              {error && <div className="col-md-12 mb-4 alert alert-danger" role="alert">
                {error}
              </div>}
              <div className="list row mb-5">
                <div className="col-md-12 col-sm-12 col-xs-12">
                  <button className="btn btn-default btn-sm float-right" onClick={() => redirectTo()}> Cancel </button>
                  <button className="btn btn-primary btn-sm float-right" onClick={() => saveVehicle()}> Save </button>
                </div>
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>
    </>
  );
};

export default CreateVehicle;
