import React, { useState, useEffect } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { AuthService, VehicleService } from "../../services";
import { Upload } from "react-bootstrap-icons";
import { Breadcrumb } from "react-bootstrap";
import DatePicker from "react-datepicker";
import moment from "moment";

const EditVehicleInspection = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const inspectionType = params.type;
  const isYearly = inspectionType === 'yearly';
  const title = isYearly ? 'Yearly Inspection' : 'Monthly Inspection';

  const [currentVehicle, setCurrentVehicle] = useState(null);
  const [inspectionDate, setInspectionDate] = useState(null);
  const [selectedFile, setSelectedFile] = useState(null);
  const [currentFileName, setCurrentFileName] = useState('');

  useEffect(() => {
    if (!AuthService.canAddOrEditVechiles()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page.');
      AuthService.logout();
      navigate('/login');
    }
    VehicleService.getVehicle(params.id).then((data) => {
      setCurrentVehicle(data.data);
    });

    const fileName = searchParams.get('fileName');
    const dateStr = searchParams.get('date');
    if (fileName) setCurrentFileName(decodeURIComponent(fileName));
    if (dateStr) {
      const parsed = moment(dateStr, 'MM/DD/YYYY');
      if (parsed.isValid()) setInspectionDate(parsed.toDate());
    }
  }, []);

  const handleSave = () => {
    if (!inspectionDate) {
      window.alert('Please select an inspection date.');
      return;
    }
    if (selectedFile) {
      const formData = new FormData();
      formData.append('file', selectedFile);
      const fileType = isYearly ? 'yearlyInspection' : 'monthlyInspection';
      VehicleService.uploadVechileFile(formData, currentVehicle.id, currentVehicle.vehicle_number, fileType, inspectionDate).then(() => {
        goBack();
      });
    } else {
      goBack();
    }
  };

  const goBack = () => {
    navigate(`/vehicles/${params.id}?tab=documents`);
  };

  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 href={`/vehicles/${params.id}?tab=documents`}>View Vehicle Information</Breadcrumb.Item>
          <Breadcrumb.Item active>Edit {title}</Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Edit {title} <button className="btn btn-link btn-sm" onClick={goBack}>Back</button></h4>
        </div>
      </div>
      <div className="app-main-content-list-container form-page">
        <div className="app-main-content-list-func-container">
          <h6 className="text-primary">{title}</h6>

          {currentFileName && (
            <div className="app-main-content-fields-section mb-3">
              <div className="field-body">
                <div className="field-label">Current File</div>
                <div className="field-value">{currentFileName}</div>
              </div>
            </div>
          )}

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

          <div className="list row mb-5 mt-3">
            <div className="col-md-12 col-sm-12 col-xs-12">
              <button className="btn btn-default btn-sm float-right" onClick={goBack}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={handleSave}> Save </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default EditVehicleInspection;
